Checking if a user exists

Hi all

Due to separation of concerns, our Ansible scripts cannot create the users we require for our scripts - this is done by another team after a server is created and prior to our run.

How can we check that the user/groups required have actually been created as part of our Ansible pre-req scripts?

We can use stat for checking if directories/folders exist but is there an equivalent for users/groups?

thanks

Hi,

You could use the command module, e.g.:

  • name: Check for users
    with_items:
  • foo
  • bar
    changed_when: false
    command: grep {{ item }} -q /etc/passwd

Thanks, I’ll check it out.

OK - I’ve had success with this insofar as I can see the success/failure for the grep result (my host is Solaris so had to change it to grep -q {{ item }} /etc/passwd)

but how can I register the result so that I can write a debug message if one or more of my required users is not present?

thanks

There is the getent module for this:

  • getent: database=passwd key=

Hi,

Yes but how can we test the result?

There is no common field for the OK result and the NOT OK result.

As for example, status or exists or true, etc.

For an existing user:
TASK [debug msg={{ ww }}] ************************************************************************************
ok: [node1] => {
“msg”: {
“ansible_facts”: {
“getent_passwd”: {
“devops”: [
“x”,
“600”,
“600”,
“”,
“/home/devops”,
“/bin/bash”
]
}
},
“changed”: false
}
}

For a not existing user :
TASK [debug msg={{ ww }}] ************************************************************************************
ok: [node1] => {
“msg”: {
“changed”: false,
“failed”: true,
“msg”: “One or more supplied key could not be found in the database.”
}
}

when you make the conditional like for example:

  • fail: msg=“user xxxx doesn’t exists”
    when: ww.failed

But when the user exists , it also reports an error:
fatal: [node1]: FAILED! => {“failed”: true, “msg”: “The conditional check ‘ww.failed’ failed. The error was: error while evaluating conditional (ww.failed): ‘dict object’ has no attribute ‘failed’\n\nThe error appears to have been in ‘/home/ansible/testeuser.yml’: line 10, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n - debug: msg={{ getent_passwd }}\n - fail: msg="tasks5 fail in server {{ inventory_hostname }}."\n ^ here\nWe could be wrong, but this one looks like it might be an issue with\nmissing quotes. Always quote template expression brackets when they\nstart a value. For instance:\n\n with_items:\n - {{ foo }}\n\nShould be written as:\n\n with_items:\n - "{{ foo }}"\n”}

segunda-feira, 25 de Abril de 2016 às 15:17:59 UTC+1, Brian Coca escreveu:

Wrong test, this should work either way:

- fail: msg="user xxxx doesn't exists"
   when: ww is failed