In the templates from the previous lesson and in the Aurora inventory you've already used filters without studying them: join for the groups in the local facts, length in pg_hba.conf, default(omit) in the team users, dict2items in the static pages, and an expression with map('extract', hostvars, 'ansible_host') that builds the list of PostgreSQL clients. Filters transform data: they clean up text, filter lists, combine dictionaries, convert formats. Lookups do something else: they bring in data from outside Ansible (a file, an environment variable, the output of a command, a generated password), and they do it on the control node. Mastering both is what lets the inventory and the roles express the logic of the infrastructure without filling up with set_fact and command tasks. In this lesson you'll go through the most useful filters with Aurora examples, tests, the main lookups and the difference between lookup and query, and you'll prepare two pieces you'll use very soon: the load balancer's server list and the PostgreSQL passwords.
Contents
- What a filter is
- A playbook for experimenting
- Default and mandatory values:
default,omitandmandatory - Text filters
- List filters
map,select,rejectandselectattr: transforming and filtering lists- Dictionary filters:
combine,dict2itemsanditems2dict - Type and format conversion
- Encoding, hashes and networks
ternary: choosing between two values- Tests
- Practice: the load balancer's server list
- What a lookup is (and where it runs)
- The most useful lookups
lookupversusquery- Practice: generating passwords with the
passwordlookup
- What a filter is
A filter receives a value from the left of the vertical bar | and returns another one:
{{ aurora_domain | upper }} {# AURORA-STORE.EXAMPLE #}
{{ common_packages | join(', ') }} {# htop, curl, vim, tree #}
{{ aurora_domain | replace('.example', '.com') | upper }} {# chained #}- Some filters accept arguments in parentheses:
join(', '). - They can be chained: each one receives the result of the previous one, from left to right.
- They work anywhere there's Jinja: templates, inventory variables, task parameters,
when(without{{ }}). - There are two families: Jinja2 filters (
upper,join,map,select,default…) and the ones Ansible adds (combine,dict2items,regex_replace,to_nice_yaml,password_hash…). Ansible's have a full name (ansible.builtin.combine), and collections add more (community.general.*,ansible.utils.*). As with modules, you can write the FQCN; in practice, the short name is almost always used foransible.builtinfilters.
To see the documentation for an Ansible filter:
- A playbook for experimenting
The quickest way to try out filters is a play against localhost that only uses debug. Create the file demo-filters.yml in ~/aurora-infra (it's only for testing: you'll delete it at the end):
---
# demo-filters.yml (for testing only: delete it when you finish the lesson)
- name: Experiment with filters and lookups
hosts: localhost
gather_facts: false
vars:
team:
- name: deploy
comment: Aurora Store deployments
- name: laura
comment: Laura Gómez - Development
admin: true
- name: marc
comment: Marc Soler - Operations
admin: true
- name: jordi
comment: Former contributor
state: absent
packages: [htop, curl, vim, tree, curl]
domain: " Aurora-Store.Example "
tasks:
- name: Try out a filter
ansible.builtin.debug:
msg: "{{ packages | unique | sort }}"TASK [Try out a filter] ********************************************************
ok: [localhost] =>
msg:
- curl
- htop
- tree
- vimhosts: localhostuses the implicit host (Lesson 2.1): there's no need to add it to the inventory, and it doesn't connect over SSH.- Even though the play runs on
localhost, the inventory is loaded:groups['webservers']andhostvars['web1']work, which lets you try out expressions with real Aurora data.
For each example in the lesson, change the task's msg (or add tasks) and run it again.
- Default and mandatory values:
default, omit and mandatory
default, omit and mandatory| Filter | Example | Result |
|---|---|---|
default(value) |
{{ item.state | default('present') }} |
The value of item.state, or present if it isn't defined |
default(value, true) |
{{ name | default('anonymous', true) }} |
Also replaces empty or false values ('', 0, false) |
default(omit) |
comment: "{{ item.comment | default(omit) }}" |
If it isn't defined, the parameter isn't sent to the module |
mandatory |
{{ aurora_app_db_host | mandatory }} |
Fails with a clear error if it isn't defined |
mandatory(msg) |
{{ x | mandatory('Define x in the inventory') }} |
The same, with your message |
You already know the first three from the Aurora roles (common_users). default(omit) deserves a clarification: omit is a special value that Ansible recognizes in module parameters and that is equivalent to not having written the parameter, so the module uses its own default value. Outside a parameter (in a msg, in a template) it makes no sense.
mandatory is useful when a mandatory variable is used in a playbook or a template and you don't have argument_specs to validate it. In the Aurora roles, the argument specification already does that job (Lesson 4.6), so you don't need it.
- Text filters
| Filter | Example with domain = " Aurora-Store.Example " |
Result |
|---|---|---|
trim |
domain | trim |
Aurora-Store.Example |
lower / upper |
domain | trim | lower |
aurora-store.example |
capitalize / title |
'aurora store' | title |
Aurora Store |
replace(a, b) |
domain | trim | replace('.Example', '.com') |
Aurora-Store.com |
split(sep) |
'web1,web2' | split(',') |
['web1', 'web2'] |
regex_replace(pattern, replacement) |
'aurora-store.example' | regex_replace('\\.example$', '.com') |
aurora-store.com |
regex_search(pattern) |
'nginx version: nginx/1.24.0 (Ubuntu)' | regex_search('[0-9.]+') |
1.24.0 |
length |
'aurora' | length |
6 |
Two details about regular expressions:
- Inside a double-quoted YAML string, the backslash is escaped:
'\\.example'. If you use single quotes in YAML, there's no need:'{{ x | regex_replace("\.example$", ".com") }}'. When in doubt, try it in the experimentation playbook. regex_searchreturns the first match (or nothing if there's none). With groups,regex_search('nginx/([0-9.]+)', '\\1')returns a list with the captured group.
A real example: in Lesson 3.7, webservers.yml showed the full output of nginx -v (nginx version: nginx/1.24.0 (Ubuntu)). With regex_search you could keep just the number: {{ nginx_version_cmd.stderr | regex_search('[0-9]+\\.[0-9]+\\.[0-9]+') }}.
- List filters
With packages = [htop, curl, vim, tree, curl]:
| Filter | Example | Result |
|---|---|---|
length |
packages | length |
5 |
first / last |
packages | first |
htop |
unique |
packages | unique |
[htop, curl, vim, tree] |
sort |
packages | unique | sort |
[curl, htop, tree, vim] |
join(sep) |
packages | unique | join(' ') |
htop curl vim tree |
min / max |
[3, 1, 2] | max |
3 |
union(other) |
['a'] | union(['b', 'a']) |
[a, b] |
difference(other) |
packages | difference(['curl']) |
[htop, vim, tree] |
intersect(other) |
packages | intersect(['vim', 'git']) |
[vim] |
flatten |
[[1, 2], [3]] | flatten |
[1, 2, 3] |
zip(other) |
['a', 'b'] | zip([1, 2]) |
[[a, 1], [b, 2]] |
sort has an important use in templates: if you generate a list whose order isn't guaranteed (for example, by combining groups), sort it. If the order changed between runs, the file would change and notify handlers for no reason.
map, select, reject and selectattr: transforming and filtering lists
map, select, reject and selectattr: transforming and filtering listsThese filters work on each element of a list. They're the most powerful tool for manipulating data without loops.
| Filter | What it does | Example with team |
Result |
|---|---|---|---|
map(attribute='x') |
Extracts an attribute from each dictionary | team | map(attribute='name') |
[deploy, laura, marc, jordi] |
map('filter') |
Applies a filter to each element | ['a', 'b'] | map('upper') |
[A, B] |
selectattr('x') |
Keeps the elements whose attribute is true | team | selectattr('admin', 'defined') |
laura and marc |
selectattr('x', 'test', value) |
Keeps the ones that pass a test | team | selectattr('state', 'defined') | selectattr('state', 'equalto', 'absent') |
jordi |
rejectattr(...) |
The opposite of selectattr |
team | rejectattr('state', 'defined') |
deploy, laura, marc |
select('test') |
Keeps the elements that pass a test | packages | select('match', 't') |
[tree] |
reject('test') |
Removes the ones that pass a test | packages | reject('equalto', 'curl') |
[htop, vim, tree] |
The tests that select, selectattr and friends receive are the ones in section 11: defined, equalto (or ==), match, search, in…
A complete example: the names of the active administrators, separated by commas.
- name: Active administrators
ansible.builtin.debug:
msg: >-
{{ team
| selectattr('admin', 'defined') | selectattr('admin')
| rejectattr('state', 'defined')
| map(attribute='name') | join(', ') }}Read it as a pipeline: from team, keep the ones that have admin defined and true, remove the ones that have state defined (in Aurora, only absent users have it), extract the name and join with commas.
map('extract'): looking up in another dictionary
map('extract', container) takes each element of the list as a key and returns the value for that key in the container. With a third argument, it also extracts a key from that value. That's exactly what the Aurora inventory does in inventory/group_vars/dbservers.yml:
postgresql_hba_clients: "{{ groups['webservers'] | map('extract', hostvars, 'ansible_host') | list }}"Step by step:
| Step | Value |
|---|---|
groups['webservers'] |
['web1', 'web2'] |
map('extract', hostvars, 'ansible_host') |
For each name, hostvars[name]['ansible_host'] |
list |
['192.168.56.11', '192.168.56.12'] |
Why the final list? map, select and their relatives return a generator (a sequence that is computed as you iterate over it), not a list. In a template or in a loop it works the same, but if you store the result in a variable or display it, convert it with list to get a real list.
- Dictionary filters:
combine, dict2items and items2dict
combine, dict2items and items2dict7.1. combine
combine merges dictionaries; if a key is in both, the one on the right wins:
With nested dictionaries, by default the key on the right replaces the whole subdictionary. With recursive=true, it also merges the inner levels:
{{ {'db': {'host': 'db1', 'port': 5432}} | combine({'db': {'port': 5433}}, recursive=true) }}
{# {'db': {'host': 'db1', 'port': 5433}} #}A typical use is having some base values and some exceptions per environment, without repeating the whole dictionary. Remember, though, that in Aurora the preferred way to vary data is the inventory (group_vars/host_vars): combine is for when you really need to merge structures.
7.2. dict2items and items2dict
You already used dict2items to iterate over aurora_app_static_pages with loop (Lesson 3.6):
| Filter | Input | Output |
|---|---|---|
dict2items |
{'robots.txt': '...', 'status.html': '...'} |
[{'key': 'robots.txt', 'value': '...'}, {'key': 'status.html', 'value': '...'}] |
items2dict |
[{'key': 'a', 'value': 1}] |
{'a': 1} |
Both accept key_name and value_name to work with other names: items2dict(key_name='name', value_name='comment') converts the team list into a dictionary {deploy: 'Aurora Store deployments', laura: ...}.
7.3. dict() from pairs
Jinja's dict() function builds a dictionary from a list of [key, value] pairs, like the ones zip generates:
The dict + zip combination will be the key to section 12.
- Type and format conversion
| Filter | Example | Result |
|---|---|---|
int |
'80' | int |
80 (number) |
float |
'1.5' | float |
1.5 |
bool |
'yes' | bool, 'false' | bool |
true, false |
string |
80 | string |
'80' |
list |
packages | unique | list |
A real list (not a generator) |
to_json / to_nice_json |
team | to_nice_json(indent=2) |
JSON text (readable with nice) |
to_yaml / to_nice_yaml |
team | to_nice_yaml(indent=2) |
YAML text |
from_json / from_yaml |
output.stdout | from_json |
Data structure |
When you need them:
intandboolto compare values that may arrive as text: everything you pass with-e key=valueis text (Lesson 3.5), so-e nginx_port=8080and a comparisonnginx_port > 1024neednginx_port | int.boolis the usual companion of switches:when: aurora_maintenance | default(false) | bool.to_nice_yaml/to_nice_jsonto generate configuration files in those formats from a variable, in a one-line template:{{ aurora_app_settings | to_nice_yaml }}.from_jsonto take advantage of commands that return JSON. For example,ip -j addron the servers:
- name: Get the IPv4 addresses as JSON
ansible.builtin.command:
cmd: ip -j -4 addr show
register: network
changed_when: false
- name: Show the interface names
ansible.builtin.debug:
msg: "{{ network.stdout | from_json | map(attribute='ifname') | list }}"On an Aurora server it would show something like ['lo', 'eth0', 'eth1'] (the names depend on the Vagrant image). This is the general pattern: if a tool offers JSON output, use it with from_json instead of slicing text with regular expressions.
- Encoding, hashes and networks
| Filter | Example | What for |
|---|---|---|
b64encode / b64decode |
'aurora' | b64encode → YXVyb3Jh |
Encoding or decoding Base64 |
hash('sha256') |
'aurora' | hash('sha256') |
Computing a hash (checksums, identifiers) |
password_hash('sha512') |
'S3cret' | password_hash('sha512') |
A hashed password for the user module |
quote |
name | quote |
Protecting a value for use in shell |
ansible.utils.ipaddr |
'192.168.56.11/24' | ansible.utils.ipaddr('network') |
Network calculations (requires the ansible.utils collection and the netaddr library) |
b64decode shows up mainly with the ansible.builtin.slurp module, which reads a remote file and returns it in Base64:
- name: Read the store's connection details
ansible.builtin.slurp:
src: /etc/aurora/db.conf
register: aurora_db_conf
- name: Show its content
ansible.builtin.debug:
msg: "{{ aurora_db_conf.content | b64decode }}"password_hash is used to give a system user a password (the user module expects the value already hashed, not in plain text). The Aurora team users don't have a password: they'll log in with SSH keys, and managing them securely is covered in Lesson 9.2. If you get an error mentioning passlib when using it, install that library in the Ansible environment (pipx inject ansible passlib, Lesson 1.2).
ipaddr is just a mention: network and subnet calculations are common in network and cloud automation (Lesson 8.4), but Aurora doesn't need them for now.
ternary: choosing between two values
ternary: choosing between two valuesternary(if_true, if_false) applied to a condition:
It's equivalent to a one-line if/else. There's also the Jinja form {{ 'warning' if aurora_env == 'production' else 'debug' }}; use whichever you find more readable, but be consistent.
- Tests
Tests return true or false and are used with is (or is not). You already know several from when and register:
| Test | Example | True if… |
|---|---|---|
defined / undefined |
aurora_app_db_host is defined |
The variable exists |
none |
value is none |
The value is null (~ or null in YAML) |
match(pattern) |
inventory_hostname is match('web') |
The pattern matches at the beginning |
search(pattern) |
aurora_domain is search('aurora') |
The pattern appears anywhere |
regex(pattern) |
x is regex('^web[0-9]+$') |
Like search, with more options |
version(v, op) |
ansible_facts['distribution_version'] is version('24.04', '>=') |
Version comparison |
in |
'webservers' in group_names |
Membership (an operator, not a test) |
subset / superset |
['curl'] is subset(common_packages) |
Inclusion between lists |
string, number, mapping, iterable |
nginx_upstream_servers is mapping |
Type of the value |
changed, failed, succeeded, skipped |
result is changed |
State of a registered result (Lesson 3.7) |
Two less obvious uses:
- Tests are what
select/selectattrreceive:team | selectattr('name', 'match', 'l')keeps the users whose name starts withl. versionavoids classic mistakes when comparing versions as text:'10.0' < '9.0'is true alphabetically;'10.0' is version('9.0', '<')is false, as it should be.
- Practice: the load balancer's server list
In the previous lesson, the nginx role learned to generate a load balancer with nginx_upstream_servers, a dictionary {address: weight}. In Lesson 5.7, a new server, lb1, will distribute the traffic between web1 and web2, and the inventory will have to build that dictionary. The data has existed since Module 2:
- The address of each web server:
ansible_hostininventory/hosts.yml. - Its weight:
aurora_lb_weightininventory/host_vars/web1.yml(2) andweb2.yml(1), a variable that no role has used until now.
Writing the dictionary by hand would work, but you'd have to touch it every time a web server was added. With filters, it's derived from the webservers group. Try it in demo-filters.yml:
- name: Build the load balancer servers
ansible.builtin.debug:
msg: >-
{{ dict(groups['webservers']
| map('extract', hostvars, 'ansible_host')
| zip(groups['webservers'] | map('extract', hostvars, 'aurora_lb_weight'))) }}How it's built:
flowchart LR
G["groups['webservers']<br/>[web1, web2]"] --> A["map extract ansible_host<br/>[192.168.56.11, 192.168.56.12]"]
G --> W["map extract aurora_lb_weight<br/>[2, 1]"]
A --> Z["zip<br/>[[192.168.56.11, 2], [192.168.56.12, 1]]"]
W --> Z
Z --> D["dict()<br/>{192.168.56.11: 2, 192.168.56.12: 1}"]
- Two
map('extract', ...)calls over the same list of hosts produce two parallel lists: addresses and weights. zippairs them up element by element.dict()converts the list of pairs into a dictionary.
If tomorrow you add web3 with its aurora_lb_weight, it'll appear in the load balancer without touching this expression. And if a web server were missing aurora_lb_weight, extract would fail with an undefined variable error: that's what you want, because a server without a weight is an inventory error. Keep the expression: in Lesson 5.7 you'll put it in inventory/group_vars/loadbalancers.yml.
- What a lookup is (and where it runs)
A lookup is a plugin that gets data from an external source and returns it as the value of an expression:
{{ lookup('ansible.builtin.env', 'USER') }}
{{ lookup('ansible.builtin.file', '~/.ssh/aurora_ed25519.pub') }}The first argument is the name of the lookup (with its FQCN, like modules), and the following ones are its parameters.
The most important rule: lookups run on the control node, not on the managed servers.
flowchart LR
subgraph Control["Control node (your computer)"]
L["lookup('file', ...)<br/>lookup('env', ...)<br/>lookup('pipe', ...)"]
end
subgraph Remote["web1"]
M["Modules: copy, template,<br/>command, slurp..."]
end
L -- "the value, already computed" --> M
Consequences you need to be clear about:
| Situation | What happens |
|---|---|
lookup('ansible.builtin.file', '/etc/aurora/db.conf') |
It reads your /etc/aurora/db.conf (which probably doesn't exist), not web1's. To read a remote file, use slurp or fetch |
lookup('ansible.builtin.env', 'HOME') |
It returns your home directory, not the remote user's |
lookup('ansible.builtin.pipe', 'hostname') |
It returns the name of your computer |
| A lookup in a variable used by 50 hosts | It runs on your computer for every host that uses it (and every time it's evaluated) |
That last row has an important consequence: variables are evaluated every time they're used. A variable defined with a lookup isn't computed once and stored; it's recomputed on every reference. With lookups that always return the same thing (a file) it doesn't matter, but with one that returns a random value, it does (section 16).
- The most useful lookups
| Lookup | Example | Returns |
|---|---|---|
ansible.builtin.file |
lookup('ansible.builtin.file', '~/.ssh/aurora_ed25519.pub') |
The content of a file on the control node |
ansible.builtin.env |
lookup('ansible.builtin.env', 'USER') |
An environment variable of the control node |
ansible.builtin.template |
lookup('ansible.builtin.template', 'report.j2') |
A rendered template, as text |
ansible.builtin.pipe |
lookup('ansible.builtin.pipe', 'git rev-parse --short HEAD') |
The output of a command on the control node |
ansible.builtin.password |
lookup('ansible.builtin.password', '/dev/null', length=24) |
A random password (section 16) |
ansible.builtin.vars |
lookup('ansible.builtin.vars', 'nginx_' + 'port') |
The value of a variable whose name is computed |
ansible.builtin.fileglob |
query('ansible.builtin.fileglob', 'files/*.conf') |
Files on the control node that match a pattern |
ansible.builtin.first_found |
Seen in Lesson 4.5 | The first path in a list that exists |
Some examples in the context of Aurora (try them in demo-filters.yml):
- name: Show control node data
ansible.builtin.debug:
msg:
- "Lab public key: {{ lookup('ansible.builtin.file', '~/.ssh/aurora_ed25519.pub') }}"
- "User running Ansible: {{ lookup('ansible.builtin.env', 'USER') }}"
- "Repository version: {{ lookup('ansible.builtin.pipe', 'git rev-parse --short HEAD') }}"
- "Domain (computed name): {{ lookup('ansible.builtin.vars', 'aurora_' + 'domain') }}"Comments:
filewith the public key is the classic use for authorizing SSH keys with theansible.posix.authorized_keymodule (you'll use it in Lesson 9.2). Relative paths are looked up as incopy(the role'sfiles/or next to the playbook).pipewithgitlets you record which version of the repository was applied. Watch out: if you wrote that value into a managed file, the file would change with every commit, and the task would notify handlers on every run.varsis useful when the variable name is built dynamically; to access a known variable, you don't need it.templateas a lookup renders a template and gives you the text (for example, for the body of a message). To create a file on the server, use thetemplatemodule.
If you want a lookup not to fail when the source doesn't exist, most of them accept errors='ignore' (returns empty) or errors='warn'.
lookup versus query
lookup versus querySome lookups return several values (like fileglob). lookup and query differ in how they deliver them:
| Function | Several results | One result |
|---|---|---|
lookup('fileglob', 'files/*.conf') |
A string with the values separated by commas | The string |
query('fileglob', 'files/*.conf') |
A list | A one-element list |
lookup('fileglob', 'files/*.conf', wantlist=True) |
A list (same as query) |
A one-element list |
In a loop, always use query (or q, its abbreviation): a loop needs a list, and a comma-separated string would give strange results.
- name: Publish all the extra configuration files
ansible.builtin.copy:
src: "{{ item }}"
dest: /etc/nginx/conf.d/
mode: "0644"
loop: "{{ query('ansible.builtin.fileglob', 'files/extra/*.conf') }}"In expressions where you expect a single value (file, env, pipe, password), lookup is the natural choice.
- Practice: generating passwords with the
password lookup
password lookupAurora's PostgreSQL users (aurora and aurora_reporting) have had no password since Lesson 3.4: the pg_hba.conf rules require scram-sha-256 for the web servers, but there's no password to authenticate with. In the next lesson you'll give them one, and the first step is to generate strong passwords. The password lookup does that:
ansible localhost -m ansible.builtin.debug \
-a "msg={{ lookup('ansible.builtin.password', '/dev/null', length=24, chars=['ascii_letters', 'digits']) }}"(Your value will be different: it's random.) The parameters:
| Parameter | Meaning |
|---|---|
| Path (first argument) | File on the control node where the password is stored. If it exists, it's reused; if not, it's generated and created. /dev/null means "don't store it" |
length |
Length (20 by default) |
chars |
Character sets: ascii_letters, digits, punctuation, ascii_lowercase… or specific characters |
Run it twice, once per user, and write down the two values temporarily: in Lesson 5.4 you'll store them encrypted. Limiting yourself to letters and digits avoids problems with characters that have a special meaning in connection strings (@, :, /) or in configuration files; with 24 characters the password is still very strong.
Two ways of using this lookup that you should not adopt:
- Storing the password in a file in the repository:
lookup('ansible.builtin.password', 'credentials/aurora_db length=24')createscredentials/aurora_dbwith the password in plain text. It's convenient, but if that file ends up in git, the password is exposed throughout the history. - Defining a variable with
/dev/null:aurora_db_password: "{{ lookup('ansible.builtin.password', '/dev/null') }}". Since variables are evaluated every time they're used (section 13), thepostgresqlrole and theaurora_approle would receive different passwords, and they would change again on every run.
The right solution is the one in the next lesson: generate the value once and store it encrypted in the repository with Ansible Vault.
Finish by deleting the test playbook:
Common Mistakes and Tips
- Seeing
<generator object ...>in the output: you've displayed the result ofmap/selectwithout converting it. Add| list. 'dict object' has no attribute 'x': an element of the list doesn't have that attribute. Useselectattr('x', 'defined')beforemap(attribute='x'), ormap(attribute='x', default='...').- Numeric comparisons that fail with
-e: the values in-e key=valueare text. Use| intor pass JSON (-e '{"nginx_port": 8080}'). - A lookup that "can't find" a file that exists on the server: lookups read the control node. For the server, use
slurporfetch. - Regular expressions that don't match: it's almost always the escaping of
\. Test the expression on its own in the experimentation playbook. - Random passwords that change on every run: a
passwordlookup with/dev/nullinside a variable. Generate the value once and store it encrypted (Lesson 5.4). - Tip: when an expression with filters goes beyond one line, write it with
>-and one filter per line, as in section 12. And if you need more than three or four chained filters, consider whether the inventory data should have a different shape.
Exercises
Exercise 1: Team users
Using the team variable from demo-filters.yml, write expressions that return:
- The list of names of the active users (without
state: absent), in alphabetical order. - A dictionary
{name: comment}of all the users. - The number of administrators.
Exercise 2: Hosts and IPs
Without creating new variables in the inventory, write an expression that returns a list of strings in the format web1=192.168.56.11 for each web server.
Exercise 3: Where does it run?
For each expression, say whether the value comes from the control node or from web1, when it's used in a task that runs on web1: (a) {{ ansible_facts['hostname'] }}, (b) {{ lookup('ansible.builtin.pipe', 'hostname') }}, (c) {{ inventory_hostname }}, (d) {{ lookup('ansible.builtin.env', 'HOME') }}.
Solutions
Exercise 1.
{{ team | rejectattr('state', 'defined') | map(attribute='name') | sort }}
{# ['deploy', 'laura', 'marc'] #}
{{ team | items2dict(key_name='name', value_name='comment') }}
{# {'deploy': 'Aurora Store deployments', 'laura': 'Laura Gómez - Development', ...} #}
{{ team | selectattr('admin', 'defined') | selectattr('admin') | list | length }}
{# 2 #}In the first one, sort already returns a list, so list isn't needed. In the third one, length needs a list: generators don't have a length. The first expression relies on the fact that, in this data, only absent users have state; if some user had an explicit state: present, you'd have to filter by the value: rejectattr('state', 'defined') would discard it by mistake.
Exercise 2.
{{ groups['webservers']
| zip(groups['webservers'] | map('extract', hostvars, 'ansible_host'))
| map('join', '=') | list }}
{# ['web1=192.168.56.11', 'web2=192.168.56.12'] #}zip pairs names and IPs, and map('join', '=') joins each pair with =.
Exercise 3. (a) From web1: facts are gathered on the server. (b) From the control node: pipe runs hostname on your computer. (c) From the inventory, which is read on the control node, but it's web1's name in the inventory (web1). (d) From the control node: your HOME, not that of the vagrant user on web1.
Conclusion
You've gone through the most widely used filters in Ansible: default and mandatory values (default, omit, mandatory), text (lower, replace, regex_replace, regex_search, split), lists (unique, sort, join, first, zip…), the map/select/reject/selectattr family with extract for cross-referencing data from several hosts, dictionaries (combine, dict2items, items2dict, dict()), conversions (int, bool, to_nice_yaml, from_json), encoding and passwords (b64decode, password_hash) and ternary, along with the tests used by when and selectattr. You've used dict and zip to build the list of servers the load balancer in Lesson 5.7 will use, and you've learned that lookups (file, env, template, pipe, password, vars, fileglob, first_found) bring in data from the control node, that query always returns a list, and that a variable with a lookup is recomputed every time it's used. You've generated the passwords for the PostgreSQL users, but you've written them down somewhere temporary, and they can't go into the repository in plain text. In the next lesson, Ansible Vault, you'll store them encrypted in the Aurora inventory, configure how they're decrypted without typing the password on every run, and finally give the aurora and aurora_reporting users a password.
Ansible Course: From Beginner to Advanced
Module 1: Introduction to Ansible
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
