Skip to content

Ansible

Configuration

https://docs.ansible.com/config

[defaults]
localhost_warning=False
collections_path=.ansible/collections
callback_result_format = yaml
callbacks_enabled=profile_tasks,profile_roles,timer
interpreter_python=auto_silent

[ssh_connection]
ssh_common_args=-o StrictHostKeyChecking=accept-new

Jinja2

Whitespace control

To trim initial newline and leading whitespace add the following to the top of a template:

#jinja2: trim_blocks: True, lstrip_blocks: True

See Jinja -Whitespace control for details.

Templating YAML

Format YAML from Ansible variable.

Variable

my_yaml_array:
    - name: item1
      host: item1.example.com
    - name: item2
      host: item2.example.com

Jinja2 template

config:
  items:
{% if my_yaml_array | length > 0 %}
{{ my_yaml_array | to_nice_yaml(indent=2) | indent(4, first=True) }}
{% endif %}

Output

config:
  items:
    - host: item1.example.com
      name: item1
    - host: item2.example.com
      name: item2

Tasks

Loop select keys in dicts

Variable

my_yaml_array:
  - name: item1
    host: item1.example.com
  - name: item2
    host: item2.example.com

Loop only name keys

- name: Loop names only
  ansible.builtin.debug:
    msg: "{{ item }}"
  loop: "{{ my_yaml_array | map(attribute='name' }}"

Conditional by group

- name: Control plane task
  when: "'kube_control_plane' in group_names"
  ansible.builtin.debug:
    msg: "This tasks runs on hosts in the 'kube_control_plan' group."

- name: Worker task
  when: "'kube_worker' in group_names"
  ansible.builtin.debug:
    msg: "This tasks runs on hosts in the 'kube_worker' group."

Conditional by OS family

- name: Update package cache
  when: ansible_os_family == 'Debian'
  ansible.builtin.apt:
    cache_valid_time: 1800

Linting

Ignoring

Inline

# noqa: [rule_id]

ansible-lint docs

- name: Decompress
  when: distfile_get.changed or not decompressed_stat.stat.exists # noqa no-handler
  community.general.decompress:
    src: "{{ distfile_volume_file }}"
    format: "{{ distfile_volume_ext | trim('.') }}"

Config

List rules in the skip_list in a ansible-lint config file. e.g. ansible-lint.yaml:

ansible-lint docs

skip_list:
  - galaxy[no-changelog]
  - var-naming[no-role-prefix]