Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add object to a dictionary in variables

Tags:

ansible

I'd like to add objects to a list in variables like this

system_user:
  - user1
system_users: "{{ system_users | union(system_user) }}"

It fails with a recursion error:

AnsibleError: recursive loop detected in template string

Is there any way to solve this? I want to create a definition file for each user in group_vars/all/ and then loop through them in a playbook. I don't want to redefine the list for every new user.

PS: There's a workaround: create variables with user names, like system_user_otto20 but it's not elegant at all.

like image 980
hryamzik Avatar asked Dec 09 '25 05:12

hryamzik


1 Answers

There is a similar opened issue: https://github.com/ansible/ansible/issues/17906

I suggest you not to use undefined variables in template strings to define them.

As another workaround you could use hash_behaviour=merge with following definitions:
group_vars/all.yml

system_users:
  user1:
  user2:

book1.yml

- hosts: localhost
  gather_facts: false
  vars:
    system_users:
      user3:
      user4:

  tasks:
    - debug: msg="{{ system_users | unique }}"

Running a playbook:

$ ansible-playbook book1.yml 
 [WARNING]: Host file not found: /etc/ansible/hosts

 [WARNING]: provided hosts list is empty, only localhost is available


PLAY [localhost] ***************************************************************

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": [
        "user4", 
        "user2", 
        "user3", 
        "user1"
    ]
}

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

unique is used to convert dictionary to unsorted list.

like image 62
Artem Gromov Avatar answered Dec 12 '25 01:12

Artem Gromov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!