How to use wildcard for ansible output - variables

I am trying to use wildcard for my ansible variable but it seems like i cant manage to use it.
I have tried something from here but still the same.
the ansible output
"reboot_required": false,
"updates": {
"0720a128-90b1-4b21-a8cf-3c5c86239435": {
"kb": [
"2267602"
],
"installed": false,
"id": "0720a128-90b1-4b21-a8cf-3c5c86239435",
"categories": [
"Definition Updates",
"Windows Defender"
],
"title": "Definition Update for Windows Defender Antivirus - KB2267602 (Definition 1.297.412.0)"
},
"60bbf4af-afd3-45fe-aad2-6d72beddeba2": {
"kb": [
"4509475"
],
"installed": false,
"id": "60bbf4af-afd3-45fe-aad2-6d72beddeba2",
"categories": [
"Updates",
"Windows Server 2016"
],
"title": "2019-06 Cumulative Update for Windows Server 2016 for x64-based Systems (KB4509475)"
I am trying to get the title, or id
- name: debug
debug:
msg: "{{ item.updates.*.id }}"
with_items:
- "{{ result }}"
appreciate the help

Given the ansible output above is stored in the variable result the tasks below
- set_fact:
id_list: "{{ result.updates|
json_query('*.id')
}}"
- debug:
var: id_list
give the list of id (similar titles)
id_list:
- 0720a128-90b1-4b21-a8cf-3c5c86239435
- 60bbf4af-afd3-45fe-aad2-6d72beddeba2
And the tasks below
- set_fact:
my_list: "{{ result.updates|
json_query('*.{ id: id, title: title }')
}}"
- debug:
var: my_list
give the list of the id, title hashes
my_list:
- id: 0720a128-90b1-4b21-a8cf-3c5c86239435
title: Definition Update for Windows Defender Antivirus - KB2267602 (Definition 1.297.412.0)
- id: 60bbf4af-afd3-45fe-aad2-6d72beddeba2
title: 2019-06 Cumulative Update for Windows Server 2016 for x64-based Systems (KB4509475)

The wildcard he's using in the example that you linked is apart of the json_query filter. He's piping to the json_query filter and then using the wildcard as part of that syntax.
results | json_query('[].block_device_mapping.*.snapshot_id')
You're not using json_query in your example and therefore, this syntax is not available and won't work.
Try piping your results to json_query and then including the path that you want to get to. If {{ results }} is already created you can leave off the with_items and go with something like:
{{ results | json_query('updates.*.id') }}
I'm guessing here at the exact syntax but you definitely have to start with json_query.
To figure out the exact syntax you want, start small piping to json_query and then grabbing the top most element(updates, in your case), adding pieces to the filter until you've narrowed it down to the information you want. I've linked to a pathfinder below that helps.
Reference:
json_query filter documentation
json_query documentation
jsonpath finder to help you figure stuff out easier.
edit: The syntax in the first part of the answer from Vladimir looks way sexier than what I'm guessing at. Try his syntax to get to what works, use my answer to understand what's wrong. Then mark him as the correct answer.

Try below. I have not tested it though.
- name: debug
debug:
msg: "{{ item|first }}:{{ item[item|first].title }}"
with_items:
- "{{ result.updates }}"

Related

Ansible script with | differences of empty map fails [duplicate]

