Filters

Filters in Ansible are from Jinja2, and are used for transforming data inside a template expression. Jinja2 ships with many filters. See builtin filters in the official Jinja2 template documentation.

Take into account that templating happens on the Ansible controller, not on the task’s target host, so filters also execute on the controller as they manipulate local data.

In addition the ones provided by Jinja2, Ansible ships with it’s own and allows users to add their own custom filters.

Filters For Formatting Data

The following filters will take a data structure in a template and render it in a slightly different format. Theseare occasionally useful for debugging:

  1. {{ some_variable | to_json }}
  2. {{ some_variable | to_yaml }}

For human readable output, you can use:

  1. {{ some_variable | to_nice_json }}
  2. {{ some_variable | to_nice_yaml }}

It’s also possible to change the indentation of both (new in version 2.2):

  1. {{ some_variable | to_nice_json(indent=2) }}
  2. {{ some_variable | to_nice_yaml(indent=8) }}

Alternatively, you may be reading in some already formatted data:

  1. {{ some_variable | from_json }}
  2. {{ some_variable | from_yaml }}

for example:

  1. tasks:
  2. - shell: cat /some/path/to/file.json
  3. register: result
  4.  
  5. - set_fact:
  6. myvar: "{{ result.stdout | from_json }}"

New in version 2.7.

To parse multi-document yaml strings, the from_yaml_all filter is provided.The from_yaml_all filter will return a generator of parsed yaml documents.

for example:

  1. tasks:
  2. - shell: cat /some/path/to/multidoc-file.yaml
  3. register: result
  4. - debug:
  5. msg: '{{ item }}'
  6. loop: '{{ result.stdout | from_yaml_all | list }}'

Forcing Variables To Be Defined

The default behavior from ansible and ansible.cfg is to fail if variables are undefined, but you can turn this off.

This allows an explicit check with this feature off:

  1. {{ variable | mandatory }}

The variable value will be used as is, but the template evaluation will raise an error if it is undefined.

Defaulting Undefined Variables

Jinja2 provides a useful ‘default’ filter that is often a better approach to failing if a variable is not defined:

  1. {{ some_variable | default(5) }}

In the above example, if the variable ‘some_variable’ is not defined, the value used will be 5, rather than an errorbeing raised.

If you want to use the default value when variables evaluate to false or an empty string you have to set the second parameter totrue:

  1. {{ lookup('env', 'MY_USER') | default('admin', true) }}

Omitting Parameters

As of Ansible 1.8, it is possible to use the default filter to omit module parameters using the special omit variable:

  1. - name: touch files with an optional mode
  2. file: dest={{ item.path }} state=touch mode={{ item.mode | default(omit) }}
  3. loop:
  4. - path: /tmp/foo
  5. - path: /tmp/bar
  6. - path: /tmp/baz
  7. mode: "0444"

For the first two files in the list, the default mode will be determined by the umask of the system as the mode=_parameter will not be sent to the file module while the final file will receive the _mode=0444 option.

Note

If you are “chaining” additional filters after the default(omit) filter, you should instead do something like this:“{{ foo | default(None) | some_filter or omit }}”. In this example, the default None (python null) value will cause thelater filters to fail, which will trigger the or omit portion of the logic. Using omit in this manner is very specific tothe later filters you’re chaining though, so be prepared for some trial and error if you do this.

List Filters

These filters all operate on list variables.

New in version 1.8.

To get the minimum value from list of numbers:

  1. {{ list1 | min }}

To get the maximum value from a list of numbers:

  1. {{ [3, 4, 2] | max }}

New in version 2.5.

Flatten a list (same thing the flatten lookup does):

  1. {{ [3, [4, 2] ] | flatten }}

Flatten only the first level of a list (akin to the items lookup):

  1. {{ [3, [4, [2]] ] | flatten(levels=1) }}

Set Theory Filters

All these functions return a unique set from sets or lists.

New in version 1.4.

To get a unique set from a list:

  1. {{ list1 | unique }}

To get a union of two lists:

  1. {{ list1 | union(list2) }}

To get the intersection of 2 lists (unique list of all items in both):

  1. {{ list1 | intersect(list2) }}

