Scenario:
Server will have no user defined, or user1 or user2 (but not both).
`
- name: Discover sudo users
getent:
database: passwd
key: “{{item}}”
register: username
when: result|succeeded
with_items:
- user1
- user2
`
I am wondering if I am even approaching this right? It doesn’t seem quite right to me. I don’t think I am using the when statement correctly here. Basically, I want to set the username variable to user1 or user2 if defined.
You are using the variable result in when that doesn't exist.
Register will register everything not only when the when: statement is true, so this will not work.
You could do something like this
- name: Get passwd as facts
getent:
database: passwd
- name: Discover sudo users
set_fact:
username: '{{ item }}'
when: getent_passwd[item] is defined
with_items:
- user1
- user2
Kai,
This works perfectly. Thank you. I have a follow-up questions. Perhaps you can explain it to me or point me to some docs that explain it
In this line:
getent_passwd[item] is defined
Why to we [bracket] item? What does this do? imply? Is it similar to {{item}}?
I can try, I hope it's understandable.
And yes item in when is the same as {{ item }}, but in when {{ }} is implied so you cant use {{ }} in when.
This is how it works:
The module getent create a variable call getent_passwd, this is a dictionary where each user on the host have a entry.
So you have potential getent['user1'] or getent['user2'] defined.
So we need to check if one of them exist and with with_items we loop over user1 and user2.
In the first iteration item variable is equal to user1, so getent[item] will be the same as getent['user1'].
In when we check if that variable exist and if so then execute set_fact.
Next item = user2 and everything repeats.
I do understand it now. Thank you.