Dictionary value access using ansible - dictionary

I have a situation where we have 2 dictionary defined in ansible role default and the selection of dictionary is based of an input variable. I want to set the fact with one of the dict's specific key value.
Below is the example code:
test.yml paybook content:
- hosts: localhost
gather_facts: true
roles:
- role1
tags: ['role1']
roles/role1/tasks/main.yml content:
- name: set fact
set_fact:
node_vip: "{% if node_vip_run == 'no' %}node_vip_no{% elif node_vip_run == 'yes' %}node_vip_yes{% endif %}"
- debug:
var: node_vip
verbosity: 1
- debug:
var: "{{ node_vip }}.ece_endpoint"
verbosity: 1
- name: set fact
set_fact:
ece_endpoint_fact: "{{ node_vip[ece_endpoint] }}"
- debug:
var: ece_endpoint
verbosity: 1
roles/role1/defaults/main.yml content:
node_vip_yes:
ece_endpoint: "https://1.1.1.1:8080"
cac_endpoint: "https:2.2.2.2:8080"
node_vip_no:
ece_endpoint: "http://3.3.3.3:8080"
cac_endpoint: "http:4.4.4.4:8080"
Run playbook:
ansible-playbook test.yaml --extra-vars 'node_vip_run=no' -v
The set fact of variable "ece_endpoint_fact" should have value "https://1.1.1.1:8080 OR http://3.3.3.3:8080" depending on the parameter input in ansible command. But I keep on getting below error:
TASK [role1 : set fact] *******************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'unicode object' has no attribute u'http://3.3.3.3:8080'\n\nThe error appears to be in '/root/roles/role1/tasks/main.yml': line 46, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: set fact\n ^ here\n"}
Please suggest what needs to be done to resolve this.
Thanks

Right now, you set node_vip to either the literal string "node_vip_no" or "node_vip_yes". But if you change it to do {{ node_vip_no }} / {{ node_vip_yes }}, then node_vip will have the value of the variable node_vip_no / node_vip_yes instead of being a literal string.
- name: set fact
set_fact:
node_vip: "{% if node_vip_run == 'no' %}{{ node_vip_no }}{% elif node_vip_run == 'yes' %}{{ node_vip_yes }}{% endif %}"
This will have node_vip's value be something like:
TASK [debug] ***************************************************************
ok: [localhost] => {
"node_vip": {
"cac_endpoint": "https:2.2.2.2:8080",
"ece_endpoint": "https://1.1.1.1:8080"
}
}
Then in your other set_fact, it should work if you put quotes around the property name:
- name: set fact
set_fact:
ece_endpoint_fact: "{{ node_vip['ece_endpoint'] }}"
# Added quotes ^ ^

Related

Fail to get values from dictionary in ansible playbook

I'm trying to get some values from a dictionary in ansible playbook.
First, I build the dictionary and it runs correctly.
Then, I would compute the output_dict evaluating the values of this dictionary but I have the issue above.
- set_fact:
state_service: "{{ state_service | default({}) | combine({ item.key : item.value }) }}"
with_items:
- { 'key': 'op_state', 'value': "{{Check_Operative_State.results[0].stdout}}"}
- { 'key': 'ad_state', 'value': "{{Check_Administrative_State.results[0].stdout}}"}
- name: Display the state of service
debug: msg="{{state_service}}"
- set_fact:
output_dict: '{{output_dict | default([]) + ["CHECK ERRORS IN SERVICE ************PASSED" if ((item.op_state == "enabled" and item.ad_state == "unlocked") or (item.op_state == "disabled" and item.ad_state == "locked")) else "CHECK ERRORS IN SERVICE **********FAILED"] }}'
with_items: "{{state_service}}"
The error:
**************************************************
2022-02-04 19:04:45,341 p=4478 u=abcd n=ansible | ok: [localhost] => {
"msg": {
"ad_state": "unlocked",
"op_state": "enabled"
}
}
2022-02-04 19:04:45,366 p=4478 u=abcd n=ansible | TASK [check : set_fact] ************************************************************************************************************************************************************************
2022-02-04 19:04:45,366 p=4478 u=abcd n=ansible | fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'op_state'\n\nThe error appears to be in '/home/abcd/health/service/script/roles/health/tasks/main.yaml': line 483, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- set_fact:\n ^ here\n"}
2022-02-04 19:04:45,368 p=4478 u=abcd n=ansible | PLAY RECAP *****************************************************************************************************************************************
Given the list below to simplify the example
l1:
- {key: op_state, value: enabled}
- {key: ad_state, value: unlocked}
Use the filter items2dict to create a dictionary from the list, e.g.
state_service: "{{ l1|items2dict }}"
gives
state_service:
ad_state: unlocked
op_state: enabled
You can't iterate a dictionary, but you can use dict2items to convert the dictionary to a list, e.g.
- debug:
var: item
loop: "{{ state_service|dict2items }}"
gives (abridged)
item:
key: op_state
value: enabled
item:
key: ad_state
value: unlocked

