I’m trying to achieve to lookup all variables in my Ansible configuration which end with "password"
in their variables names. Then I would like to access the values of the password variables and check their character length.
I can lookup all my password variables with lookup('varnames', 'password')
but then how do I loop over the result list and get their values?
I tried:
- name: Show passwords
ansible.builtin.debug:
msg: "{{ item }}"
with_items: "{{ lookup('ansible.builtin.varnames', 'password') }}"
But what I am getting is the variable name itself:
ok: [host1] => (item=test_password,test_password_default,admin_password,ldap_password) => { "msg": "test_password,test_password_default,admin_password,ldap_password" }
I would like to get the variable values instead and then do an assertion of the character length.
By default the varnames
lookup produces a single comma-delimited string. Add wantlist=true
:
- name: Show passwords
ansible.builtin.debug:
msg: "{{ item }}"
with_items: "{{ lookup('ansible.builtin.varnames', 'password', wantlist=true) }}"
Or use query
instead of lookup
(query
always returns a list):
- name: Show passwords
ansible.builtin.debug:
msg: "{{ item }}"
with_items: "{{ query('ansible.builtin.varnames', 'password') }}"
(Both of the above solutions are documeted here).
Lastly, you can use the vars
lookup to get the value of the variable:
- name: Show passwords
ansible.builtin.debug:
msg: "{{ item }}: {{ lookup('vars', item) }}"
with_items: "{{ query('ansible.builtin.varnames', 'password') }}"
Note that the vars
lookup only returns "top-level variable names". If you actually want fact values, you may need to look them up via hostvars
instead.