Ansible - Append value to variable

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

---
- hosts: localhost
  vars:
    foo: "Hello"
  tasks:
  - name: output the 'foo' variable
    debug:
      var: foo
...

 

Something like this should be returned.

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

 

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

---
- hosts: localhost
  vars:
    foo: "Hello"
  tasks:
  - name: append 'World' to the 'foo' variable
    set_fact:
      foo: "{{ foo }} World"

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

 

One of the issues with Ansible when statements is that sometimes, you will find yourself creating two tasks, one when a condition evaulated to true, another when a condition evaulates to false.

- name: append 'World' to the 'foo' variable
    set_fact:
      foo: "{{ foo }} World"
    when:
      - bar is defined

- name: append 'Earth' to the 'foo' variable
    set_fact:
      foo: "{{ foo }} Earth"
    when:
      - bar is undefined

 

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

---
- hosts: localhost
  vars:
    foo: "Hello"
  tasks:
  - name: append 'World' to the 'foo' variable
    set_fact:
      foo: "{% if foo is defined %}{{ foo }} World{% else %}{{ foo}} Earth{% endif %}"

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

 



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 9ebeb 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   |