Bootstrap FreeKB - Ansible - Appending values to a variable using set_fact
Ansible - Appending values to a variable using set_fact

Updated:   |  Ansible articles

Let's say you are using the vars plugin to set the "foo" variable to contain a value of "bar". The debug module can be used to confirm that the foo variable contains bar.

---
- hosts: localhost
  vars:
    foo: "bar"
  tasks:
  - debug:
      var: foo
...

 

Something like this should be returned.

ok: [localhost] => {
    "foo": "bar"
}

 

The set_fact module can be used to update the foo variable. Here is how you could append "Hello" and "World" to the foo variable.

---
- hosts: localhost
  vars:
    foo: "bar"
  tasks:
  - set_fact:
      foo: "{{ foo }} Hello"

  - set_fact:
      foo: "{{ foo }} World"

  - name: output the 'foo' variable
    debug:
      var: foo
...

 

Which should now output the following.

ok: [localhost] => {
    "foo": "bar Hello World"
}

 

Sometimes you will find yourself creating two tasks, one when a condition evaulates to true, another when a condition evaulates to false.

---
- hosts: localhost
  vars:
    foo: "bar"
  tasks:
  - set_fact:
      foo: "{{ foo }} Hello"
    when: bar is defined

  - set_fact:
      foo: "{{ foo }} World"
    when: bar is undefined
...

 

Jinja2 if statements can be used to consolidate this to one task.

---
- hosts: localhost
  vars:
    foo: "bar"
  tasks:
  - set_fact:
      foo: "{% if foo is defined %}{{ foo }} Hello{% else %}{{ foo}} World{% endif %}"
...

 




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 4a6375 in the box below so that we can be sure you are a human.