This question already has an answer here:
Ansible with_subelements
(1 answer)
Closed 4 years ago.
I'm trying to create a bunch of groups and members for a custom module using an external var file. All I need to do is to access a list of dictionaries in a list.
I have tried many things but the closest I might have for now is:
vars.yml:
groups_and_members:
FIRST_GROUP:
"memberx":
octet: 1
action: add
"nostandardy":
octet: 3
action: add
"memberz":
octet: 5
action: add
OTHER_GROUP:
"member1":
octet: 7
action: delete
"unexpected":
octet: 1
action: add
task.yml:
- name: "add members"
mymodule:
cmd: "{{ item.value.action }}"
parameters:
name: "{{ item.key }}"
octet: "{{ item.value.octet }}"
with_items: "{{ groups_and_members }}"
So the idea is to take from the list (groups_and_members).value(FIRST_GROUP in the first iteration). and use its members attribute in cmd. But because I don't know the name of the group nor the name of the member, I'm not sure how to access them. I will not know the name of the groups or the members beforehand. The dicts should be in a list, to not have to make a new task in case there's a new dict.
How can I access the group, member and member attributes?
I have tried with_dict, with_subelements etc. but can't seem to figure it out.
I should have formatted the list of dictionaries differently. This is a duplicate question: Answer here:
Ansible with_subelements
My vars should have looked like this:
groups_members:
- groupname: FIRST_GROUP
members:
- name: memberx
octet: "1"
action: add
- name: nostandardy
octet: "3"
action: add
- name: memberz
octet: "2"
action: add
- name: unexpected
octet: "1"
action: add
- groupname: RHOST
members:
- member: other1
octet: "1"
action: add
Could then be accessed as item.1.action or item.0.value and task be with
with_subelements:
- "{{ groups_members }}"
- members
Related
I have this playbook and I need to find a way to display the values of the list of dictionaries under prerequisite knowing that we have different key names. how can I display theses values keeping the same syntax of my playbook?
Expected output:
"linux/mysql/8.0.19/prerequis/mysql-community-common-8.0.19-1.el7.x86_64.rpm"
"mysql-community-common-8.0.19-1.el7.x86_64"
"linux/mysql/8.0.19/prerequis/mysql-community-libs-8.0.19-1.el7.x86_64.rpm"
"mysql-community-libs-8.0.19-1.el7.x86_64"
"linux/mysql/8.0.19/prerequis/mysql-community-client-8.0.11-1.el7.x86_64.rpm"
"mysql-community-client-8.0.11-1.el7.x86_64"
"linux/mysql/8.0.19/prerequis/mysql-shell-8.0.19-1.el7.x86_64.rpm"
"mysql-shell-8.0.19-1.el7.x86_64"
- name: "extract values from a list of dictionaries"
hosts: localhost
tasks:
- name: "adding variables"
set_fact:
products:
mysql_8_0_19:
CentOS_7:
signature: "mysql-community-server-8.0.19-1.el7.x86_64"
url: "linux/mysql/8.0.19/mysql-community-server-8.0.19-1.el7.x86_64.rpm"
pymysql_url: "linux/mysql/8.0.19/prerequis/PyMySQL-0.9.3.tar.gz"
prerequisite:
- mysql_c_common_url: "linux/mysql/8.0.19/prerequis/mysql-community-common-8.0.19-1.el7.x86_64.rpm"
mysql_c_common_signature: "mysql-community-common-8.0.19-1.el7.x86_64"
- mysql_c_libs_url: "linux/mysql/8.0.19/prerequis/mysql-community-libs-8.0.19-1.el7.x86_64.rpm"
mysql_c_libs_signature: "mysql-community-libs-8.0.19-1.el7.x86_64"
- mysql_c_client_url: "linux/mysql/8.0.19/prerequis/mysql-community-client-8.0.11-1.el7.x86_64.rpm"
mysql_c_client_signature: "mysql-community-client-8.0.11-1.el7.x86_64"
- mysql_shell_url: "linux/mysql/8.0.19/prerequis/mysql-shell-8.0.19-1.el7.x86_64.rpm"
mysql_shell_signature: "mysql-shell-8.0.19-1.el7.x86_64"
- name: " display "
debug:
msg: "{{ item }}"
with_items: "{{ products.mysql_8_0_19.prerequisite }}"'
Getting the values of a dictionary in Ansible with an "unknown" set of keys usually call for the usage of dict2items.
Your use case does fit the bill, you just have to map this filter on all elements of the prerequisite list, then flatten it and finally extract the values with another map filter.
So, you can achieve what you need with the task:
- debug:
msg: "{{ item }}"
loop: >-
{{
products.mysql_8_0_19.prerequisite
| map('dict2items')
| flatten
| map(attribute='value')
}}
You might want to add a | list filter at the end if you are on an old version of Ansible and get an error like <generator object do_map at 0x7f3xxxxx>
Given the task:
- debug:
var: >-
products.mysql_8_0_19.prerequisite
| map('dict2items')
| flatten
| map(attribute='value')
vars:
products:
mysql_8_0_19:
prerequisite: "{{ prerequisite }}"
prerequisite:
- mysql_c_common_url: >-
linux/mysql/8.0.19/prerequis{#- allows line wrap -#}
/mysql-community-common-8.0.19-1.el7.x86_64.rpm
mysql_c_common_signature: >-
mysql-community-common-8.0.19-1.el7.x86_64
- mysql_c_libs_url: >-
linux/mysql/8.0.19/prerequis{#- allows line wrap -#}
/mysql-community-libs-8.0.19-1.el7.x86_64.rpm
mysql_c_libs_signature: >-
mysql-community-libs-8.0.19-1.el7.x86_64
- mysql_c_client_url: >-
linux/mysql/8.0.19/prerequis{#- allows line wrap -#}
/mysql-community-client-8.0.11-1.el7.x86_64.rpm
mysql_c_client_signature: >-
mysql-community-client-8.0.11-1.el7.x86_64
- mysql_shell_url: >-
linux/mysql/8.0.19/prerequis{#- allows line wrap -#}
/mysql-shell-8.0.19-1.el7.x86_64.rpm
mysql_shell_signature: >-
mysql-shell-8.0.19-1.el7.x86_64
This yields:
- linux/mysql/8.0.19/prerequis/mysql-community-common-8.0.19-1.el7.x86_64.rpm
- mysql-community-common-8.0.19-1.el7.x86_64
- linux/mysql/8.0.19/prerequis/mysql-community-libs-8.0.19-1.el7.x86_64.rpm
- mysql-community-libs-8.0.19-1.el7.x86_64
- linux/mysql/8.0.19/prerequis/mysql-community-client-8.0.11-1.el7.x86_64.rpm
- mysql-community-client-8.0.11-1.el7.x86_64
- linux/mysql/8.0.19/prerequis/mysql-shell-8.0.19-1.el7.x86_64.rpm
- mysql-shell-8.0.19-1.el7.x86_64
I have got an ansible problem where I have to change the items of a list in some cases.
Imagine, if there is the string "apple0" and another digit from 0 to 9 the list element should be appended by the string T2. If there is any other element, lets say banana or peach, it should stay as it is.
---
- hosts: localhost
become: no
vars:
fruit: [banana,apple05,apple04,peach]
tasks:
- name: my task
set_fact:
"{{ item | replace('^apple0[0-9]*$','?1T2') }}"
loop: "{{fruit}}"
- debug:
msg:
- "{{fruit}}"
suggested output:
ok: [localhost] => {
"msg": [
[
"banana",
"apple05T2",
"apple04T2",
"peach"
]
]
}
For example
- set_fact:
fruit2: "{{ fruit2|default([]) + [(item is match('^apple0\\d$'))|
ternary(item ~ 'T2', item)] }}"
loop: "{{ fruit }}"
gives
fruit2:
- banana
- apple05T2
- apple04T2
- peach
The next option is to map the filter regex_replace. For example, the task below gives the same result
- set_fact:
fruit2: "{{ fruit|map('regex_replace', my_regex, my_replace)|list }}"
vars:
my_regex: '^(apple0\d)$'
my_replace: '\1T2'
I have a variable dir_lst_raw in an ansible playbook whose value is a list as shown below:
"dir_lst_raw": [
"/path1/dir1/user",
"/path2/dir2/admin",
"/path3/dir3/user.ansible_backup_2020-03-16",
"/path1/dir1/config.ansible_backup_2020-03-16",
"/path2/dir2/dir3/somefile"
]
I need to remove all the lines containing .ansible_backup_ and save to another variable as a list.
I've googled for regex and tried to not match the pattern with the select filter as below:
- set_fact:
dir_lst: "{{ dir_lst_flt_r | select('match','(^.ansible_backup_)+') | list }}"
but the new variable dir_lst turned out as an empty list. I am expecting dir_lst as below:
"dir_lst_raw": [
"/path1/dir1/user",
"/path2/dir2/admin",
"/path2/dir2/dir3/somefile"
]
Could somebody please suggest how can I get it done?
Q: "Remove all the lines containing .ansible_backup_"
A: The task below does the job
- set_fact:
dir_lst: "{{ dir_lst_raw|reject('match', my_regex)|list }}"
vars:
my_regex: '^(.*)\.ansible_backup_(.*)$'
- debug:
var: dir_lst
gives
dir_lst:
- /path1/dir1/user
- /path2/dir2/admin
- /path2/dir2/dir3/somefile
i got a problem how to consume the following command output in Ansible
basically im trying to get the list of Active Directory OUs and loop over that list to search for specific name. My script works well when multiple OUs exists but i have an issue when only single OU exists. Explained below
tasks:
- name: PS - Pull System OUs from AD
win_command: powershell -
args:
stdin: "Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchScope 1 -SearchBase 'OU=SYSTEMS,DC=domain,DC=int' -Server domain.int | select-object name | ConvertTo-json"
become: yes
register: ou_reg_out
- name: Select Systems OU
block:
- name: Set list of standardized OUs as facts
set_fact:
ou_reg_list: "{{ ou_reg_out.stdout }}"
- name: Set System OU for system
set_fact:
ou_name: "OU={{item.name}}"
loop: "{{ ou_reg_list }}"
when: (item.name|upper) == (srv_type|upper)
when: ou_reg_out.stdout|length != 0
basically i need to be able to loop over the ou_reg_out.stdout.
It works when command returns multiple OUs as ou_reg_out.stdout returns list:
ou_reg_out.stdout:
- { name: OU1 }
- { name: OU2 }
issue is when only single OU exists , command doesnt return the list
ou_reg_out.stdout:
{ name: OU1 }
Any idea how to workaround this problem ?
Test the type of the variable and branch the code.
json_query filter helps to select the items from the list. Then ternary helps to conditionally select the value. The value of the first item that matches the condition is used. Defaults to 'NOTFOUND'.
For example the play bellow for both versions of ou_reg_list
- hosts: localhost
vars:
ou_reg_list:
- { name: OU1 }
- { name: OU2 }
# ou_reg_list:
# { name: OU1 }
srv_type: 'ou1'
tasks:
- set_fact:
ou_name: "OU={{ (ou_reg_list.name == srv_type|upper)|
ternary( ou_reg_list.name, 'NOTFOUND') }}"
when: ou_reg_list is mapping
- block:
- set_fact:
ou_names: "{{ ou_reg_list|json_query(query) }}"
vars:
query: "[?name=='{{ srv_type|upper }}'].name"
- set_fact:
ou_name: "OU={{ (ou_names|length > 0)|
ternary( ou_names.0, 'NOTFOUND') }}"
when: ou_reg_list is not mapping
- debug:
var: ou_name
gives
"ou_name": "OU=OU1"
I am trying to concatenate a string which is referenced as variable with a nested list
I looked into the options of using the set_fact and join but to no avail.
#config.yml
- name: concatenate
module_name:Test
state: present
port: {{ env_dc }}{{item.ports}}
with_items:
- "{{ my_list }}"
#group_vars\all.yml
env_dc: uk
my_list:
- {name: switch1, ports: [p1, p2, p3, p4]}
I am expecting the following output:
ukp1
ukp2
ukp3
ukp4
But I am getting;
"item": {
"ports": [
"p1",
"p2",
"p3",
"p4"
]
Actual Playbook:
Error message:
If you write this:
port: {{ env_dc }}{{item.ports}}
You are not producing a new list formated by concatenating the value in env_dc with each item in item.ports; you are simply creating a new string that has the contents of env_dc followed by the string representation of item.ports. That is, in your example, that would evaluate to something like:
uk['p1', 'p2', 'p3', 'p4']
You can solve this using the map filter (which can apply a filter to all items in a list) and the regex_replace filter, like this:
---
- hosts: localhost
gather_facts: false
vars:
env_dc: uk
my_list:
- name: switch1
ports:
- p1
- p2
- p3
- p4
tasks:
- debug:
msg: "ports: {{ item.ports|map('regex_replace', '^', env_dc)|list }}"
with_items: "{{ my_list }}"
Which given your example data would evaluate to:
TASK [debug] **********************************************************************************
ok: [localhost] => (item={u'name': u'switch1', u'ports': [u'p1', u'p2', u'p3', u'p4']}) => {
"msg": "ports: [u'ukp1', u'ukp2', u'ukp3', u'ukp4']"
}