ansible loop with items - loops

I can get information for Individual Package Version like this
- name: Print zsh Version
debug:
msg: "{{ ansible_facts.packages['zsh'][0].version }}"
when: " 'zsh' in ansible_facts.packages"
I am trying to use a loop for a list, but I am unable to quote the {{item}}.
software: ['ksh','zsh','bash']
- name: Print Softwre Versions
debug:
msg: "{{ ansible_facts.packages['{{item}}'][0].version }}"
with_items: "{{ software }}"
I get the following error message
"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute '{{item}}'
How do I make this work ?

You don't need to quote it or put it in curly bracers, you are already in curly bracers:
- name: Print software versions
debug:
msg: "{{ ansible_facts.packages[item][0].version }}"
vars:
software:
- 'ksh'
- 'zsh'
- 'bash'
loop: "{{ software }}"
Fully working playbook:
- hosts: localhost
gather_facts: no
tasks:
- name: Gather package facts
package_facts:
manager: auto
- name: Print software versions
debug:
msg: "{{ ansible_facts.packages[item][0].version }}"
vars:
software:
- 'ksh'
- 'zsh'
- 'bash'
loop: "{{ software }}"
Gives this recap:
PLAY [localhost] ***************************************************************
TASK [Gather package facts] ****************************************************
ok: [localhost]
TASK [Print software versions] *************************************************
ok: [localhost] => (item=ksh) => {
"msg": "2020.0.0-5"
}
ok: [localhost] => (item=zsh) => {
"msg": "5.8-3ubuntu1"
}
ok: [localhost] => (item=bash) => {
"msg": "5.0-6ubuntu1"
}
PLAY RECAP *********************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
PS: try not to mix YAML and JSON notation, your software array is in JSON, while the rest of your playbook is in YAML.

Related

Ansible nested_loops and product filter

I want to improve my ansible role because i have a lot of users to roll out.
For each user that is created there will be also multiple folders
created and this is very time consuming.
This is my users.yml file where i put every single user in (>1000)
ftp_users:
testuser1:
public_key: "public key"
password: "sha string"
home: /home/testuser1
customer_type: linux
testuser2:
public_key: "public key"
password: "sha string"
home: /home/testuser2
customer_type: windows
For this 2 users i want to create two folders "in" and "out".
Therefore i've created two tasks where i iterating over the dictionary:
- name: Create required out-folder for jailed users.
become: true
ansible.builtin.file:
owner: "{{ item.key }}"
group: ftpusers
mode: 0770
path: "/home/{{ item.value.customer_type }}/{{ item.key }}/out"
state: directory
loop: "{{ ftp_users | dict2items }}"
when: "'state' not in item.value or item.value.state == 'present'"
- name: Create required in-folder for jailed users.
become: true
ansible.builtin.file:
owner: "{{ item.key }}"
group: ftpusers
mode: 0770
path: "/home/{{ item.value.customer_type }}/{{ item.key }}/in"
state: directory
loop: "{{ ftp_users | dict2items }}"
when: "'state' not in item.value or item.value.state == 'present'"
This is very stupid because it takes a lot of time when 1000 users are rolled out.
I want to make one tasks to simultaniously create the "in" and "out" folder for every user, that i dont have to iterate two times over the whole dictionary.
What would be better nested_loops or the product filter?
Can someone show me an example?
Unfortunately block doesnt accept loop, so you could use include_tasks:
- name: "tips4"
hosts: localhost
gather_facts: false
vars:
ftp_users:
testuser1:
public_key: "public key"
password: "sha string"
home: /home/testuser1
customer_type: linux
testuser2:
public_key: "public key"
password: "sha string"
home: /home/testuser2
customer_type: windows
tasks:
- name: Create required out-folder for jailed users
include_tasks: create_folders.yml
loop: "{{ ftp_users | dict2items }}"
when: "'state' not in item.value or item.value.state == 'present'"
Create another file create_folders.yml in same folder than your playbook
# create_folders.yml
---
- name: Create required out-folder for jailed users
debug:
msg: "owner: {{ item.key }}, path: /home/{{ item.value.customer_type }}/{{ item.key }}/out"
- name: Create required in-folder for jailed users
debug:
msg: "owner: {{ item.key }}, path: /home/{{ item.value.customer_type }}/{{ item.key }}/in"
result:
TASK [Create required out-folder for jailed users]
ok: [localhost] => {
"msg": "owner: testuser1, path: /home/linux/testuser1/out"
}
TASK [Create required in-folder for jailed users]
ok: [localhost] => {
"msg": "owner: testuser1, path: /home/linux/testuser1/in"
}
TASK [Create required out-folder for jailed users]
ok: [localhost] => {
"msg": "owner: testuser2, path: /home/windows/testuser2/out"
}
TASK [Create required in-folder for jailed users]
ok: [localhost] => {
"msg": "owner: testuser2, path: /home/windows/testuser2/in"
}
with this playbook, in and out folder are created in same loop, so you just iterate one time...

