variable not defined

Here is my play book, i am trying to check the id’s using wildcards like ora****
I am getting variable not defined

The variable *id* was registered in a loop. You need the attribute
*results*. (Take a look at *id*.)

Try

    - debug:
        msg: "{{ id.results|map(attribute='stdout')|list }}"

Notes:

* Use *getent* instead of reading /etc/passwd* on your own
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/getent_module.html

* Use *command* instead of *shell*, *loop* instead of *with_items*,
  and *userid.stdout_lines* instead of *userid.stdout.split('\n')*

    - command: "id {{ item }}"
      register: id
      loop: "{{ userid.stdout_lines }}"

You can make your shell command much more efficient. No need to use cat and grep.

awk -F: ‘$1 ~ /^ora/ { print $1 }’ /etc/passwd

This will find and print all usernames that begin “ora”.

  • shell: “awk -F: ‘$1 ~ /^ora/ { print $1 }’ /etc/passwd”
    register: userid
    ignore_errors: true

Then you can look at userid.results.stdout_lines (as a list) to see the list of usernames.

  • debug: var=userid.results.stdout_lines

Walter

Thank you Vladimir Botka,

This worked like a charm.

  • debug:
    msg: “{{ id.results|map(attribute=‘stdout’)|list }}”

Try

- hosts: node1.example.com
  gather_facts: false
  vars:
    users: "{{ getent_passwd.keys()|list }}"
  tasks:
    - getent:
        database: passwd
    - command: "id {{ item }}"
      register: id
      loop: "{{ users|select('match', '^user.*$') }}"
    - debug:
        msg: "{{ id.results|map(attribute='stdout')|list }}"

Notes:

* The module *getent* stores the data automagically. In the case of
  *passwd* the dictionary will be *getent_passwd*

* Put the declaration of *users* into vars

* Fit the regex to your needs and iterate the selected users

* The debug of the results is the same as before

* Take a look at *getent_passwd*

* The same way you can get the content of /etc/group in the
  dictionary *getent_group*

* You can create any structure you like when you have both
  dictionaries *getent_passwd* and *getent_group*

You all are making this way too hard. You don’t even have to ignore errors with this task.

  • shell: “awk -F: ‘$1 ~ /^ora/ { print $1 }’ /etc/passwd”
    register: userids

  • debug: var=userids.results.stdout_lines
    when: userid.results.stdout_lines

Then ‘when’ condition will be true only when the list is longer than zero length.

Walter