ANSIBLE - how to concatenate a string with a list - list

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']"
}

Related

Extract values from a list of dictionaries in Ansible

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

Getting error Object of type set is not JSON serializable while executing my ansible script

My scenario is a bit similar to the one mentioned here
but a bit difference, let me take same example mentioned in above question solution by Vladimir Botka , added name:c and name:d block
output:
- Name: A
source: [a, b, c, a, b, c]
dest: [x,y,z]
- Name: B
source: [a, b, c, a, b, c]
dest: [x.c, y, z, x, y, z]
- Name: C
source:
dest:
- Name: D
source: "1.2"
dest: "x"
I am using same answer suggested in above post but a bit modifications as :
- set_fact:
out1: "{{output |replace('None','[]')}}"
- set_fact:
out: "{{ out|d([]) + [{'Name': item.Name,
'source': _src,
'dest': _dst}] }}"
loop: "{{ out1 }}"
vars:
_src: "{{ item.source|unique}}"
_dst: "{{ item.dest|unique}}"
- debug:
var: out
I used out1: "{{output |replace('None','[]')}}" cause loop is failing for name:c as source and dest is empty and not a list i am making it list by replacing None as [], to over come loop error, i am able to fix loop error.
not sure if its right approach or not but solved loop error issue.
but second error i am getting is Object of type set is not JSON serializable for name:d cause source and destination is not a list.
how can this error be fixed or any workaround ??
Q: "Error when source and destination is not a list"
A: Filter unique items if the type of the value is a list otherwise copy the value, e.g.
- set_fact:
out: "{{ out|d([]) + [{'Name': item.Name,
'source': _src,
'dest': _dst}] }}"
loop: "{{ out1 }}"
vars:
_src: "{{ (item.source|type_debug == 'list')|
ternary(item.source|unique, item.source) }}"
_dst: "{{ (item.dest|type_debug == 'list')|
ternary(item.dest|unique, item.dest) }}"

ansible list items should be replaced when meeting criteria

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'

Ansible consume AD command output

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"

Error in Ansible when modify list items with backslash

I have a list in following format and need to replace commas with backlash but getting error when trying to use replace function.
"sub_keys": [
",,ps1,printer1",
",,ps1,printer2",
",,ps2,printer1"]
expected result:
new_list:[ "\\ps1\printer1",
"\\ps1\printer2"
"\\ps2\printer1"]
i tried the following code:
- name: Convert list
set_fact:
new_list: '{{ new_list + [item.replace (",","\")] }}'
with_items: "{{ sub_keys }}"
Have you tried:
- name: Convert list
set_facts:
new_list:
- "\\\\ps1\\printer1"
- "\\\\ps1\\printer2"
- "\\\\ps2\\printer1"