Bootstrap FreeKB - Ansible - Create an array of value using the set_fact module
Ansible - Create an array of value using the set_fact module

Updated:   |  Ansible articles

If you are not familiar with modules, check out Ansible - Getting Started with Modules.

The set_fact module can be used to create an array of values, also known as a list. 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"
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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