Low Orbit Flux Logo 2 F

Ansible - List - Dictionary

List / array:



vars:
  list1:
    - one
    - two
    - three
  list2: ['one', 'two', 'three']

Dictionaries / hash:



vars:
  dict1:
    field1: one
    field2: two

Referencing dict fields:



dict1['field1']
dict1.field1

Big example showing how to use lists and dictionaries:




---
- name: A Test Playbook
  hosts: all
  vars:
    list1:
      - RedHat
      - Fedora
      - Debian
      - Ubuntu
    dict1:
      OS: Ubuntu
      IP: 192.168.3.2
      CPU: intel
      Mem: 32
  tasks:

    - name: Print List
      ansible.builtin.debug:
        var: list1

    - name: Print Dictionary
      ansible.builtin.debug:
        var: dict1

    - name: Print List Element
      ansible.builtin.debug:
        var: list1[2]

    - name: Print Dict Element
      ansible.builtin.debug:
        var: dict1['OS']


    - name: Loop Over List
      ansible.builtin.debug:
        msg: "Value: {{ item }}"
      loop: "{{ list1 }}"

    - name: Loop Over Dictionary
      ansible.builtin.debug:
        msg: "Key: {{ item.key }} Value: {{ item.value }}"
      loop: "{{ dict1|dict2items }}"


A small example:




- name: Create two hard links
  ansible.builtin.file:
    src: '/tmp/{{ item.src }}'
    dest: '{{ item.dest }}'
    state: hard
  loop:
    - { src: x, dest: y }
    - { src: z, dest: k }