Low Orbit Flux Logo 2 F

Ansible - Filters

Filters are used for transforming variables.

Example using filters:




tasks:
  - shell: cat /data/some_silly_config.yaml
    register: result
  - debug:
      msg: '{{ item }}'
    loop: '{{ result.stdout | from_yaml_all | list }}'


If a value starts with a variable, the line needs to be quoted.




app_path: {{ base_path }}/22          # No
app_path: "{{ base_path }}/22"        # Yes


JSON and YAML:




{{ some_variable | to_json }}                             # to JSON
{{ some_variable | to_yaml }}                             # to YAML
{{ some_variable | to_nice_json }}                        # to human readable JSON
{{ some_variable | to_nice_yaml }}                        # to human readable YAML
{{ some_variable | to_nice_json(indent=2) }}              # to human readable JSON, indent
{{ some_variable | to_nice_yaml(indent=8) }}              # to human readable YAML, indent
{{ some_variable | to_yaml(indent=8, width=1337) }}       # to YAML, indent, longer width
{{ some_variable | to_nice_yaml(indent=8, width=1337) }}  # to human readable YAML, indent, longer width
{{ some_variable | from_json }}                           # from JSON
{{ some_variable | from_yaml }}                           # from YAML


Variables and defaults




{{ variable | mandatory }}                  # make var mandatory, fail if undefined
{{ some_variable | default(5) }}            # provide default value

mode: "{{ item.mode | default(omit) }}"     # ommit if not defined


Lists and dictionaries:




{{ list1 | min }}                            # min value in list
{{ [3, 4, 2] | max }}                        # max value in list
{{ [3, [4, 2] ] | flatten }}                 # flatten a list
{{ [3, [4, [2]] ] | flatten(levels=1) }}     # flatten a list, 1 level
{{ list1 | unique }}                         # unique items in a list
{{ list1 | union(list2) }}                   # union of two lists
{{ list1 | intersect(list2) }}               # intersection of two lists
{{ list1 | difference(list2) }}              # difference between lists
{{ list1 | symmetric_difference(list2) }}    # symetric difference

{{ dict | dict2items }}                                          # dictionary to list of key value pairs ( for looping )
{{ files | dict2items(key_name='file', value_name='path') }}     # specify names for key and value
{{ tags | items2dict }}                                          # reverse of dict2items, list of key value pairs back to dict
{{ tags | items2dict(key_name='key', value_name='value') }}      # select which to use as a key or value


msg: "{{ [1,2,3,4,5] | zip(['a','b','c','d','e','f']) | list }}"                   # zip two lists together, shortest combo
msg: "{{ [1,2,3] | zip_longest(['a','b','c'], [22, 23], fillvalue='X') | list }}"  # zip two lists, always exhaust
{{ dict(keys_list | zip(values_list)) }}                                           # create a dictionary

{{ {'a':1, 'b':2} | combine({'b':3}) }}    # merge hashes, dups from second hash overrides first
{{ a | combine(b, c, d) }}                 # merge multiple hashes


Misc Useful Filters:




"{{ domain_definition | json_query('domain.cluster[*].name') }}"   # query JSON

{{ configmap_resource_definition | k8s_config_resource_name }}     # a Kubernetes filter

{{ "Plain style (default)" | comment }}                #  generate commented text
{{ "My Special Case" | comment(decoration="! ") }}     #  generate commented text with !

{{ string_value | quote }}                    # quote a string
{{ (name == "John") | ternary('Mr','Ms') }}   # one value on true and another on false
{{ list | join(" ") }}                        # concat a list to a string

{{ encoded | b64decode }}                     # b64 decode string, utf-8 by default
{{ decoded | string | b64encode }}            # b64 encode string, utf-8 by default
{{ hostname | to_uuid }}                      # create a UUID from a string
{{  '1.1 GB'|human_to_bytes}}                 # get bytes from human readable size

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


Passwords and Encryption:




{{ 'test1' | hash('sha1') }}             #sha1 hash
{{ 'test1' | hash('md5') }}              # md5 hash
{{ 'test2' | hash('blowfish') }}         # blowfish hash
{{ 'passwordsaresecret' | password_hash('sha512') }}                # sha256 password, random salt
{{ 'secretpassword' | password_hash('sha256', 'mysecretsalt') }}    # sha256 password, specific salt
{{ 'secretpassword' | password_hash('sha512', 65534 | random(seed=inventory_hostname) | string) }}  # predictable host specific hash


Network Stuff:




"{{ '52:54:00' | random_mac }}"           # generate random MAC address with specified prefix

{{ myvar | ipaddr }}                      # test for valid IP
{{ myvar | ipv4 }}                        # test for IPv4
{{ myvar | ipv6 }}                        # test for IPv6
{{ '192.0.2.1/24' | ipaddr('address') }}  # grab IP from CIDR


url: "http://user:password@www.acme.com:9000/dir/index.html?query=term#fragment"

{{ url | urlsplit('hostname') }}     # 'www.acme.com'
{{ url | urlsplit('netloc') }}       # 'user:password@www.acme.com:9000'
{{ url | urlsplit('username') }}     # 'user'
{{ url | urlsplit('password') }}     # 'password'
{{ url | urlsplit('path') }}         # '/dir/index.html'
{{ url | urlsplit('port') }}         # '9000'
{{ url | urlsplit('scheme') }}       # 'http'
{{ url | urlsplit('query') }}        # 'query=term'
{{ url | urlsplit('fragment') }}     # 'fragment'
{{ url | urlsplit }}                 #  all values as a hash

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

{{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\\1') }}      # convert "ansible" to "able"
{{ 'foobar' | regex_replace('^f.*o(.*)$', '\\1') }}        # convert "foobar" to "bar"
{{ 'localhost:80' | regex_replace(':80') }}                # convert "localhost:80" to "localhost"


Paths:




{{ path | basename }}                  # get file name from file path
{{ path | dirname }}                   # get dir from a path
{{ path | expanduser }}                # expand a path with the ~
{{ path | expandvars }}                # expand path with env variables

{{ path | realpath }}                  # real path of a link
{{ path | relpath('/etc') }}           # relative path of a link from a start point
{{ path | splitext }}                  # get the root and extension of a path or filename

{{ path | win_basename }}              # get file name from file path on Windows
{{ path | win_dirname }}               # get dir from Windows path
{{ path | win_splitdrive }}            # get windows drive letter from path
{{ path | win_splitdrive | first }}    # only the windows drive letter
{{ path | win_splitdrive | last }}     # rest of the path without the drive letter