To get the difference of 2 lists (items in 1 that don’t exist in 2):

  1. {{ list1 | difference(list2) }}

To get the symmetric difference of 2 lists (items exclusive to each list):

  1. {{ list1 | symmetric_difference(list2) }}

Dict Filter

New in version 2.6.

To turn a dictionary into a list of items, suitable for looping, use dict2items:

  1. {{ dict | dict2items }}

Which turns:

  1. tags:
  2. Application: payment
  3. Environment: dev

into:

  1. - key: Application
  2. value: payment
  3. - key: Environment
  4. value: dev

items2dict filter

New in version 2.7.

This filter turns a list of dicts with 2 keys, into a dict, mapping the values of those keys into key: value pairs:

  1. {{ tags | items2dict }}

Which turns:

  1. tags:
  2. - key: Application
  3. value: payment
  4. - key: Environment
  5. value: dev

into:

  1. Application: payment
  2. Environment: dev

This is the reverse of the dict2items filter.

items2dict accepts 2 keyword arguments, key_name and value_name that allow configuration of the names of the keys to use for the transformation:

  1. {{ tags | items2dict(key_name='key', value_name='value') }}

zip and zip_longest filters

New in version 2.3.

To get a list combining the elements of other lists use zip:

  1. - name: give me list combo of two lists
  2. debug:
  3. msg: "{{ [1,2,3,4,5] | zip(['a','b','c','d','e','f']) | list }}"
  4.  
  5. - name: give me shortest combo of two lists
  6. debug:
  7. msg: "{{ [1,2,3] | zip(['a','b','c','d','e','f']) | list }}"

To always exhaust all list use zip_longest:

  1. - name: give me longest combo of three lists , fill with X
  2. debug:
  3. msg: "{{ [1,2,3] | zip_longest(['a','b','c','d','e','f'], [21, 22, 23], fillvalue='X') | list }}"

Similarly to the output of the items2dict filter mentioned above, these filters can be used to contruct a dict:

  1. {{ dict(keys_list | zip(values_list)) }}

Which turns:

  1. list_one:
  2. - one
  3. - two
  4. list_two:
  5. - apple
  6. - orange

into:

  1. one: apple
  2. two: orange

subelements Filter

New in version 2.7.

Produces a product of an object, and subelement values of that object, similar to the subelements lookup:

  1. {{ users | subelements('groups', skip_missing=True) }}

Which turns:

  1. users:
  2. - name: alice
  3. authorized:
  4. - /tmp/alice/onekey.pub
  5. - /tmp/alice/twokey.pub
  6. groups:
  7. - wheel
  8. - docker
  9. - name: bob
  10. authorized:
  11. - /tmp/bob/id_rsa.pub
  12. groups:
  13. - docker

Into:

  1. -
  2. - name: alice
  3. groups:
  4. - wheel
  5. - docker
  6. authorized:
  7. - /tmp/alice/onekey.pub
  8. - wheel
  9. -
  10. - name: alice
  11. groups:
  12. - wheel
  13. - docker
  14. authorized:
  15. - /tmp/alice/onekey.pub
  16. - docker
  17. -
  18. - name: bob
  19. authorized:
  20. - /tmp/bob/id_rsa.pub
  21. groups:
  22. - docker
  23. - docker

An example of using this filter with loop:

  1. - name: Set authorized ssh key, extracting just that data from 'users'
  2. authorized_key:
  3. user: "{{ item.0.name }}"
  4. key: "{{ lookup('file', item.1) }}"
  5. loop: "{{ users | subelements('authorized') }}"

Random Mac Address Filter

New in version 2.6.

This filter can be used to generate a random MAC address from a string prefix.

To get a random MAC address from a string prefix starting with ‘52:54:00’:

  1. "{{ '52:54:00' | random_mac }}"
  2. # => '52:54:00:ef:1c:03'

Note that if anything is wrong with the prefix string, the filter will issue an error.

Random Number Filter

New in version 1.6.

This filter can be used similar to the default jinja2 random filter (returning a random item from a sequence ofitems), but can also generate a random number based on a range.

To get a random item from a list:

  1. "{{ ['a','b','c'] | random }}"
  2. # => 'c'

To get a random number between 0 and a specified number:

  1. "{{ 60 | random }} * * * * root /script/from/cron"
  2. # => '21 * * * * root /script/from/cron'

Get a random number from 0 to 100 but in steps of 10:

  1. {{ 101 | random(step=10) }}
  2. # => 70

Get a random number from 1 to 100 but in steps of 10:

  1. {{ 101 | random(1, 10) }}
  2. # => 31
  3. {{ 101 | random(start=1, step=10) }}
  4. # => 51

As of Ansible version 2.3, it’s also possible to initialize the random number generator from a seed. This way, you can create random-but-idempotent numbers:

  1. "{{ 60 | random(seed=inventory_hostname) }} * * * * root /script/from/cron"

Shuffle Filter

New in version 1.8.

This filter will randomize an existing list, giving a different order every invocation.

To get a random list from an existing list:

  1. {{ ['a','b','c'] | shuffle }}
  2. # => ['c','a','b']
  3. {{ ['a','b','c'] | shuffle }}
  4. # => ['b','c','a']

As of Ansible version 2.3, it’s also possible to shuffle a list idempotent. All you need is a seed.:

  1. {{ ['a','b','c'] | shuffle(seed=inventory_hostname) }}
  2. # => ['b','a','c']

note that when used with a non ‘listable’ item it is a noop, otherwise it always returns a list

Math

New in version 1.9.

Get the logarithm (default is e):

  1. {{ myvar | log }}

Get the base 10 logarithm:

  1. {{ myvar | log(10) }}

Give me the power of 2! (or 5):

  1. {{ myvar | pow(2) }}
  2. {{ myvar | pow(5) }}

Square root, or the 5th:

  1. {{ myvar | root }}
  2. {{ myvar | root(5) }}

Note that jinja2 already provides some like abs() and round().

JSON Query Filter

New in version 2.2.

Sometimes you end up with a complex data structure in JSON format and you need to extract only a small set of data within it. The json_query filter lets you query a complex JSON structure and iterate over it using a loop structure.

Note

This filter is built upon jmespath, and you can use the same syntax. For examples, see jmespath examples.

Now, let’s take the following data structure:

  1. domain_definition:
  2. domain:
  3. cluster:
  4. - name: "cluster1"
  5. - name: "cluster2"
  6. server:
  7. - name: "server11"
  8. cluster: "cluster1"
  9. port: "8080"
  10. - name: "server12"
  11. cluster: "cluster1"
  12. port: "8090"
  13. - name: "server21"
  14. cluster: "cluster2"
  15. port: "9080"
  16. - name: "server22"
  17. cluster: "cluster2"
  18. port: "9090"
  19. library:
  20. - name: "lib1"
  21. target: "cluster1"
  22. - name: "lib2"
  23. target: "cluster2"

To extract all clusters from this structure, you can use the following query:

  1. - name: "Display all cluster names"
  2. debug:
  3. var: item
  4. loop: "{{ domain_definition | json_query('domain.cluster[*].name') }}"

Same thing for all server names:

  1. - name: "Display all server names"
  2. debug:
  3. var: item
  4. loop: "{{ domain_definition | json_query('domain.server[*].name') }}"

This example shows ports from cluster1:

  1. - name: "Display all ports from cluster1"
  2. debug:
  3. var: item
  4. loop: "{{ domain_definition | json_query(server_name_cluster1_query) }}"
  5. vars:
  6. server_name_cluster1_query: "domain.server[?cluster=='cluster1'].port"

Note

You can use a variable to make the query more readable.

Or, alternatively print out the ports in a comma separated string:

  1. - name: "Display all ports from cluster1 as a string"
  2. debug:
  3. msg: "{{ domain_definition | json_query('domain.server[?cluster==`cluster1`].port') | join(', ') }}"

Note

Here, quoting literals using backticks avoids escaping quotes and maintains readability.

Or, using YAML single quote escaping:

  1. - name: "Display all ports from cluster1"
  2. debug:
  3. var: item
  4. loop: "{{ domain_definition | json_query('domain.server[?cluster==''cluster1''].port') }}"

Note

Escaping single quotes within single quotes in YAML is done by doubling the single quote.

In this example, we get a hash map with all ports and names of a cluster:

  1. - name: "Display all server ports and names from cluster1"
  2. debug:
  3. var: item
  4. loop: "{{ domain_definition | json_query(server_name_cluster1_query) }}"
  5. vars:
  6. server_name_cluster1_query: "domain.server[?cluster=='cluster2'].{name: name, port: port}"

IP address filter

New in version 1.9.

To test if a string is a valid IP address:

  1. {{ myvar | ipaddr }}

You can also require a specific IP protocol version:

  1. {{ myvar | ipv4 }}
  2. {{ myvar | ipv6 }}

IP address filter can also be used to extract specific information from an IPaddress. For example, to get the IP address itself from a CIDR, you can use:

  1. {{ '192.0.2.1/24' | ipaddr('address') }}

More information about ipaddr filter and complete usage guide can be foundin ipaddr filter.

Network CLI filters

New in version 2.4.

To convert the output of a network device CLI command into structured JSONoutput, use the parse_cli filter:

  1. {{ output | parse_cli('path/to/spec') }}

The parse_cli filter will load the spec file and pass the command outputthrough it, returning JSON output. The YAML spec file defines how to parse the CLI output.

The spec file should be valid formatted YAML. It defines how to parse the CLIoutput and return JSON data. Below is an example of a valid spec file thatwill parse the output from the show vlan command.

  1. ---
  2. vars:
  3. vlan:
  4. vlan_id: "{{ item.vlan_id }}"
  5. name: "{{ item.name }}"
  6. enabled: "{{ item.state != 'act/lshut' }}"
  7. state: "{{ item.state }}"
  8.  
  9. keys:
  10. vlans:
  11. value: "{{ vlan }}"
  12. items: "^(?P<vlan_id>\\d+)\\s+(?P<name>\\w+)\\s+(?P<state>active|act/lshut|suspended)"
  13. state_static:
  14. value: present

The spec file above will return a JSON data structure that is a list of hasheswith the parsed VLAN information.

The same command could be parsed into a hash by using the key and valuesdirectives. Here is an example of how to parse the output into a hashvalue using the same show vlan command.

  1. ---
  2. vars:
  3. vlan:
  4. key: "{{ item.vlan_id }}"
  5. values:
  6. vlan_id: "{{ item.vlan_id }}"
  7. name: "{{ item.name }}"
  8. enabled: "{{ item.state != 'act/lshut' }}"
  9. state: "{{ item.state }}"
  10.  
  11. keys:
  12. vlans:
  13. value: "{{ vlan }}"
  14. items: "^(?P<vlan_id>\\d+)\\s+(?P<name>\\w+)\\s+(?P<state>active|act/lshut|suspended)"
  15. state_static:
  16. value: present

Another common use case for parsing CLI commands is to break a large commandinto blocks that can be parsed. This can be done using the start_block andend_block directives to break the command into blocks that can be parsed.

  1. ---
  2. vars:
  3. interface:
  4. name: "{{ item[0].match[0] }}"
  5. state: "{{ item[1].state }}"
  6. mode: "{{ item[2].match[0] }}"
  7.  
  8. keys:
  9. interfaces:
  10. value: "{{ interface }}"
  11. start_block: "^Ethernet.*$"
  12. end_block: "^$"
  13. items:
  14. - "^(?P<name>Ethernet\\d\\/\\d*)"
  15. - "admin state is (?P<state>.+),"
  16. - "Port mode is (.+)"

The example above will parse the output of show interface into a list ofhashes.

The network filters also support parsing the output of a CLI command using theTextFSM library. To parse the CLI output with TextFSM use the followingfilter:

  1. {{ output.stdout[0] | parse_cli_textfsm('path/to/fsm') }}

Use of the TextFSM filter requires the TextFSM library to be installed.

Network XML filters

New in version 2.5.

To convert the XML output of a network device command into structured JSONoutput, use the parse_xml filter:

  1. {{ output | parse_xml('path/to/spec') }}

The parse_xml filter will load the spec file and pass the command outputthrough formatted as JSON.

The spec file should be valid formatted YAML. It defines how to parse the XMLoutput and return JSON data.

Below is an example of a valid spec file thatwill parse the output from the show vlan | display xml command.

  1. ---
  2. vars:
  3. vlan:
  4. vlan_id: "{{ item.vlan_id }}"
  5. name: "{{ item.name }}"
  6. desc: "{{ item.desc }}"
  7. enabled: "{{ item.state.get('inactive') != 'inactive' }}"
  8. state: "{% if item.state.get('inactive') == 'inactive'%} inactive {% else %} active {% endif %}"
  9.  
  10. keys:
  11. vlans:
  12. value: "{{ vlan }}"
  13. top: configuration/vlans/vlan
  14. items:
  15. vlan_id: vlan-id
  16. name: name
  17. desc: description
  18. state: ".[@inactive='inactive']"

The spec file above will return a JSON data structure that is a list of hasheswith the parsed VLAN information.

The same command could be parsed into a hash by using the key and valuesdirectives. Here is an example of how to parse the output into a hashvalue using the same show vlan | display xml command.

  1. ---
  2. vars:
  3. vlan:
  4. key: "{{ item.vlan_id }}"
  5. values:
  6. vlan_id: "{{ item.vlan_id }}"
  7. name: "{{ item.name }}"
  8. desc: "{{ item.desc }}"
  9. enabled: "{{ item.state.get('inactive') != 'inactive' }}"
  10. state: "{% if item.state.get('inactive') == 'inactive'%} inactive {% else %} active {% endif %}"
  11.  
  12. keys:
  13. vlans:
  14. value: "{{ vlan }}"
  15. top: configuration/vlans/vlan
  16. items:
  17. vlan_id: vlan-id
  18. name: name
  19. desc: description
  20. state: ".[@inactive='inactive']"

The value of top is the XPath relative to the XML root node.In the example XML output given below, the value of top is configuration/vlans/vlan,which is an XPath expression relative to the root node (<rpc-reply>).configuration in the value of top is the outer most container node, and vlanis the inner-most container node.

items is a dictionary of key-value pairs that map user-defined names to XPath expressionsthat select elements. The Xpath expression is relative to the value of the XPath value contained in top.For example, the vlan_id in the spec file is a user defined name and its value vlan-id is therelative to the value of XPath in top

Attributes of XML tags can be extracted using XPath expressions. The value of state in the specis an XPath expression used to get the attributes of the vlan tag in output XML.:

  1. <rpc-reply>
  2. <configuration>
  3. <vlans>
  4. <vlan inactive="inactive">
  5. <name>vlan-1</name>
  6. <vlan-id>200</vlan-id>
  7. <description>This is vlan-1</description>
  8. </vlan>
  9. </vlans>
  10. </configuration>
  11. </rpc-reply>

Note

For more information on supported XPath expressions, see https://docs.python.org/2/library/xml.etree.elementtree.html#xpath-support.

Hashing filters

New in version 1.9.

To get the sha1 hash of a string:

  1. {{ 'test1' | hash('sha1') }}

To get the md5 hash of a string:

  1. {{ 'test1' | hash('md5') }}

Get a string checksum:

  1. {{ 'test2' | checksum }}

Other hashes (platform dependent):

  1. {{ 'test2' | hash('blowfish') }}

To get a sha512 password hash (random salt):

  1. {{ 'passwordsaresecret' | password_hash('sha512') }}

To get a sha256 password hash with a specific salt:

  1. {{ 'secretpassword' | password_hash('sha256', 'mysecretsalt') }}

An idempotent method to generate unique hashes per system is to use a salt that is consistent between runs:

  1. {{ 'secretpassword' | password_hash('sha512', 65534 | random(seed=inventory_hostname) | string) }}

