Skip to content

Instantly share code, notes, and snippets.

@oskaralmlov
Last active September 30, 2021 17:00
Show Gist options
  • Save oskaralmlov/952722b0015dabf8b90709596485db17 to your computer and use it in GitHub Desktop.
Save oskaralmlov/952722b0015dabf8b90709596485db17 to your computer and use it in GitHub Desktop.

Ansible snippets

A collection of code snippets for solving different problems in Ansible.

Get the IP address of each host in an inventory group:

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"]

Extracting attributes from dictionaries

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"]

Filtering a list based on criteria

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"]

Filtering a dictionary based on criteria

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"}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment