FreeKB - Ansible vars parameter (variables, arrays, lists)
Ansible - vars parameter (variables, arrays, lists)

The vars module is used to create variables and arrays (aka lists).  In this example, a variable named "foo" is created with a value of "Hello World".

vars:
  foo: "Hello World"

 

The debug module can be used to print the value of the "foo" variable. Notice the double curley braces {{ ... }}. Jinja2 uses double curley braces for variables.

- name: "output the contents of the 'foo' variable"
  debug: 
    msg: "{{ foo }}"

 

Which should return the following.

TASK [output the contents of the 'foo' variable]
ok: [server1.example.com] => {
    "msg": "Hello World"
}

 


One key with multiple values (array)

In this example, the "foo" key has two values, "Hello" and "World". When there are two or more items, this is now an array (aka list).

vars:
  foo: 
    - Hello 
    - World

 

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

- name: "output the contents of the 'foo' array"
  debug: 
    msg: "{{ foo }}"

 

Which should return the following. Notice the bracket characters [ ], which means this is indeed an array.

TASK [output the contents of the 'foo' array]
ok: [server1.example.com] => {
    "msg": [
        "Hello"
        "World",
    ]
}

 

Additionally, the loop or with_items parameters can be used to loop through each item in the array, like this.

- name: "loop through the 'foo' array"
  debug: 
    msg: "{{ item }}"
  loop: "{{ foo }}"

 

Which should return the following.

TASK [loop through the 'foo' array] 
ok: [server1.example.com] => (item=Hello) => {
    "msg": "Hello"
}
ok: [server1.example.com] => (item=World) => {
    "msg": "World"
}

 


key value pairs

Or, key value pair can be created like this.

vars:
  variables:
    - key: foo
      value: "Hello"
    - key: bar
      value: "World"

 

The debug and loop modules can be used to print the key value pairs.

- debug: 
    msg: "{{ item }}"
  loop: "{{ variables }}"

 

Which should return the following.

TASK [debug] 
ok: [server1.example.com] => (item={u'value': u'Hello', u'key': u'foo'}) => {
    "msg": {
        "key": "foo",
        "value": "Hello"
    }
}
ok: [server1.example.com] => (item={u'value': u'World', u'key': u'bar'}) => {
    "msg": {
        "key": "bar",
        "value": "World"
    }
}


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 4f046 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   |