Ansible cannot invoke variable for hostname in playbook

I need to add new users to multiple Ubuntu servers. Unfortunately, the password and username are not consistent. Every machine has its own username and the password cannot be the same. For example, host-1 will have a user account host-1_username with password host-1_password and host-2 will have a user account host-2_username with password host-2_password, and so on.
I would like to do that by Ansible. I have a list.yaml file:
---
list:
- hostname: host-1
username: host-1_username
password: host-1_password
- hostname: host-2
username: host-2_username
password: host-2_password
- hostname: host-3
username: host-3_username
password: host-3_password
Here is my Ansible playbook:
- name: Crate new user
vars_files:
- list.yml
hosts: "{{ item.hostname }}"
remote_user: root
become: true
tasks:
- name: Create new user
ansible.builtin.user:
name: "{{ item.username }}"
groups: sudo
password: "{{ item.password | password_hash('sha512') }}"
shell: /bin/bash
- name: Modify sshd_config
ansible.builtin.lineinfile:
dest: /etc/ssh/sshd_config
line: 'AllowUsers {{ item.username }}'
loop: "{{ list }}"
But looks like Ansible cannot invoke the variable to add into hosts column:
ERROR! couldn't resolve module/action 'hosts'. This often indicates a misspelling, missing collection, or incorrect module path.
I am very new to Ansible, any help is appreciated!
Given the data
shell> cat list.yml
users_list:
- hostname: host-1
username: host-1_username
password: host-1_password
- hostname: host-2
username: host-2_username
password: host-2_password
- hostname: host-3
username: host-3_username
password: host-3_password
Create an inventory file, e.g.
shell> cat hosts
host-1
host-2
host-3
Convert the data to dictionaries, e.g.
- hosts: all
gather_facts: false
vars_files:
- list.yml
tasks:
- set_fact:
users_dict: "{{ users_list|items2dict(key_name='hostname', value_name='username') }}"
psswd_dict: "{{ users_list|items2dict(key_name='hostname', value_name='password') }}"
run_once: true
gives
users_dict:
host-1: host-1_username
host-2: host-2_username
host-3: host-3_username
and
psswd_dict:
host-1: host-1_password
host-2: host-2_password
host-3: host-3_password
Use the dictionaries to select the hosts' specific users and passwords, e.g.
- debug:
msg: "Create user: {{ users_dict[inventory_hostname] }}
password: {{ psswd_dict[inventory_hostname] }}"
gives
TASK [debug] ***************************************************************
ok: [host-1] =>
msg: 'Create user: host-1_username password: host-1_password'
ok: [host-2] =>
msg: 'Create user: host-2_username password: host-2_password'
ok: [host-3] =>
msg: 'Create user: host-3_username password: host-3_password'
You can omit the inventory file and create a playbook completely driven by the data. Create dynamic group my_group in the first play and use it in the second one. The playbook below gives the same results
- name: Create dynamic group of the hosts from users_list
hosts: localhost
gather_facts: false
vars_files:
- list.yml
tasks:
- add_host:
name: "{{ item.hostname }}"
groups: my_group
loop: "{{ users_list }}"
- name: Create users
hosts: my_group
gather_facts: false
vars_files:
- list.yml
tasks:
- set_fact:
users_dict: "{{ users_list|items2dict(key_name='hostname', value_name='username') }}"
psswd_dict: "{{ users_list|items2dict(key_name='hostname', value_name='password') }}"
run_once: true
- debug:
var: users_dict
run_once: true
- debug:
var: psswd_dict
run_once: true
- debug:
msg: "Create user: {{ users_dict[inventory_hostname] }}
password: {{ psswd_dict[inventory_hostname] }}"

In Ansible how to execute a role while looping over an array in the playbook

