A collection of code snippets for solving different problems in Ansible.
This works by first getting the inventory hostnames of all members in the database
group and then extracting the variable ansible_host
for each one of them.
database_servers_ips: "{{ groups.database | map('extract', hostvars, 'ansible_host') }}"
-> ["10.0.0.1", "10.0.0.2"]
In this example we are only interested in the username of each user. We extract them from the users
dictionary using the map
filter and give it the name of the attribute we want to extract.
users:
- username: bob
password: hunter42
- username: alice
password: 24retnuh
usernames: "{{ users | map(attribute='username') }}"
-> ["bob", "alice"]
In this example we want to get only the interfaces starting with eth
from the interfaces
list. We do this by using the select
filter and provide it with 2 arguments; the test ('regex') and the test argument ('^eth').
interfaces:
- eth1
- eth2
- ens18
eth_interfaces: "{{ interfaces | select('regex', '^eth') }}"
-> ["eth1", "eth2"]
In this example we want to filter the users
dictionary and only get the users that are sysadmins. We use the selectattr
filter and provide it with the attribute ('role') that we want to filter on, the test ('eq') to apply and the test argument ('sysadmin').
users:
- username: bob
role: sysadmin
- username: alice
role: sysadmin
- username: cedric
role: manager
syadmins: "{{ users | selectattr('role', 'eq', 'sysadmin') }}"
-> [{"role": "sysadmin", "username": "bob"}, {"role": "sysadmin", "username": "alice"}]