FreeKB - Ansible set_fact module (array of values)
Ansible - set_fact module (array of values)

The set_fact module can be used to create an array of values, also known as a list. The ansible-doc set_fact command can be used to show the Ansible documention on the set_tact module.

In this example, the "list" fact contains two values, "Hello" and "World".

- set_fact: 
    list: "[ 'Hello', 'World']"

 

Or like this.

- set_fact:
    list:
      - Hello
      - World

 

The debug module can be used to output the values in the list. Notice the double curley braces {{ ... }}. Jinja2 uses double curley braces for variables.

- debug: 
    msg: "{{ list }}"

 

Which should produce the following.

TASK [debug] 
ok: [server1.example.com] => {
    "msg": [
        "Hello",
        "World"
    ]
}

 


Append values

Here is how you would append values to the end of the list.

- set_fact: 
    list: "{{ list }} + [ 'new value' ]"

 

The debug module should now produce the following.

TASK [debug] 
ok: [server1.example.com] => {
    "msg": [
        "Hello",
        "World",
        "new value"
    ]
}

 


Looping through list

The loop parameter can be used to loop through the values.

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

 

Likewise, the with_items parameter can be used as well. However, Ansible recommends using the loop option, as the loop option is meant to supercede the with_items option.

- debug: 
    msg: "{{ item }}"
  with_items: "{{ list }}"

 

Looping through the list should return the following.

TASK [debug] 
ok: [server1.example.com] => (item=Hello) => {
    "msg": "Hello"
}
ok: [server1.example.com] => (item=World) => {
    "msg": "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 60934 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   |