Hash types available depend on the master system running ansible,‘hash’ depends on hashlib password_hash depends on passlib (https://passlib.readthedocs.io/en/stable/lib/passlib.hash.html).

New in version 2.7.

Some hash types allow providing a rounds parameter:

  1. {{ 'secretpassword' | password_hash('sha256', 'mysecretsalt', rounds=10000) }}

Combining hashes/dictionaries

New in version 2.0.

The combine filter allows hashes to be merged. For example, thefollowing would override keys in one hash:

  1. {{ {'a':1, 'b':2} | combine({'b':3}) }}

The resulting hash would be:

  1. {'a':1, 'b':3}

The filter also accepts an optional recursive=True parameter to notonly override keys in the first hash, but also recurse into nestedhashes and merge their keys too

  1. {{ {'a':{'foo':1, 'bar':2}, 'b':2} | combine({'a':{'bar':3, 'baz':4}}, recursive=True) }}

This would result in:

  1. {'a':{'foo':1, 'bar':3, 'baz':4}, 'b':2}

The filter can also take multiple arguments to merge:

  1. {{ a | combine(b, c, d) }}

In this case, keys in d would override those in c, which wouldoverride those in b, and so on.

This behaviour does not depend on the value of the hash_behaviour_setting in _ansible.cfg.

Extracting values from containers

New in version 2.1.

The extract filter is used to map from a list of indices to a list ofvalues from a container (hash or array):

  1. {{ [0,2] | map('extract', ['x','y','z']) | list }}
  2. {{ ['x','y'] | map('extract', {'x': 42, 'y': 31}) | list }}

The results of the above expressions would be:

  1. ['x', 'z']
  2. [42, 31]

The filter can take another argument:

  1. {{ groups['x'] | map('extract', hostvars, 'ec2_ip_address') | list }}

This takes the list of hosts in group ‘x’, looks them up in hostvars,and then looks up the ec2_ip_address of the result. The final resultis a list of IP addresses for the hosts in group ‘x’.

The third argument to the filter can also be a list, for a recursivelookup inside the container:

  1. {{ ['a'] | map('extract', b, ['x','y']) | list }}

This would return a list containing the value of b[‘a’][‘x’][‘y’].

Comment Filter

New in version 2.0.

The comment filter allows to decorate the text with a chosen commentstyle. For example the following:

  1. {{ "Plain style (default)" | comment }}

will produce this output:

  1. #
  2. # Plain style (default)
  3. #

Similar way can be applied style for C (//…), C block(//), Erlang (%…) and XML (<!—…—>):

  1. {{ "C style" | comment('c') }}
  2. {{ "C block style" | comment('cblock') }}
  3. {{ "Erlang style" | comment('erlang') }}
  4. {{ "XML style" | comment('xml') }}

If you need a specific comment character that is not included by any of theabove, you can customize it with:

  1. {{ "My Special Case" | comment(decoration="! ") }}

producing:

  1. !
  2. ! My Special Case
  3. !

It is also possible to fully customize the comment style:

  1. {{ "Custom style" | comment('plain', prefix='#######\n#', postfix='#\n#######\n ###\n #') }}

That will create the following output:

  1. #######
  2. #
  3. # Custom style
  4. #
  5. #######
  6. ###
  7. #

The filter can also be applied to any Ansible variable. For example tomake the output of the ansible_managed variable more readable, we canchange the definition in the ansible.cfg file to this:

  1. [defaults]
  2.  
  3. ansible_managed = This file is managed by Ansible.%n
  4. template: {file}
  5. date: %Y-%m-%d %H:%M:%S
  6. user: {uid}
  7. host: {host}

and then use the variable with the comment filter:

  1. {{ ansible_managed | comment }}

which will produce this output:

  1. #
  2. # This file is managed by Ansible.
  3. #
  4. # template: /home/ansible/env/dev/ansible_managed/roles/role1/templates/test.j2
  5. # date: 2015-09-10 11:02:58
  6. # user: ansible
  7. # host: myhost
  8. #

URL Split Filter

New in version 2.4.

The urlsplit filter extracts the fragment, hostname, netloc, password, path, port, query, scheme, and username from an URL. With no arguments, returns a dictionary of all the fields:

  1. {{ "http://user:[email protected]:9000/dir/index.html?query=term#fragment" | urlsplit('hostname') }}
  2. # => 'www.acme.com'
  3.  
  4. {{ "http://user:[email protected]:9000/dir/index.html?query=term#fragment" | urlsplit('netloc') }}
  5. # => 'user:[email protected]:9000'
  6.  
  7. {{ "http://user:[email protected]:9000/dir/index.html?query=term#fragment" | urlsplit('username') }}
  8. # => 'user'
  9.  
  10. {{ "http://user:[email protected]:9000/dir/index.html?query=term#fragment" | urlsplit('password') }}
  11. # => 'password'
  12.  
  13. {{ "http://user:[email protected]:9000/dir/index.html?query=term#fragment" | urlsplit('path') }}
  14. # => '/dir/index.html'
  15.  
  16. {{ "http://user:[email protected]:9000/dir/index.html?query=term#fragment" | urlsplit('port') }}
  17. # => '9000'
  18.  
  19. {{ "http://user:[email protected]:9000/dir/index.html?query=term#fragment" | urlsplit('scheme') }}
  20. # => 'http'
  21.  
  22. {{ "http://user:[email protected]:9000/dir/index.html?query=term#fragment" | urlsplit('query') }}
  23. # => 'query=term'
  24.  
  25. {{ "http://user:[email protected]:9000/dir/index.html?query=term#fragment" | urlsplit('fragment') }}
  26. # => 'fragment'
  27.  
  28. {{ "http://user:[email protected]:9000/dir/index.html?query=term#fragment" | urlsplit }}
  29. # =>
  30. # {
  31. # "fragment": "fragment",
  32. # "hostname": "www.acme.com",
  33. # "netloc": "user:[email protected]:9000",
  34. # "password": "password",
  35. # "path": "/dir/index.html",
  36. # "port": 9000,
  37. # "query": "query=term",
  38. # "scheme": "http",
  39. # "username": "user"
  40. # }

Regular Expression Filters

To search a string with a regex, use the “regex_search” filter:

  1. # search for "foo" in "foobar"
  2. {{ 'foobar' | regex_search('(foo)') }}
  3.  
  4. # will return empty if it cannot find a match
  5. {{ 'ansible' | regex_search('(foobar)') }}
  6.  
  7. # case insensitive search in multiline mode
  8. {{ 'foo\nBAR' | regex_search("^bar", multiline=True, ignorecase=True) }}

To search for all occurrences of regex matches, use the “regex_findall” filter:

  1. # Return a list of all IPv4 addresses in the string
  2. {{ 'Some DNS servers are 8.8.8.8 and 8.8.4.4' | regex_findall('\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b') }}

To replace text in a string with regex, use the “regex_replace” filter:

  1. # convert "ansible" to "able"
  2. {{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\\1') }}
  3.  
  4. # convert "foobar" to "bar"
  5. {{ 'foobar' | regex_replace('^f.*o(.*)$', '\\1') }}
  6.  
  7. # convert "localhost:80" to "localhost, 80" using named groups
  8. {{ 'localhost:80' | regex_replace('^(?P<host>.+):(?P<port>\\d+)$', '\\g<host>, \\g<port>') }}
  9.  
  10. # convert "localhost:80" to "localhost"
  11. {{ 'localhost:80' | regex_replace(':80') }}
  12.  
  13. # add "https://" prefix to each item in a list
  14. {{ hosts | map('regex_replace', '^(.*)$', 'https://\\1') | list }}

Note

Prior to ansible 2.0, if “regex_replace” filter was used with variables inside YAML arguments (as opposed to simpler ‘key=value’ arguments),then you needed to escape backreferences (e.g. \1) with 4 backslashes (\\) instead of 2 (\).

New in version 2.0.

To escape special characters within a regex, use the “regex_escape” filter:

  1. # convert '^f.*o(.*)$' to '\^f\.\*o\(\.\*\)\$'
  2. {{ '^f.*o(.*)$' | regex_escape() }}

Other Useful Filters

To add quotes for shell usage:

  1. - shell: echo {{ string_value | quote }}

To use one value on true and another on false (new in version 1.9):

  1. {{ (name == "John") | ternary('Mr','Ms') }}

To concatenate a list into a string:

  1. {{ list | join(" ") }}

To get the last name of a file path, like ‘foo.txt’ out of ‘/etc/asdf/foo.txt’:

  1. {{ path | basename }}

To get the last name of a windows style file path (new in version 2.0):

  1. {{ path | win_basename }}

To separate the windows drive letter from the rest of a file path (new in version 2.0):

  1. {{ path | win_splitdrive }}

To get only the windows drive letter:

  1. {{ path | win_splitdrive | first }}

To get the rest of the path without the drive letter:

  1. {{ path | win_splitdrive | last }}

To get the directory from a path:

  1. {{ path | dirname }}

To get the directory from a windows path (new version 2.0):

  1. {{ path | win_dirname }}

To expand a path containing a tilde (~) character (new in version 1.5):

{{ path | expanduser }}

To expand a path containing environment variables:

{{ path | expandvars }}

Note

expandvars expands local variables; using it on remote paths can lead to errors.

New in version 2.6.

To get the real path of a link (new in version 1.8):

{{ path | realpath }}

To get the relative path of a link, from a start point (new in version 1.7):

{{ path | relpath('/etc') }}

To get the root and extension of a path or filename (new in version 2.0):

# with path == 'nginx.conf' the return would be ('nginx', '.conf')
{{ path | splitext }}

To work with Base64 encoded strings:

{{ encoded | b64decode }}
{{ decoded | b64encode }}

As of version 2.6, you can define the type of encoding to use, the default is utf-8:

{{ encoded | b64decode(encoding='utf-16-le') }}
{{ decoded | b64encode(encoding='utf-16-le') }}

New in version 2.6.

To create a UUID from a string (new in version 1.9):

{{ hostname | to_uuid }}

To cast values as certain types, such as when you input a string as “True” from a vars_prompt and the systemdoesn’t know it is a boolean value:

- debug:
    msg: test
  when: some_string_value | bool

New in version 1.6.

To make use of one attribute from each item in a list of complex variables, use the “map” filter (see the Jinja2 map() docs for more):

# get a comma-separated list of the mount points (e.g. "/,/mnt/stuff") on a host
{{ ansible_mounts | map(attribute='mount') | join(',') }}

To get date object from string use the to_datetime filter, (new in version in 2.2):

# Get total amount of seconds between two dates. Default date format is %Y-%m-%d %H:%M:%S but you can pass your own format
{{ (("2016-08-14 20:00:12" | to_datetime) - ("2015-12-25" | to_datetime('%Y-%m-%d'))).total_seconds()  }}

# Get remaining seconds after delta has been calculated. NOTE: This does NOT convert years, days, hours, etc to seconds. For that, use total_seconds()
{{ (("2016-08-14 20:00:12" | to_datetime) - ("2016-08-14 18:00:00" | to_datetime)).seconds  }}
# This expression evaluates to "12" and not "132". Delta is 2 hours, 12 seconds

# get amount of days between two dates. This returns only number of days and discards remaining hours, minutes, and seconds
{{ (("2016-08-14 20:00:12" | to_datetime) - ("2015-12-25" | to_datetime('%Y-%m-%d'))).days  }}

New in version 2.4.

To format a date using a string (like with the shell date command), use the “strftime” filter:

# Display year-month-day
{{ '%Y-%m-%d' | strftime }}

# Display hour:min:sec
{{ '%H:%M:%S' | strftime }}

# Use ansible_date_time.epoch fact
{{ '%Y-%m-%d %H:%M:%S' | strftime(ansible_date_time.epoch) }}

# Use arbitrary epoch value
{{ '%Y-%m-%d' | strftime(0) }}          # => 1970-01-01
{{ '%Y-%m-%d' | strftime(1441357287) }} # => 2015-09-04

Note

To get all string possibilities, check https://docs.python.org/2/library/time.html#time.strftime

Combination Filters

New in version 2.3.

This set of filters returns a list of combined lists.To get permutations of a list:

- name: give me largest permutations (order matters)
  debug:
    msg: "{{ [1,2,3,4,5] | permutations | list }}"

- name: give me permutations of sets of three
  debug:
    msg: "{{ [1,2,3,4,5] | permutations(3) | list }}"

Combinations always require a set size:

- name: give me combinations for sets of two
  debug:
    msg: "{{ [1,2,3,4,5] | combinations(2) | list }}"

Also see the zip and zip_longest filters

Debugging Filters

New in version 2.3.

Use the type_debug filter to display the underlying Python type of a variable.This can be useful in debugging in situations where you may need to know the exacttype of a variable:

{{ myvar | type_debug }}

A few useful filters are typically added with each new Ansible release. The development documentation showshow to extend Ansible filters by writing your own as plugins, though in general, we encourage new onesto be added to core so everyone can make use of them.

See also