I'm customizing linux users creation inside my role. I need to let users of my role customize home_directory, group_name, name, password.
I was wondering if there's a more flexible way to cope with default values.
I know that the code below is possible:
- name: Create default
user:
name: "default_name"
when: my_variable is not defined
- name: Create custom
user:
name: "{{my_variable}}"
when: my_variable is defined
But as I mentioned, there's a lot of optional variables and this creates a lot of possibilities.
Is there something like the code above?
user:
name: "default_name", "{{my_variable}}"
The code should set name="default_name" when my_variable isn't defined.
I could set all variables on defaults/main.yml and create the user like that:
- name: Create user
user:
name: "{{my_variable}}"
But those variables are inside a really big hash and there are some hashes inside that hash that can't be a default.
You can use Jinja's default:
- name: Create user
user:
name: "{{ my_variable | default('default_value') }}"
Not totally related, but you can also check for both undefined AND empty (for e.g my_variable:) variable. (NOTE: only works with ansible version > 1.9, see: link)
- name: Create user
user:
name: "{{ ((my_variable == None) | ternary('default_value', my_variable)) \
if my_variable is defined else 'default_value' }}"
If anybody is looking for an option which handles nested variables, there are several such options in this github issue.
In short, you need to use "default" filter for every level of nested vars. For a variable "a.nested.var" it would look like:
- hosts: 'localhost'
tasks:
- debug:
msg: "{{ ((a | default({})).nested | default({}) ).var | default('bar') }}"
or you could set default values of empty dicts for each level of vars, maybe using "combine" filter. Or use "json_query" filter. But the option I chose seems simpler to me if you have only one level of nesting.
In case you using lookup to set default read from environment you have also set the second parameter of default to true:
- set_facts:
ansible_ssh_user: "{{ lookup('env', 'SSH_USER') | default('foo', true) }}"
You can also concatenate multiple default definitions:
- set_facts:
ansible_ssh_user: "{{ some_var.split('-')[1] | default(lookup('env','USER'), true) | default('foo') }}"
If you are assigning default value for boolean fact then ensure that no quotes is used inside default().
- name: create bool default
set_fact:
name: "{{ my_bool | default(true) }}"
For other variables used the same method given in verified answer.
- name: Create user
user:
name: "{{ my_variable | default('default_value') }}"
If you have a single play that you want to loop over the items, define that list in group_vars/all or somewhere else that makes sense:
all_items:
- first
- second
- third
- fourth
Then your task can look like this:
- name: List items or default list
debug:
var: item
with_items: "{{ varlist | default(all_items) }}"
Pass in varlist as a JSON array:
ansible-playbook <playbook_name> --extra-vars='{"varlist": [first,third]}'
Prior to that, you might also want a task that checks that each item in varlist is also in all_items:
- name: Ensure passed variables are in all_items
fail:
msg: "{{ item }} not in all_items list"
when: item not in all_items
with_items: "{{ varlist | default(all_items) }}"
The question is quite old, but what about:
- hosts: 'localhost'
tasks:
- debug:
msg: "{{ ( a | default({})).get('nested', {}).get('var','bar') }}"
It looks less cumbersome to me...
#Roman Kruglov mentioned json_query. It's perfect for nested queries.
An example of json_query sample playbook for existing and non-existing value:
- hosts: localhost
gather_facts: False
vars:
level1:
level2:
level3:
level4: "LEVEL4"
tasks:
- name: Print on existing level4
debug:
var: level1 | json_query('level2.level3.level4') # prints 'LEVEL4'
when: level1 | json_query('level2.level3.level4')
- name: Skip on inexistent level5
debug:
var: level1 | json_query('level2.level3.level4.level5') # skipped
when: level1 | json_query('level2.level3.level4.level5')

Can variables be use as ansible filter parameters

I am creating a list of URLs (just strings really).
I want to select the one that contains the string in a ansible variable 'blog'.
Can't seem to code the select parameter correctly.
Is this possible?
- name: get blog_urls
shell:
cmd: wp site list --field=url
chdir: "{{ blog_docroot }}"
register: blog_urls
- name: show blog value
debug:
msg: "{{ blog }}"
- name: select the correct url
set_fact:
url: "{{ blog_urls.stdout_lines | select('contains', blog ) }}"
blog_url conatins:
"http://jackson2.sjfc.edu/",
"https://jackson2.sjfc.edu/oit/",
"https://jackson2.sjfc.edu/aaforms/",
"https://jackson2.sjfc.edu/admissions/",
"https://jackson2.sjfc.edu/arts-sciences/",
"https://jackson2.sjfc.edu/pharmacy/",
"https://jackson2.sjfc.edu/grants/",
"https://jackson2.sjfc.edu/alumni/",
"https://jackson2.sjfc.edu/wson/",
"https://jackson2.sjfc.edu/education/",
"https://jackson2.sjfc.edu/images/",
"https://jackson2.sjfc.edu/oit-test/",
"https://jackson2.sjfc.edu/provost/",
"https://jackson2.sjfc.edu/registrar/",
"https://jackson2.sjfc.edu/faculty-committees/",
"https://jackson2.sjfc.edu/faculty-files/",
"https://jackson2.sjfc.edu/avdownload/",
"https://jackson2.sjfc.edu/mac/",
"https://jackson2.sjfc.edu/giddnfellowship/",
"https://jackson2.sjfc.edu/dnp-mentors/"
blog would contain 'aaforms' or 'oit-test' or 'provost'...
If I hard code the desired value of blog (see line below) it works:
- name: select the correct url
set_fact:
url: "{{ blog_urls.stdout_lines | select('contains', 'aaforms' ) }}"
But of course I want to pass the second parameter of the 'select' filter as a ansible variable.
Your example in question is an almost working one. The select filter will return an a list based on the match criteria.
For example, let's say blog variable is aaforms:
vars:
blog: aaforms
tasks:
- set_fact:
my_blogs: "{{ blog_urls.stdout_lines | select('contains', blog) | list }}"
- debug:
var: my_blogs
This gives the URLs matched by the blog variable (in this case one).
"my_blogs": [
"https://jackson2.sjfc.edu/aaforms/"
]

Use a var in a var in Ansible (lookup) - aws_ssm plugin

I'm trying to use a var in a var declaration on Ansible (2.7.10)
I'm using aws_ssm lookup plugin (https://docs.ansible.com/ansible/latest/plugins/lookup/aws_ssm.html)
Working example (hardcoded values):
var: "{{ lookup('aws_ssm', '/path/server00', region='eu-west-3') }}"
I want to use variables for the server name and the AWS region, but all my tentatives went on errors.
What I've tried so far:
var: "{{ lookup('aws_ssm', '/path/{{ server }}', region={{ region }}) }}"
var: "{{ lookup('aws_ssm', '/path/{{ server }}', region= + region) }}"
- name: xxx
debug: msg="{{ lookup('aws_ssm', '/path/{{ server }}', region='{{ region }}' ) }}"
register: var
Without any success yet, thanks for your help,
You never nest {{...}} template expressions. If you're already inside a template expression, you can just refer to variables by name. For example:
var: "{{ lookup('aws_ssm', '/path/' + server, region=region) }}"
(This assumes that the variables server and region are defined.)
You can also take advantage of Python string formatting syntax. The following will all give you the same result:
'/path/' + server
'/path/%s' % (server)
'/path/{}'.format(server)
And instead of + you can use the Jinja ~ concatenation operator, which acts sort of like + but forces arguments to be strings. So while this is an error:
'some string' + 1
This will result in the text some string1:
'some string' ~ 1

Ansible variable list span

When adding a variable list in Ansible how would one achieve a span of similar values? For instance "000-100" - in an Ansible hosts file this can be done by listing like so, "hostname-[a:v].com". Would this process be the similar in a variable list?
My use case is to provision many VM's within oVirt in a single go without having to make a line by line list.
---
- name: Create VM based on template
hosts: ovirt-engine
become: yes
become_method: sudo
vars:
- temp: '{{temp_fedora25}}'
- iname:
- db-aa
- db-ab
- db-ac
tasks:
- name: Giving Birth to lil Baby VM's
ovirt:
user: '{{ovirt_usr}}'
password: '{{ovirt_pass}}'
url: '{{engine_url}}'
instance_name: "{{item}}"
instance_nic: ovirtmgmt
resource_type: template
image: '{{temp}}'
zone: superblade-a
disk_alloc: preallocated
with_items: "{{iname}}"
You can use sequence lookup:
- name: numeric
debug:
msg: "{{ item }}"
with_sequence: start=1 count=10 format=server-%0d
- name: characters from small 'a'
debug:
msg: "{{ item }}"
with_sequence: start=0x61 count=10 format=server-%c
- name: save for future use
set_fact:
my_seq: "{{ lookup('sequence','start={} count={} format={}{}'.format(beg,cnt,pref,fmt),wantlist=True) }}"
vars:
beg: 1
cnt: 10
pref: host-
fmt: '%0d'
You can skip set_fact and define my_seq in vars section, but if you use my_seq much, list generation will be done internally every time. With set_fact list is generated once.
With respect to the correct answer from Konstantin, I'm adding the full solution as per my case....
My goal is to be able to reuse the sequenced values as registered variables in order to pass the instance name to host name. This works so far but Im sure it can be streamlined by nesting variables perhaps?
---
- name: Create VM based on template
hosts: ovirt-engine
become: yes
become_method: sudo
vars:
- temp: '{{temp_fedora25}}'
- host_pre: db
- host_seq: a%c
- host_cnt: 3
- host_srt: 0x61
tasks:
- name: Giving Birth to lil Baby VM's
ovirt:
user: '{{ovirt_usr}}'
password: '{{ovirt_pass}}'
url: '{{engine_url}}'
instance_name: "{{item}}"
instance_nic: ovirtmgmt
resource_type: template
image: '{{temp}}'
zone: superblade-a
disk_alloc: preallocated
with_sequence: start="{{host_srt}}" count="{{host_cnt}}" format="{{host_pre}}-{{host_seq}}"

Remove quotes from Ansible variable output

I'm using this task to add a line to a file:
lineinfile: "dest={{ ansible_env.HOME }}/{{ deploy_dir }}/config/deploy/{{ stage_name }}.rb
insertbefore='# role-based syntax'
line='server "'{{ ip_addr }}'", user: "'{{ user_name }}'", roles: %w{'{{ role }}'}'"
Which adds this line:
server '172.16.8.11', user: 'vagrant', roles: %w{'api'}
But I don't want the quotes around api. Instead I want this output:
server '172.16.8.11', user: 'vagrant', roles: %w{api}
Actually the quotes do not come from the variable, but are right there in your string:
%w{'{{ role }}'}
Now the solution is little bit tricky though. Because you can not simply remove the quotes like that:
%w{{{ role }}}
This would result into a parse error, since {{ starts an expression...
The solution is to write the outer parentheses, which are meant to be in the string, as an expression themselves.
So to output { you would instead write {{'{'}} and instead of } you would write {{'}'}}. Does that make sense? You're instructing the template engine (Jinja2) to output the parentheses to avoid the parsing error:
%w{{'{'}}{{ role }}{{'}'}}
But since role is an expression already, you just also can group it together into one single expression:
%w{{ '{'+role+'}' }}
Your whole task would then read like this:
- lineinfile:
dest: "{{ ansible_env.HOME }}/{{ deploy_dir }}/config/deploy/{{ stage_name }}.rb"
insertbefore: "# role-based syntax"
line: "server '{{ ip_addr }}', user: '{{ user_name }}', roles: %w{{ '{'+role+'}' }}"
This also is converted into proper YAML syntax because this quoted k=v format is just really hard to read. :)