Filters & Lookups
Filters transform values inside {{ }}: {{ name | upper }}. Ansible has Jinja2's built-in filters plus many of its own. Lookups fetch data from outside the play (files, environment variables, password stores) on the control node.
The filters you will use weekly
| Filter | Example | Result |
|---|---|---|
default |
{{ port | default(80) }} |
80 if port is undefined |
mandatory |
{{ db_host | mandatory }} |
fail with a clear error if undefined |
bool, int, string |
{{ "yes" | bool }} |
True |
join, split |
{{ ['a','b'] | join(',') }} |
a,b |
map, select, reject, selectattr |
{{ users | selectattr('admin') | map(attribute='name') }} |
names of admin users |
combine |
{{ defaults | combine(overrides, recursive=true) }} |
merged dictionaries |
dict2items, items2dict |
{{ {'a': 1} | dict2items }} |
[{'key': 'a', 'value': 1}] |
to_nice_yaml, to_nice_json, from_json, from_yaml |
serialise or parse | |
regex_replace, regex_search |
{{ 'v1.2.3' | regex_replace('^v', '') }} |
1.2.3 |
b64encode, b64decode, hash('sha256'), password_hash('sha512') |
encodings and hashes | |
ipaddr family (ansible.utils.ipaddr) |
{{ '10.0.1.0/24' | ansible.utils.ipaddr('net') }} |
network maths |
unique, sort, difference, union, flatten |
list maths |
ansible-doc -t filter -l lists all installed filters.
Filters on real data
cat > filters.yml <<'YML'
- name: Filters
hosts: localhost
gather_facts: false
vars:
users:
- {name: ada, admin: true, shell: /bin/bash}
- {name: grace, admin: false}
- {name: linus, admin: true, shell: /bin/zsh}
defaults: {log_level: info, db: {host: localhost, port: 5432}}
overrides: {db: {host: db1.internal}}
release: "v2.14.1"
tasks:
- name: Show filter results
ansible.builtin.debug:
msg:
- "admins: {{ users | selectattr('admin') | map(attribute='name') | join(', ') }}"
- "shells: {{ users | map(attribute='shell', default='/bin/sh') | unique | sort }}"
- "merged: {{ defaults | combine(overrides, recursive=true) }}"
- "version: {{ release | regex_replace('^v', '') }} major={{ (release | regex_replace('^v', '')).split('.')[0] }}"
- "missing: {{ undefined_thing | default('fallback') }}"
- "env var: {{ lookup('ansible.builtin.env', 'HOME') }}"
YML
ansible-playbook filters.yml | sed -n '/"msg"/,/^ ]/p' "msg": [
"admins: ada, linus",
"shells: ['/bin/bash', '/bin/sh', '/bin/zsh']",
"merged: {'log_level': 'info', 'db': {'host': 'db1.internal', 'port': 5432}}",
"version: 2.14.1 major=2",
"missing: fallback",
"env var: /home/learner"
]
combine(…, recursive=true) is the answer to "dictionaries are replaced, not merged" from Variable Precedence: keep the defaults dictionary and an overrides dictionary, and merge them yourself.
Rendering structured config
Many modern tools read YAML or JSON. Build the structure as a variable and let a filter write it, instead of hand-writing YAML in a template:
cat > cfg.yml <<'YML'
- name: Structured config
hosts: localhost
gather_facts: false
vars:
otel_config:
receivers: {otlp: {protocols: {grpc: {endpoint: "0.0.0.0:4317"}}}}
exporters: {debug: {}}
service: {pipelines: {traces: {receivers: [otlp], exporters: [debug]}}}
tasks:
- name: Write the collector config
ansible.builtin.copy:
dest: otel.yaml
content: "{{ otel_config | to_nice_yaml(indent=2) }}"
mode: "0644"
YML
ansible-playbook cfg.yml >/dev/null && cat otel.yamlexporters:
debug: {}
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
service:
pipelines:
traces:
exporters:
- debug
receivers:
- otlp
No indentation mistakes are possible, and the variable can be merged with per-environment overrides first. (to_nice_yaml sorts keys alphabetically, which keeps diffs stable; the tool reading the file doesn't care about the order.)
Lookups
Lookups run on the control node, not on the managed host:
| Lookup | Example |
|---|---|
file |
{{ lookup('ansible.builtin.file', 'files/id_ed25519.pub') }} |
env |
{{ lookup('ansible.builtin.env', 'CI_COMMIT_SHA') }} |
template |
render a template into a variable |
pipe |
output of a local command |
password |
generate and store a random password in a local file |
community.hashi_vault.hashi_vault, amazon.aws.aws_secret |
fetch secrets from Vault or AWS Secrets Manager |
- name: Authorized key from the repository
ansible.posix.authorized_key:
user: deploy
key: "{{ lookup('ansible.builtin.file', 'files/deploy.pub') }}"query('…') is the same as lookup('…') but always returns a list, which is what loops want.
Test yourself
Which filter merges two dictionaries, including nested keys?
joincombine(…, recursive=true)uniondict2items
Where does lookup('ansible.builtin.file', 'x.pub') read the file?
- On the managed host
- On the control node
- From Galaxy
- From the inventory
Why render YAML config with to_nice_yaml instead of writing YAML by hand in a template?
- It is required
- The structure is a real variable, so indentation can't break and it can be merged first
- It encrypts the file
- Templates can't output YAML