How should i write the yaml file for use in ansible variable?
I started to deploying an ansible server, and i was trying to create 5 users in the client hosts, through a playbook (add5userslist.yaml), with a loop that uses variables in a list from another file (userslist.yaml), but isnt working.
And...this is what ansible retrieves when i try to use this playbook with that list:
Seems like the problem is the list used in fact ansible doesnt even sees that as a list, but well im new in ansible and dont know what should that file have.
the playbook code:
- hosts: GrupoPrincipal
tasks:
- include_vars:
file: /etc/ansible/playbooks/userslist.yaml
name: userslist
- name: Add 5 users from a list
ansible.builtin.user:
name: "{{ item.name }}"
password: "{{'abc123.' | password_hash('sha512')}}"
loop: "{{ userslist }}"
the userlist.yaml code is only this, is the only thing that worked a little:
name: 'user1'
name: 'user2'
name: 'user3'
name: 'user4'
name: 'user5'
@Martin helped me with the problem above, but now im trying with more than 1 item type, doenst seems to work, here is how i have the new code
- hosts: GrupoPrincipal
tasks:
- include_vars:
file: /etc/ansible/playbooks/userslist.yaml
name: userslist
- name: Add 5 users from a list and put them in groups
ansible.builtin.user:
name: "{{ item.names }}"
groups: "{{ item.groups }}"
password: "{{'abc123.' | password_hash('sha512')}}"
loop:
- { names: '{{ userslist.names }}', groups: '{{ userslist.groups }}' }
and the new list yaml:
names:
- user1
- user2
- user3
- user4
- user5
groups:
- users
- users
- users
- users
- users
You're telling to your task to loop over an object who's representing your files variables but loop require a list.
You have to define your var_files like :
users:
- user1
- user2
And then in your main playbook, removing "item.name" in order to just use the item, and precise inside your varfile what variable you use :
- hosts: GrupoPrincipal
tasks:
- include_vars:
file: /etc/ansible/playbooks/userslist.yaml
name: userslist
- name: Add 5 users from a list
ansible.builtin.user:
name: "{{ item }}"
password: "{{'abc123.' | password_hash('sha512')}}"
loop: "{{ userslist.users }}"