Apply map filter to value of dictionary with ansible/jinja2

I'm trying to write an ansible playbook that outputs some details about a system, in a nicely formatted way. In particular, disk sizes.
Input variable looks something like:
- friendly_name: 'disk1 name'
size: 123456
- friendly_name: 'disk2 name'
size: 654321
{{ dict(ansible_facts.disks | json_query('[].[friendly_name, size]')) }}
I'm struggling to come up with a way to apply a function to the 'value' of the dictionary (or the second value of the nested list, prior to converting it to a dict) - I'd like to apply human_readable(unit='G') or similar, without resorting to set_fact or FilterPlugins
So ideally I'd have an output variable of the form:
{'disk1 name': '1024G', 'disk2 name': '8192G'}
You could split the dictionary ansible_facts.disks into two lists, one containing the size and the other one the friendly name, then apply the human_readable filter to the list containing the size with the map filter, then zip the two lists back together.
Given the task:
- debug:
msg: "{{ dict(
ansible_facts.disks | map(attribute='friendly_name') |
zip(ansible_facts.disks | map(attribute='size') | map('human_readable','unit','G'))
) }}"
vars:
ansible_facts:
disks:
- friendly_name: 'disk1 name'
size: 1099511627776
- friendly_name: 'disk2 name'
size: 8796093022208
This yields:
TASK [debug] ********************************************************************
ok: [localhost] => {
"msg": {
"disk1 name": "1024.00 Gb",
"disk2 name": "8192.00 Gb"
}
}
Without the formatting you could simply use items2dict
- debug:
msg: "{{ ansible_facts.disks|items2dict(key_name='friendly_name',
value_name='size') }}"
gives
msg:
disk1 name: 1099511627776
disk2 name: 8796093022208
Use Jinja to change the format, e.g.
- debug:
msg: "{{ _disks|from_yaml }}"
vars:
_disks: |
{% for i in ansible_facts_disks %}
{{ i.friendly_name }}: {{ i.size|human_readable(unit='G') }}
{% endfor %}
gives
msg:
disk1 name: 1024.00 GB
disk2 name: 8192.00 GB

If statements with nested grain returns nothing

I am trying to write an if statement based on a nested grain. I have tried this statement in multiple different ways:
System Services Needed:
module.run:
- name: service.systemctl_reload
- onchanges:
- file: /lib/systemd/system/salt-minion.service
{% if salt['grains.get']('Project:DeviceTypeID') == '2' %}
- file: /etc/rc.local
- file: /opt/interfaces_init.sh
{% endif %}
Returns:
Rendering SLS 'Development:System' failed: Jinja variable 'dict object' has no attribute 'Project:DeviceTypeID'
System Services Needed:
module.run:
- name: service.systemctl_reload
- onchanges:
- file: /lib/systemd/system/salt-minion.service
{% if grains['Project']['DeviceTypeID'] == '2' %}
- file: /etc/rc.local
- file: /opt/interfaces_init.sh
{% endif %}
System Services Needed:
module.run:
- name: service.systemctl_reload
- onchanges:
- file: /lib/systemd/system/salt-minion.service
{% if grains['Project:DeviceTypeID'] == '2' %}
- file: /etc/rc.local
- file: /opt/interfaces_init.sh
{% endif %}
As you can tell from the example their are multiple device type IDs. In this example DeviceTypeID = 2 I need to worry about rc.local and a shell script. I can not seem to get this work for the life of me. I know the grain exists as I can run the following:
sudo salt 'Dev-Box' grains.get Project
and I will get:
Dev-Box:
DeviceTypeID:
1
IsActive:
True
SoftwareEnvironmentName:
Production
SoftwareVersion:
Foo
This is either a bug or I am missing something (significantly more likely I am missing something). Any help would be much appreciated.
Edit 1:
Added ['grains.get']('Project:DeviceTypeID') example
in salt grains.get return a dictionary in the following format:
{'minion-id': value}
I believe if you change your code into something like bellow, it should works.
{% if salt['grains.get']('Project:DeviceTypeID')[minion-id] == '2' %}
If you can't do:
salt 'Dev-Box' grains.get 'Project:DeviceTypeID'
Then you don't actually have the proper grain set.
Try the following:
salt 'Dev-Box' grains.setval Project '{"DeviceTypeID": 2, "IsActive": True, "SoftwareEnvironmentName": "Production", "SoftwareVersion": "Foo"}'
Then the following state:
Do the {{ salt['grains.get']('Project:DeviceTypeID') }} things:
test.succeed_with_changes:
- some: thing
You should get:
ID: Do the 2 things
Function: test.succeed_with_changes
Result: True
Comment: Success!
Started: 17:10:42.739240
Duration: 0.491 ms
Changes:
----------
testing:
----------
new:
Something pretended to change
old:
Unchanged
Given what you wrote elsewhere
salt Dev-Box grains.setval BETTI "{'DeviceTypeID': 2, 'IsActive': True SoftwareEnvironmentName': 'Production', 'SoftwareVersion': 'Foo'}"
Your problem is that you have ' and " confused.
Wrapping the value with " makes it a string. Wrapping it with ' and providing valid JSON makes it a dictionary value.

Ansible include_vars into dictionary

