Ansible : conditional user creation


Ansible can be a slippery fish to grab, but I’m slowly and steadily getting a grip. Here’s my Ansible repository with a handful of roles for post-install server configuration:

I’d like to add a user_setup role for basic post-install user setup. Here’s what it should do:

  • IF there is no user with an UID of 1000

  • AND IF there is no user microlinux on the system

  • THEN create user microlinux with and UID of 1000

I’ve already got the part where I set the password and group membership, which looks like this:

- name: "Configure admin user: microlinux"
    name: microlinux
    groups: wheel
    password: >-
      {{passwd_microlinux | 
        password_hash('sha512', 65534   |
        random(seed=inventory_hostname) |
        string) }}

What I’m missing now is the two conditions above in Ansible syntax. How would I express these ?



Ansible can “getent passwd”. Alas, it can look like failure:

  - name: Get uid info
      database: passwd
      key: 1000
    ignore_errors: true
    register: has_num

  - name: Get name info
      database: passwd
      key: microlinux
    ignore_errors: true
    register: has_name

  - ansible.builtin.debug:
      msg: "Neither name nor uid exists"
    - has_name.failed
    - has_num.failed
1 Like