I want to iterate over array and pass each array element value to role from playbook but it is not working in ansible, Can some one help
---
#play book
- name: create config for instance
hosts: all
vars:
LIST: [Asia, Americas, Artic, Antartic ,Oceania,Europe,Africa]
connection: local
roles:
- role: create_config
debug:
msg : "{{ item }}"
vars:
VENUE: "{{ item }}"
with_items:
- "{{ LIST }}"
## Role
- name: create directory structure
file:
path: "{{item}}"
state: directory
mode: 0755
with_items:
- "{{dest_folder}}/{{instance_name}}/{{VENUE}}"
I am getting below error
ansible-playbook -i inventory/AlgoTest_SP create_pkg_1.yml
PLAY [create config for instance] **************************************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************************************************************
ok: [localhost]
TASK [create_config : create directory structure] *******************************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "{{ item }}: 'item' is undefined"}
PLAY RECAP ****************************************************************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
To be able to loop over roles, you need the include_role task, as in:
- name: create config for instance
hosts: localhost
vars:
LIST: [Asia, Americas, Artic, Antartic ,Oceania,Europe,Africa]
tasks:
- include_role:
name: create_config
vars:
VENUE: "{{ item }}"
with_items:
- "{{LIST}}"
cat roles/create_config/tasks/main.yml
- debug:
msg: "{{VENUE}}"
- name: create directory structure
file:
path: "{{item}}"
state: directory
mode: 0755
with_items:
- "{{inventory_hostname}}/{{VENUE}}"
Resulting in:
$ ansible-playbook 69045121.yml
PLAY [create config for instance] ********************************************************************************************************************************************************************************************************************************************************************************************
TASK [Gathering Facts] *******************************************************************************************************************************************************************************************************************************************************************************************************
ok: [localhost]
TASK [include_role : create_config] ******************************************************************************************************************************************************************************************************************************************************************************************
TASK [create_config : debug] *************************************************************************************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"msg": "Asia"
}
TASK [create_config : create directory structure] ****************************************************************************************************************************************************************************************************************************************************************************
changed: [localhost] => (item=localhost/Asia)
TASK [create_config : debug] *************************************************************************************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"msg": "Americas"
}
[...] and so on
As a final note, you could, and should, likely handle this differently. Also, you have clash in the item variable name from the outer (playbook) and inner (role) with_items, you can use loop_var to set a different looping varname.

Iterate a list within a dictionary in ansible

I have a variable structured like this. I have successfully used this with with_dict with a single key in the accessible_from
vars:
mysql_dbs:
db1:
user: db1_user
pass: "password"
accessible_from: localhost
db2:
user: db2_user
pass: "password2"
accessible_from: '%'
This is applied using the mysql_db ansible module, like this:
- name: Configure mysql users
mysql_user: name={{ item.value.user }} password={{ item.value.pass }} host={{ item.value.accessible_from | default('localhost')}} priv={{ item.key }}.*:ALL state=present
with_dict: "{{ mysql_dbs }}"
I would like accessible_from to have the ability to be a list. It doesn't matter if it has to be a list, but a single key/value pair is not enough :) So for example:
vars:
mysql_dbs:
db1:
user: db1_user
pass: "password"
accessible_from:
- server1
- server2
- localhost
db2:
user: db2_user
pass: "password"
accessible_from:
- '%'
So - the aim is to create all the DBs and users in one play. I've tried playing around with with_subelements, without success. Is it actually possible to do this? Or is it necessary to restructure the data, or rewrite the play? I'll do that if I have to, but I was wondering if there was another way round it.
First: You may refactor your mysql_dbs into list (because in with_subelements you can't refer items' keys), like:
mysql_dbs:
- name: db1
user: db1_user
pass: "password"
accessible_from:
- server1
- server2
- localhost
- name: db2
user: db2_user
pass: "password2"
accessible_from:
- '%'
And user with_subelements:
- mysql_user: name={{ item[0].user }} password={{ item[0].pass }} host={{ item[1] }} priv={{ item[0].name }}.*:ALL state=present
with_subelements:
- "{{ mysql_dbs }}"
- accessible_from
But this will fail if accessible_from is undefined for any db. You may use skip_missing, but this will skip entire db. So you can't omit accessible_from in this case.
Second: You may use helper set_fact to form a list with key and value, also defaulting accessible_from to localhost. This will work without refactoring your data:
- set_fact:
db_name: "{{ item.key }}"
db_params: "{{ dict(accessible_from=['localhost']) | combine(item.value) }}"
with_dict: "{{ mysql_dbs }}"
register: mysql_dbs_fact
loop_control:
label: "{{ item.key }}"
- debug:
msg: "mysql_user: name={{ item[0].db_params.user }} password={{ item[0].db_params.pass }} host={{ item[1] }} priv={{ item[0].db_name }}.*:ALL state=present"
with_subelements:
- "{{ mysql_dbs_fact.results | map(attribute='ansible_facts') | list }}"
- db_params.accessible_from
loop_control:
label: "{{ item[0].db_name }}->{{ item[1] }}"
Try this:
vars:
mysql_dbs:
db1:
user: db1_user
pass: "password"
accessible_from:
- acc_from: server1
- acc_from: server2
- acc_from: localhost
db2:
user: db2_user
pass: "password"
accessible_from:
- acc_from: '%'
tasks:
- name: Configure mysql users
debug: msg="{{ item.0.user }} password={{ item.0.pass }} host={{ item.1.acc_from }} priv={{ item.0 }}.*:ALL state=present"
with_subelements:
- "{{ mysql_dbs }}"
- accessible_from

How to iterate through N level children of hosts using Ansible Playbook?

I know how to achieve this using host_vars but the problem with it is the host files can get convoluted so I'm leaning towards ini files where I can put all the data in one file. This SO post helped me have an idea how to put a collection in a variable for a particular host.
I have this sample inventory:
;hosts.yml
[web1]
example1.com databases=["example1_com","mysql"]
example2.com databases=["example1_com","mysql"]
[web1:vars]
ansible_host=10.0.16.21
[web2]
example3.com databases=["example3_com"]
example4.com databases=["example4_com","mysql"]
[web2:vars]
ansible_host=10.0.16.22
[web:children]
web1
web2
Now I wanted to loop through each hosts using the the web group and iterate through the databases host var.
I did something like this:
---
- debug:
msg: "{{ item }} - {{ hostvars[item]['databases'] }} "
with_items:
- "{{ groups['web'] }}"
and the output is:
ok: [localhost] => (item=example1.com) => {
"item": "example1.com",
"msg": "example1.com - [example1_com,mysql] "
}
ok: [localhost] => (item=example2.com) => {
"item": "example2.com",
"msg": "example2.com - [example1_com,mysql] "
}
ok: [localhost] => (item=example3.com) => {
"item": "example3.com",
"msg": "example3.com - [example3_com] "
}
ok: [localhost] => (item=example4.com) => {
"item": "example4.com",
"msg": "example4.com - [example4_com,mysql] "
}
I tried achieving this using with_sublements loop but the problem is the 2nd element needs to be dynamic which is not possible with_subelements.
with_subelements:
- "{{ groups['web'] }}"
- {{ hostvars[item]['databases'] }} #item is dynamic, this will cause an undefined host error.
It's not 100% clear to me what your original approach was, and if the code in your question was meant to represent your new approach (since you are still referencing hostvars there). I think you need to work more with specifying the groups you want affected within the playbook (hosts: web) or on the command line (-l web) when running the playbook to run the tasks only for those hosts you want, rather than trying to get the group dynamically within the task itself.
Regarding the linked question/answer, where a way of defining a list within a variable was discussed: you need to make sure to enclose the list data within single quotes, e.g. '["example1_com","mysql"]'.
Given that, if you simply want to iterate over a list from a host variable defined in an inventory file, you can do the following:
Inventory File "inv"
[web1]
example1.com databases='["example1_com","mysql"]'
example2.com databases='["example1_com","mysql"]'
[web1:vars]
ansible_host=10.0.16.21
[web2]
example3.com databases='["example3_com"]'
example4.com databases='["example4_com","mysql"]'
[web2:vars]
ansible_host=10.0.16.22
[web:children]
web1
web2
Playbook File "test.yml"
---
- hosts: web
gather_facts: no
tasks:
- debug: msg="Host is {{ inventory_hostname }}. Database is {{ item }}"
with_items:
- "{{ databases }}"
You can then run the playbook:
ansible-playbook test.yml -i inv
generating the following output:
PLAY ***************************************************************************
TASK [debug] *******************************************************************
ok: [example3.com] => (item=example3_com) => {
"item": "example3_com",
"msg": "Host is example3.com. Database is example3_com"
}
ok: [example1.com] => (item=example1_com) => {
"item": "example1_com",
"msg": "Host is example1.com. Database is example1_com"
}
ok: [example1.com] => (item=mysql) => {
"item": "mysql",
"msg": "Host is example1.com. Database is mysql"
}
ok: [example2.com] => (item=example1_com) => {
"item": "example1_com",
"msg": "Host is example2.com. Database is example1_com"
}
ok: [example2.com] => (item=mysql) => {
"item": "mysql",
"msg": "Host is example2.com. Database is mysql"
}
ok: [example4.com] => (item=example4_com) => {
"item": "example4_com",
"msg": "Host is example4.com. Database is example4_com"
}
ok: [example4.com] => (item=mysql) => {
"item": "mysql",
"msg": "Host is example4.com. Database is mysql"
}
PLAY RECAP *********************************************************************
example1.com : ok=1 changed=0 unreachable=0 failed=0
example2.com : ok=1 changed=0 unreachable=0 failed=0
example3.com : ok=1 changed=0 unreachable=0 failed=0
example4.com : ok=1 changed=0 unreachable=0 failed=0
If you properly structure your playbook, you can also set it up to run different sets of tasks for different host groups (perhaps including the tasks from an external file so you DRY). Or you could simply specify hosts: all in the playbook, and use command line limiting to only run the tasks against a specific set of hosts.

Resources