In my ansible playbook, I read a list of directories into a list. I then want to read a "config.yml" file from each of these directories and put their content into dictionary, so that I can reference the config-data via the directory name from that dictionary.
The first part is no problem, but I cannot get the second part to work:
Step 1, load directories:
- name: Include directories
include_vars:
file: /main-config.yml
name: config
Step 2, load configs from directories:
- name: load deploymentset configurations
include_vars:
file: /path/{{ item }}/config.yml
name: "allconfs.{{ item }}" ## << This is the problematic part
with_items:
- "{{ config.dirs }}"
I tried different things like "allconfs['{{ item }}'], but none seemed to work. The playbook completed successfully, but the data was not in the dictionary.
I also tried defining the outer dictionary beforehand, but that did not work either.
The config files themselves are very simple:
/main-config.yml:
dirs:
- dir1
- dir2
- dir3
/path/dir1/config.yml:
some_var: "some_val"
another_var: "another val"
I want to be able to then access the values of the config.yml files like this:
{{ allconfs.dir1.some_var }}
UPDATE to try Konstantins approach:
- name: load deploymentset configurations
include_vars:
file: /repo/deploymentsets/{{ item }}/config.yml
name: "default_config"
with_items:
- "{{ config.deploymentsets }}"
register: default_configs
- name: combine configs
set_fact:
default_configs: "{{ dict(default_configs.results | json_query('[].[item, ansible_facts.default_config]')) }}"
Error message:
fatal: [127.0.0.1]: FAILED! => {"failed": true, "msg": "Unexpected templating type error occurred on ({{ dict(default_configs.results | json_query('[].[item, ansible_facts.default_config]')) }}): <lambda>() takes exactly 0 arguments (1 given)"}
Here is a piece of code from one of my projects with similar functionality:
- name: Load config defaults
include_vars:
file: "{{ item }}.yml"
name: "default_config"
with_items: "{{ config_files }}"
register: default_configs
tags:
- configuration
- name: Combine configs into one dict
# Здесь мы делаем словарь вида
# default_configs:
# config_name_1: { default_config_object }
# config_name_2: { default_config_object }
# config_name_3: { default_config_object }
# ...
set_fact:
default_configs: "{{ dict(default_configs.results | json_query('[].[item, ansible_facts.default_config]')) }}"
tags:
- configuration
default_config is a dummy var to temporary load var data.
The trick is to use register: default_configs with include_vars and parse it with the following task stripping out unnecessary fields.
AFAIK it isn't possible to create a single dictionary that encompasses multiple include_vars. From my testing it would create separate dictionaries for each included directory. Here's what you can do instead.
Remove allconfs. from your variable name.
- name: load deploymentset configurations
include_vars:
file: /path/{{ item }}/config.yml
name: "{{ item }}"
with_items:
- "{{ config.dirs }}"
You can then either access variables directly with
debug:
msg: "{{ dir1.some_var }}"
with_items: "{{ config.dirs }}"
Or if you need to loop through all variables in your included directories use this (hoisted from Ansible: how to construct a variable from another variable and then fetch it's value).
debug:
msg: "{{ hostvars[inventory_hostname][item].some_var }}"
with_items: "{{ config.dirs }}"

Ansible: can't access dictionary value - got error: 'dict object' has no attribute

---
- hosts: test
tasks:
- name: print phone details
debug: msg="user {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
with_dict: "{{ users }}"
vars:
users:
alice: "Alice"
telephone: 123
When I run this playbook, I am getting this error:
One or more undefined variables: 'dict object' has no attribute 'name'
This one actually works just fine:
debug: msg="user {{ item.key }} is {{ item.value }}"
What am I missing?
This is not the exact same code. If you look carefully at the example, you'll see that under users, you have several dicts.
In your case, you have two dicts but with just one key (alice, or telephone) with respective values of "Alice", 123.
You'd rather do :
- hosts: localhost
gather_facts: no
tasks:
- name: print phone details
debug: msg="user {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
with_dict: "{{ users }}"
vars:
users:
alice:
name: "Alice"
telephone: 123
(note that I changed host to localhost so I can run it easily, and added gather_facts: no since it's not necessary here. YMMV.)
You want to print {{ item.value.name }} but the name is not defined.
users:
alice: "Alice"
telephone: 123
should be replaced by
users:
name: "Alice"
telephone: 123
Then both the name and the telephone attribute are defined within the dict (users).
I found out that with dict only works when giving the dict inline. Not when taking it from vars.
- name: ssh config
lineinfile:
dest: /etc/ssh/sshd_config
regexp: '^#?\s*{{item.key}}\s'
line: '{{item.key}} {{item.value}}'
state: present
with_dict:
LoginGraceTime: "1m"
PermitRootLogin: "yes"
PubkeyAuthentication: "yes"
PasswordAuthentication: "no"
PermitEmptyPasswords: "no"
IgnoreRhosts: "yes"
Protocol: 2
If you want to take it from vars which can also be defined globally or on some other place, you can use lookup.
- name: ssh config
lineinfile:
dest: /etc/ssh/sshd_config
regexp: '^#?\s*{{item.key}}\s'
line: '{{item.key}} {{item.value}}'
state: present
loop: "{{ lookup('dict', sshd_config) }}"
vars:
sshd_config:
LoginGraceTime: "1m"
PermitRootLogin: "yes"
PubkeyAuthentication: "yes"
PasswordAuthentication: "no"
PermitEmptyPasswords: "no"
IgnoreRhosts: "yes"
Protocol: 2
small correction:
- name: print phone details
debug: msg="user {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
with_dict: "{{ users }}" <<<<<<<<<<<<<<<<

Resources