ansibleansible-facts

Run ansible task if the client is not in ad domain


Currently I am creating a playbook to automate our initial server setup for ubuntu server 20.04.4 LTS. I've created the following simple task:

  - name: Join Domain domain.group
    expect:
      command: realm join -U domainuser domain.group
      responses:
        Password for *: "{{domain_join_pw}}"

This works just fine, but once the task is done and I run the play again it gets interrupted with the following message:

["realm: Already joined to this domain"]

Is there a way to check if the client is already in the domain and only run the task when it's not?

I tried the ansible_fqdn and ansible_domain fact like this:

  - name: Join Domain domain.group
    expect:
      command: realm join -U domainuser domain.group
      responses:
        Password for *: "{{domain_join_pw}}"
    when: ansible_fqdn != "domain.group"

I am quite new to Ansible, I think it's not hard to do but can't find out how. Thanks for every awnser.


Solution

  • It is assumed that the domain is registered within a variable.

    DOMAIN: "domain.group"
    

    You could use the following generic and not yet tested example to enhance your use case.

    - name: Check if system is already domain joined
      shell:
        cmd: realm list | grep {{ DOMAIN }}
      changed_when: false
      check_mode: false
      register: domain_joined
      failed_when: domain_joined.rc !=0 and domain_joined.rc !=1
    

    and let tasks later run only when not domain joined, in example

    when: not domain_joined | bool
    

    ... currently I have domain joined systems only, therefore I could not run a full test with a not joined system yet.

    You may have also a look into the command

    sssctl domain-status ${DOMAIN}
    Online status: Online
    
    Active servers:
    AD Global Catalog: not connected
    AD Domain Controller: ad.example.com
    
    Discovered AD Global Catalog servers:
    None so far.
    
    Discovered AD Domain Controller servers:
    - ad.example.com
    

    or {{ DOMAIN }} when used from within Ansible, check the output as well how to filter and register the result for further usage.