FreeKB - Ansible Getting Started with Hashes (key value pairs)
Ansible - Getting Started with Hashes (key value pairs)

There are 20+ ways to create variables in Ansible, such as on the command line, in a playbook, or from a file, just to name a few. Refer to Ansible - Getting Started with Variables.

Here is how you would create an hash of food using the vars plugin.

vars:
  food: 
    - { key: 'fruit', value: 'banana' }
    - { key: 'fruit', value: 'orange' }
    - { key: 'veggy', value: 'onion' }
    - { key: 'veggy', value: 'pepper' }

 

Or like this.

vars:
  food:
    - key: fruit
      value: banana
    - key: fruit
      value: orange
    - key: veggy
      value: onion
    - key: veggy
      value: pepper

 

The debug module can be used to output the hash, like this.

- name: output the contents of the 'food' hash
  debug: 
    var: food

 

Which should return the following.

TASK [output the contents of the 'food' hash]
ok: [server1.example.com] => {
    "food": [
        {
            "key": "fruit",
            "value": "apple"
        },
        {
            "key": "fruit",
            "value": "banana"
        },
        {
            "key": "veggy",
            "value": "onion"
        },
        {
            "key": "veggy",
            "value": "pepper"
        }
    ]
}

 


Looping through a hash

The following parameters can be used to loop through each item in a hash.

In this example, the loop parameter is used to loop over the food hash.

- name: "loop through the 'food' hash"
  debug: 
    msg: "{{ item }}"
  loop:
    - { key: 'fruit', value: 'banana' }
    - { key: 'fruit', value: 'orange' }
    - { key: 'veggy', value: 'onion' }
    - { key: 'veggy', value: 'pepper' }

 

Which should return the following. Note that some or all of the output can be suppressed or limited using the no_log or loop_control parameters.

TASK [loop through the 'food' hash] 
ok: [server1.example.com] => (item=apple) => {
    "msg": {
        "key": "fruit",
        "value": "apple"
    }
}
ok: [openshift1.software.eng.us] => (item={'key': 'fruit', 'value': 'banana'}) => {
    "msg": {
        "key": "fruit",
        "value": "banana"
    }
}
ok: [openshift1.software.eng.us] => (item={'key': 'veggy', 'value': 'onion'}) => {
    "msg": {
        "key": "veggy",
        "value": "onion"
    }
}
ok: [openshift1.software.eng.us] => (item={'key': 'veggy', 'value': 'pepper'}) => {
    "msg": {
        "key": "veggy",
        "value": "pepper"
    }
}

 

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 87fa4 in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |