Ansible tips & tricks

Ansible data types

integer: 3211241
boolean: true/false
float: 3.141592653
string: "qwerty"
list:
- "item 1"
- "item 2"
dictionary:
key1: "value 1"
key2: "value 2"

Dump all variables

---
- name: dump all
  hosts: all
 
  tasks:
    - name: Print some debug information 
      vars: 
        msg: |
          Module Variables ("vars"):
          --------------------------------
          {{ vars | to_nice_json }} 
          
          Environment Variables ("environment"):
          --------------------------------
          {{ environment | to_nice_json }} 
          
          GROUP NAMES Variables ("group_names"):
          --------------------------------
          {{ group_names | to_nice_json }}
          
          GROUPS Variables ("groups"):
          --------------------------------
          {{ groups | to_nice_json }}
          
          HOST Variables ("hostvars"):
          --------------------------------
          {{ hostvars | to_nice_json }} 

      debug:
        msg: "{{ msg.split('\n') }}"

manipulating data

Extract subitems from list of dictionaries

Use "{{ variable | map(attribute='key_name') | list }}"

Select items from list of dictionaries

Use "{{ variable | selectattr('key_name', 'match', 'value') | list }}"

Instead of match, you can also use search or regex. See: https://docs.ansible.com/ansible/latest/user_guide/playbooks_tests.html#testing-strings

See the Jinja2 documentation for a list of available tests: https://jinja.palletsprojects.com/en/2.9.x/templates/#list-of-builtin-tests

Sort list of dictionaries by subitem

Use "{{ variable | sort(attribute='key_name') }}"

Add item to list

Use "{{ variable | default([]) + [item] }}"

Add item to dictionary

Use "{{ variable | default({}) | combine({key_name: key_value}) }}"

Replace multiple lines using replace module (lineinfile does not support multi-line regexp)

Example:

- name: Comment out hint zone "." in named.conf
  replace:
    path: "/etc/named.conf"
    regexp: '^(zone\s+"\."\s+IN\s+{[^\n]*)\n(\s*type\s+hint;[^\n]*)\n(\s*file\s+"named\.ca";[^\n]*)\n(};)'
    replace: '# \1\n# \2\n# \3\n# \4'

-- Ivo van Geel - 21 Sep 2021

Edit | Attach | Watch | Print version | History: r19 | r7 < r6 < r5 < r4 | Backlinks | Raw View | More topic actions...
Topic revision: r5 - 17 Nov 2021 - IvoVanGeel
 
  • Edit
  • Attach
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2010-2019 by LANIS