Is it possible to set a fact of a list in Ansible?

Yes, this is possible. As mentioned in another answer, you can set an array using double quotes, like so:

- name: set foo fact to a list
  set_fact: 
    foo: "[ 'one', 'two', 'three' ]"

However, I thought I’d create another answer to indicate that it’s also possible to add to an existing array, like so:

- name: add items to foo list fact
  set_fact: 
    foo: "{{foo}} + [ 'four' ]"

Combining these and adding debugging as a playbook (which I’m calling facts.yml) like so:

---
- name: test playbook
  gather_facts: false
  hosts: localhost
  tasks:
    - name: set foo fact to an array
      set_fact: 
        foo: "[ 'one', 'two', 'three' ]"
    - debug: 
        var: foo
    - name: add items to foo array fact
      set_fact: 
        foo: "{{foo}} + [ 'four' ]"
    - debug: 
        var: foo

Produces (via ansible-playbook facts.yml) the following:

PLAY [test playbook] ******************************************************** 

TASK: [set foo fact to an array] ********************************************
ok: [localhost]

TASK: [debug var=foo] *******************************************************
ok: [localhost] => {
    "foo": [
        "one", 
        "two", 
        "three"
    ]
}

TASK: [add items to foo array fact] *****************************************
ok: [localhost]

TASK: [debug var=foo] *******************************************************
ok: [localhost] => {
    "foo": [
        "one", 
        "two", 
        "three", 
        "four"
    ]
}

PLAY RECAP ****************************************************************** 
localhost                  : ok=4    changed=0    unreachable=0    failed=0   

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)