Ansible - Extracting a variable from a large JSON output - ansible

The gcp_sql_instance_info module does not seem to allow you to specify the name of the database you are trying to get info for. All it does is every detail of every database in that project.
What would be the best way to extract the "ipAddress" of a database based on it's name and register that value to a variable?
{
"resources": [
{
"kind": "sql#instance",
"state": "RUNNABLE",
"databaseVersion": "POSTGRES_13",
"settings": {
"authorizedGaeApplications": [],
"tier": "db-custom-1-3840",
"kind": "sql#settings",
"availabilityType": "ZONAL",
"pricingPlan": "PER_USE",
"replicationType": "SYNCHRONOUS",
"activationPolicy": "ALWAYS",
"ipConfiguration": {
"privateNetwork": "example-network",
"authorizedNetworks": [],
"ipv4Enabled": false
},
"locationPreference": {
"zone": "us-west1-b",
"kind": "sql#locationPreference"
},
"dataDiskType": "PD_SSD",
"maintenanceWindow": {
"kind": "sql#maintenanceWindow",
"hour": 0,
"day": 0
},
"backupConfiguration": {
"startTime": "02:00",
"kind": "sql#backupConfiguration",
"backupRetentionSettings": {
"retentionUnit": "COUNT",
"retainedBackups": 7
},
"enabled": false,
"replicationLogArchivingEnabled": false,
"pointInTimeRecoveryEnabled": false,
"transactionLogRetentionDays": 7
},
"settingsVersion": "3",
"storageAutoResizeLimit": "0",
"storageAutoResize": true,
"dataDiskSizeGb": "100"
},
"ipAddresses": [
{
"type": "PRIVATE",
"ipAddress": "10.10.10.1"
}
],
"instanceType": "CLOUD_SQL_INSTANCE",
"backendType": "SECOND_GEN",
"name": "database-1",
"region": "us-west1",
"gceZone": "us-west1-b",
"databaseInstalledVersion": "POSTGRES_13_7",
"createTime": "2022-07-22T20:20:32.274Z"
},
{
"kind": "sql#instance",
"state": "RUNNABLE",
"databaseVersion": "MYSQL_8_0",
"settings": {
"authorizedGaeApplications": [],
"tier": "db-n1-standard-1",
"kind": "sql#settings",
"availabilityType": "ZONAL",
"pricingPlan": "PER_USE",
"replicationType": "SYNCHRONOUS",
"activationPolicy": "ALWAYS",
"ipConfiguration": {
"privateNetwork": "example-network",
"authorizedNetworks": [],
"ipv4Enabled": false
},
"locationPreference": {
"zone": "us-west1-c",
"kind": "sql#locationPreference"
},
"dataDiskType": "PD_SSD",
"backupConfiguration": {
"startTime": "21:00",
"kind": "sql#backupConfiguration",
"backupRetentionSettings": {
"retentionUnit": "COUNT",
"retainedBackups": 7
},
"enabled": false,
"transactionLogRetentionDays": 7
},
"settingsVersion": "1",
"storageAutoResizeLimit": "0",
"storageAutoResize": true,
"dataDiskSizeGb": "10"
},
"ipAddresses": [
{
"type": "PRIVATE",
"ipAddress": "10.10.10.2"
}
],
"instanceType": "CLOUD_SQL_INSTANCE",
"backendType": "SECOND_GEN",
"name": "database-2",
"region": "us-west1",
"gceZone": "us-west1-c",
"databaseInstalledVersion": "MYSQL_8_0_26",
"createTime": "2022-07-27T19:27:59.235Z"
}
]

Q: "Extract the ipAddress of a database based on its name."
A: Crete a dictionary. For example, select the first item from the list ipAddresses
name_ip: "{{ dict(resources|json_query(name_ip_query)) }}"
name_ip_query: '[].[name, ipAddresses[0].ipAddress]'
give
name_ip:
database-1: 10.10.10.1
database-2: 10.10.10.2
Notes
Example of a complete playbook for testing
- hosts: localhost
vars_files:
- resources.yml
vars:
name_ip: "{{ dict(resources|json_query(name_ip_query)) }}"
name_ip_query: '[].[name, ipAddresses[0].ipAddress]'
name_ver: "{{ dict(resources|json_query(name_ver_query)) }}"
name_ver_query: '[].[name, databaseVersion]'
ip_of_db1: "{{ name_ip['database-1'] }}"
tasks:
- debug:
var: name_ip
- debug:
var: name_ver
- debug:
var: ip_of_db1
gives
TASK [debug] *********************************************************************************
ok: [localhost] =>
name_ip:
database-1: 10.10.10.1
database-2: 10.10.10.2
TASK [debug] *********************************************************************************
ok: [localhost] =>
name_ver:
database-1: POSTGRES_13
database-2: MYSQL_8_0
TASK [debug] *********************************************************************************
ok: [localhost] =>
ip_of_db1: 10.10.10.1
There might be more IP addresses. The variable ipAddresses is a list. An option would be to create a list of all IP addresses. For example,
name_ips: "{{ dict(resources|json_query(name_ips_query)) }}"
name_ips_query: '[].[name, ipAddresses[].ipAddress]'
give
name_ips:
database-1: [10.10.10.1]
database-2: [10.10.10.2]

This is a working playbook to achieve the desired output:
- hosts: localhost
vars:
db_instance_name: instance-1
tasks:
- name: get info on an instance
gcp_sql_instance_info:
project: project_id
auth_kind: serviceaccount
service_account_file: "/path/to/sa/example.json"
register: cloud_sql_resources
- set_fact:
query: "resources[?contains(name,'{{ db_instance_name }}')].ipAddresses[].ipAddress"
- set_fact:
ipAddress: "{{ cloud_sql_resources | to_json | from_json | json_query(query) }}"
- debug:
msg: "{{ ipAddress }}"
You can run your playbook like this: ansible-playbook -v main.yaml --extra-vars "db_instance_name=instance-1", that would print:
TASK [debug] ********************************************************************************************************************
ok: [localhost] => {
"msg": [
"35.224.46.127"
]
}

Related

Select specific cluster with prefix in VMware cluster from Ansible

I'm using the below playbook to list all the VMware cluster belonging to my datacenter, but I need to select a specific cluster containing LAB in the cluster name.
- hosts: localhost
vars_files: 1credentials.yml
tasks:
- name: Gather cluster info from given datacenter
community.vmware.vmware_cluster_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
datacenter: SDx-CoE-T7
validate_certs: no
delegate_to: localhost
register: cluster_info
- debug:
msg: "{{ cluster_info }}"
- debug:
msg: "{{ cluster_info.clusters.keys() | list | to_yaml }}"
I'm trying to use selectattr(), but, I am not able to get the exact syntax. Can you please suggest the best option to filter the cluster name containing LAB.
Below is the playbook output:
PLAY [localhost] *******************************************************************************************************************************************************
TASK [Gathering Facts] *************************************************************************************************************************************************
ok: [localhost]
TASK [Gather cluster info from given datacenter] ***********************************************************************************************************************
ok: [localhost]
TASK [debug] ***********************************************************************************************************************************************************
ok: [localhost] => {
"msg": {
"changed": false,
"clusters": {
"TEST_LAB": {
"datacenter": "TEST_CoE-T7",
"drs_default_vm_behavior": "fullyAutomated",
"drs_enable_vm_behavior_overrides": true,
"drs_vmotion_rate": 3,
"enable_ha": false,
"enabled_drs": false,
"enabled_vsan": false,
"ha_admission_control_enabled": true,
"ha_failover_level": 1,
"ha_host_monitoring": "enabled",
"ha_restart_priority": [
"medium"
],
"ha_vm_failure_interval": [
30
],
"ha_vm_max_failure_window": [
-1
],
"ha_vm_max_failures": [
3
],
"ha_vm_min_up_time": [
120
],
"ha_vm_monitoring": "vmMonitoringDisabled",
"ha_vm_tools_monitoring": [
"vmMonitoringDisabled"
],
"hosts": [],
"moid": "domain-c28615",
"resource_summary": {
"cpuCapacityMHz": 0,
"cpuUsedMHz": 0,
"memCapacityMB": 0,
"memUsedMB": 0,
"pMemAvailableMB": 0,
"pMemCapacityMB": 0,
"storageCapacityMB": 0,
"storageUsedMB": 0
},
"tags": [],
"vsan_auto_claim_storage": false
},
"TEST_LaaS": {
"datacenter": "TEST_CoE-T7",
"drs_default_vm_behavior": "fullyAutomated",
"drs_enable_vm_behavior_overrides": true,
"drs_vmotion_rate": 3,
"enable_ha": true,
"enabled_drs": true,
"enabled_vsan": false,
"ha_admission_control_enabled": true,
"ha_failover_level": 1,
"ha_host_monitoring": "enabled",
"ha_restart_priority": [
"medium"
],
"ha_vm_failure_interval": [
30
],
"ha_vm_max_failure_window": [
-1
],
"ha_vm_max_failures": [
3
],
"ha_vm_min_up_time": [
120
],
"ha_vm_monitoring": "vmMonitoringDisabled",
"ha_vm_tools_monitoring": [
"vmMonitoringDisabled"
],
"hosts": [
{
"folder": "/TEST_CoE-T7/host/TEST_LaaS",
"name": "172.17.65.84"
},
{
"folder": "/TEST_CoE-T7/host/TEST_LaaS",
"name": "172.17.65.85"
},
{
"folder": "/TEST_CoE-T7/host/TEST_LaaS",
"name": "172.17.168.202"
}
],
"moid": "domain-c861",
"resource_summary": {
"cpuCapacityMHz": 158040,
"cpuUsedMHz": 17494,
"memCapacityMB": 786073,
"memUsedMB": 361592,
"pMemAvailableMB": 0,
"pMemCapacityMB": 0,
"storageCapacityMB": 22707456,
"storageUsedMB": 14326118
},
"tags": [],
"vsan_auto_claim_storage": false
}
},
"failed": false
}
}
TASK [debug] ***********************************************************************************************************************************************************
ok: [localhost] => {
"msg": "[TEST_Automation, TEST_LAB, TEST_LaaS,]\n"
}
If I use ansible version 2.9.27, I'm getting below error:
fatal: [localhost]: FAILED! => {"msg": "Unexpected templating type error occurred on ({{ cluster_info.clusters | dict2items | selectattr('key','contains','Common')| items2dict | list }}): items2dict requires a list, got <class 'generator'> instead."}
I tried with below one removing items2dict:
- debug:
msg: "{{ cluster_info.clusters | dict2items | selectattr('key','contains','TEST') | list }}"
It is giving the below output but I need only the key: TEST_Lab
ok: [localhost] => {
"msg": [
{
"key": "TEST_LAB",
"value": {
"drs_default_vm_behavior": "partiallyAutomated",
"drs_enable_vm_behavior_overrides": true,
"drs_vmotion_rate": 3,
"enable_ha": false,
"enabled_drs": true,
"enabled_vsan": false,
"ha_admission_control_enabled": true,
"ha_failover_level": 1,
"ha_host_monitoring": "enabled",
"ha_restart_priority": [
"medium"
],
"ha_vm_failure_interval": [
30
],
"ha_vm_max_failure_window": [
-1
],
"ha_vm_max_failures": [
3
],
"ha_vm_min_up_time": [
120
],
"ha_vm_monitoring": "vmMonitoringDisabled",
"ha_vm_tools_monitoring": [
"vmMonitoringDisabled"
],
"tags": [],
"vsan_auto_claim_storage": false
}
}
]
}
In order to use selectattr, you need to have a value to filter on, not a key. But transforming a dictionary into a list, containing the key and value is as simple as using the dict2items filter, in Ansible.
Then, to come back to your dictionary, just use the "antonym" filter, items2dict.
So, your debug task ends up being:
- debug:
var: >-
cluster_info.clusters
| dict2items
| selectattr('key','contains','LAB')
| items2dict
Given the task, with a reduced dictionary for readability:
- debug:
var: |-
cluster_info.clusters
| dict2items
| selectattr('key','contains','LAB')
| items2dict
vars:
cluster_info:
clusters:
TEST_LAB:
datacenter: TEST_CoE-T7
drs_default_vm_behavior: fullyAutomated
TEST_LaaS:
datacenter: TEST_CoE-T7
drs_default_vm_behavior: fullyAutomated
This will yield:
ok: [localhost] =>
? |-
cluster_info.clusters
| dict2items
| selectattr('key','contains','LAB')
| items2dict
: TEST_LAB:
datacenter: TEST_CoE-T7
drs_default_vm_behavior: fullyAutomated

Usage of Ansible JMESPath in queries

I am using following JSON file:
sample.json:
{
"lldp_output['gathered']": [
{
"mode": "trunk",
"name": "GigabitEthernet0/0",
"trunk": {
"encapsulation": "dot1q"
}
},
{
"access": {
"vlan": 12
},
"mode": "access",
"name": "GigabitEthernet0/1"
},
{
"name": "GigabitEthernet0/2"
}
]
}
And the playbook:
---
- hosts: localhost
gather_facts: no
vars:
tmpdata: "{{ lookup('file','sample.json') | from_json }}"
tasks:
- name: Take 4
debug:
msg: "{{ tmpdata | community.general.json_query(lldp_output['gathered']) }}"
I get the following error:
TASK [Take 4] ********************************************************************************************
task path: /root/scripts/atest.yml:18
fatal: [localhost]: FAILED! => {
"msg": "Error in jmespath.search in json_query filter plugin:\n'lldp_output' is undefined"
}
How do I query the JSON shown so I get a list of all ports that have mode: trunk
When I run in a playbook:
---
- name: Find trunk ports
hosts: ios
tasks:
- name: Collect interface output
cisco.ios.ios_l2_interfaces:
config:
state: gathered
register:
"intf_output"
- debug:
var=intf_output
- name: Take 4
debug:
msg: "{{ intf_output | json_query(query) }}"
vars:
query: >-
"lldp_output['gathered']"[?mode=='trunk']
The structure returned is like following:
{
"intf_output": {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"failed": false,
"gathered": [
{
"name": "GigabitEthernet0/0"
},
{
"mode": "trunk",
"name": "GigabitEthernet0/1",
"trunk": {
"allowed_vlans": [
"10",
"20",
"30",
"100"
],
"encapsulation": "dot1q"
}
},
{
"mode": "trunk",
"name": "GigabitEthernet0/2",
"trunk": {
"allowed_vlans": [
"10",
"20",
"30",
"100"
],
"encapsulation": "dot1q"
}
},
{
"mode": "trunk",
"name": "GigabitEthernet0/3",
"trunk": {
"allowed_vlans": [
"10",
"20",
"30",
"100"
],
"encapsulation": "dot1q"
}
},
{
"mode": "trunk",
"name": "GigabitEthernet1/0",
"trunk": {
"allowed_vlans": [
"10",
"20",
"30",
"100"
],
"encapsulation": "dot1q"
}
},
{
"mode": "trunk",
"name": "GigabitEthernet1/1",
"trunk": {
"allowed_vlans": [
"10",
"20",
"30",
"100"
],
"encapsulation": "dot1q"
}
},
{
"name": "GigabitEthernet1/2"
},
{
"name": "GigabitEthernet1/3"
},
{
"name": "GigabitEthernet2/0"
},
{
"name": "GigabitEthernet2/1"
},
{
"name": "GigabitEthernet2/2"
},
{
"name": "GigabitEthernet2/3"
},
{
"name": "GigabitEthernet3/0"
},
{
"name": "GigabitEthernet3/1"
},
{
"name": "GigabitEthernet3/2"
},
{
"name": "GigabitEthernet3/3"
}
]
}
}
For each host I run against the playbook against.
The argument to json_query must be a string. Because you haven't quoted your argument, Ansible is looking for a variable named lldp_output. But you've got additonal problems, since you're trying to access a key named lldp_output['gathered'], but [ is a syntactically significant character in JSON (and JMESPath queries), so that needs to be escaped as well.
In order to avoid all sorts of quote escaping contortions, we can place the query itself into a variable, so that we have:
- hosts: localhost
vars:
tmpdata: "{{ lookup('file','sample.json') | from_json }}"
tasks:
- name: Take 4
debug:
msg: "{{ tmpdata | json_query(query) }}"
vars:
query: >-
"lldp_output['gathered']"
Note that we are using the >- block quote operator, which means that the value of query is the literal string "lldp_output['gathered']", including the outer quotes.
That playbook outputs:
TASK [Take 4] *********************************************************************************
ok: [localhost] => {
"msg": [
{
"mode": "trunk",
"name": "GigabitEthernet0/0",
"trunk": {
"encapsulation": "dot1q"
}
},
{
"access": {
"vlan": 12
},
"mode": "access",
"name": "GigabitEthernet0/1"
},
{
"name": "GigabitEthernet0/2"
}
]
}
To get just those systems with mode equal to trunk, just add that
criteria to your query:
- hosts: localhost
vars:
tmpdata: "{{ lookup('file','sample.json') | from_json }}"
tasks:
- name: Take 4
debug:
msg: "{{ tmpdata | json_query(query) }}"
vars:
query: >-
"lldp_output['gathered']"[?mode=='trunk']
This will output:
TASK [Take 4] *********************************************************************************
ok: [localhost] => {
"msg": [
{
"mode": "trunk",
"name": "GigabitEthernet0/0",
"trunk": {
"encapsulation": "dot1q"
}
}
]
}
Update
Given the data you've shown in your updated question, things are much
simpler, because you don't have the weird quoting you had in the
original question. With intf_output defined as shown, you can
write:
tasks:
- name: Take 4
debug:
msg: "{{ intf_output | json_query(query) }}"
vars:
query: >-
gathered[?mode=='trunk']

Ansible / jmespath - 1d list to zipped list of dictionaries

I'm attempting to transform a 1d list of AWS EC2 IDs into a list of dictionaries suitable for usage as the targets param to the Ansible elb_target_group module.
Sample input:
TASK [debug]
ok: [localhost] => {
"instance_ids": [
"i-1111",
"i-2222",
"i-3333"
]
}
Desired output:
TASK [debug]
ok: [localhost] => {
"targets": [
{"Id": "i-1111", "Port": 6443},
{"Id": "i-2222", "Port": 6443},
{"Id": "i-3333", "Port": 6443},
]
}
What I've tried: a json_query / JMESPath expression which confusingly returns null values:
---
- name: test
hosts: localhost
connection: local
vars:
instance_ids:
- i-1111
- i-2222
- i-3333
keys_list:
- Id
- Port
tasks:
- debug: var=instance_ids
- debug:
msg: "{{ instance_ids | zip_longest([6443], fillvalue=6443) | list }}" # Halfway there...
- debug:
msg: "{{ instance_ids | zip_longest([6443], fillvalue=6443) | list | map('json_query', '{Id: [0], Port: [1]}') | list }}"
Output:
TASK [debug]
ok: [localhost] => {
"msg": [
[
"i-1111",
6443
],
[
"i-2222",
6443
],
[
"i-3333",
6443
]
]
}
TASK [debug]
ok: [localhost] => {
"msg": [
{
"Id": null,
"Port": null
},
{
"Id": null,
"Port": null
},
{
"Id": null,
"Port": null
}
]
}
How should I adjust the '{Id: [0], Port: [1]}' part ?
Stumbled my way to a working solution with json_query and a JMESPath int literal:
"{{ instance_ids | json_query('[*].{Id: #, Port: `6443`}') }}"
Example:
- name: test
hosts: localhost
connection: local
vars:
instance_ids:
- i-1111
- i-2222
- i-3333
tasks:
- debug:
msg: "{{ instance_ids | json_query('[*].{Id: #, Port: `6443`}') }}"
Output:
TASK [debug]
ok: [localhost] => {
"msg": [
{
"Id": "i-1111",
"Port": 6443
},
{
"Id": "i-2222",
"Port": 6443
},
{
"Id": "i-3333",
"Port": 6443
}
]
}

Parse / Loop ansible registered variable

Trying to figure out how to filter out the list of UserNames in the output of the following playbook.
- name: Get all users
ome_user_info:
hostname: "{{ dellome_hostname }}"
username: "{{ dellome_username }}"
password: "{{ dellome_password }}"
register: users
Now the output provides the following:
ok: [192.168.1.100] => {
"users": {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"deprecations": [
{
"msg": "Distribution Ubuntu 18.04 on host 192.168.1.100 should use /usr/bin/python3, but is using /usr/bin/python for backward compatibility with prior Ansible releases. A future Ansible release will default to using the discovered platform python for this host. See https://docs.ansible.com/ansible/2.8/reference_appendices/interpreter_discovery.html for more information",
"version": "2.12"
}
],
"failed": false,
"user_info": {
"192.168.1.100": {
"#odata.context": "/api/$metadata#Collection(AccountService.Account)",
"#odata.count": 3,
"value": [
{
"#odata.id": "/api/AccountService/Accounts('10066')",
"#odata.type": "#AccountService.Account",
"Description": "admin",
"DirectoryServiceId": 0,
"Enabled": true,
"Id": "10066",
"IsBuiltin": true,
"Locked": false,
"Name": "admin",
"Password": null,
"Permissions#odata.navigationLink": "/api/AccountService/Accounts('10066')/Permissions",
"RoleId": "10",
"UserName": "admin",
"UserTypeId": 1
},
{
"#odata.id": "/api/AccountService/Accounts('10102')",
"#odata.type": "#AccountService.Account",
"Description": null,
"DirectoryServiceId": 0,
"Enabled": true,
"Id": "10102",
"IsBuiltin": false,
"Locked": false,
"Name": "dell",
"Password": null,
"Permissions#odata.navigationLink": "/api/AccountService/Accounts('10102')/Permissions",
"RoleId": "10",
"UserName": "dell",
"UserTypeId": 1
},
{
"#odata.id": "/api/AccountService/Accounts('10233')",
"#odata.type": "#AccountService.Account",
"Description": null,
"DirectoryServiceId": 10232,
"Enabled": true,
"Id": "10233",
"IsBuiltin": false,
"Locked": false,
"Name": "Domain Users",
"Password": null,
"Permissions#odata.navigationLink": "/api/AccountService/Accounts('10233')/Permissions",
"RoleId": "10",
"UserName": "Domain Users",
"UserTypeId": 2
}
]
}
}
}
}
I was able to determine the following from the output of the registered variable users.
- debug:
var: "{{ users | length }}"
This provides me the length of 5. Which makes sense to an extent. If I start poking into the output I can then determine the following:
- debug:
var: "{{ users.user_info | length }}"
This shows me the length of 1 which makes sense. If I add the var using users.user_info I can then see the output below.
TASK [manage_users : debug] *************************************************************************************************************************************************************
ok: [192.168.1.100] => {
"users.user_info": {
"192.168.1.100": {
"#odata.context": "/api/$metadata#Collection(AccountService.Account)",
"#odata.count": 3,
"value": [
{
"#odata.id": "/api/AccountService/Accounts('10066')",
"#odata.type": "#AccountService.Account",
"Description": "admin",
"DirectoryServiceId": 0,
"Enabled": true,
"Id": "10066",
"IsBuiltin": true,
"Locked": false,
"Name": "admin",
"Password": null,
"Permissions#odata.navigationLink": "/api/AccountService/Accounts('10066')/Permissions",
"RoleId": "10",
"UserName": "admin",
"UserTypeId": 1
},
{
"#odata.id": "/api/AccountService/Accounts('10102')",
"#odata.type": "#AccountService.Account",
"Description": null,
"DirectoryServiceId": 0,
"Enabled": true,
"Id": "10102",
"IsBuiltin": false,
"Locked": false,
"Name": "dell",
"Password": null,
"Permissions#odata.navigationLink": "/api/AccountService/Accounts('10102')/Permissions",
"RoleId": "10",
"UserName": "dell",
"UserTypeId": 1
},
{
"#odata.id": "/api/AccountService/Accounts('10233')",
"#odata.type": "#AccountService.Account",
"Description": null,
"DirectoryServiceId": 10232,
"Enabled": true,
"Id": "10233",
"IsBuiltin": false,
"Locked": false,
"Name": "Domain Users",
"Password": null,
"Permissions#odata.navigationLink": "/api/AccountService/Accounts('10233')/Permissions",
"RoleId": "10",
"UserName": "Domain Users”,
"UserTypeId": 2
}
]
}
}
}
Trying to figure out how I can loop through and get an array of the following: value —> UserName. Essentially I am going to take the following value and loop through and delete users that don’t equal the following. Admin, dell, domain users.
Now one might say you would easily just say while not = to items - then that list would work - I first need to figure out how to search and get the values out. I have tried the following:
- debug:
var: users.user_info().value()
- debug:
var: users.user_info.find('UserName')
- debug:
msg: UserName
loop: users.user_info."192.168.1.100".value
#- debug:
# var: users.user_info."{{ dellome_hostname }}".UserName
#- debug:
# var: "(claims1 | from_json).value"
# msg: "{{ users.user_info.UserName | list }}"
# (output_text.stdout | from_json).ismaster
#- debug:
# msg: "{{ item }}"
#loop: "{{ users.user_info | from_json | list }}"
At the end of this once I understand how to get the data out i can then create a loop to execute the following:
---
- name: Delete a User in Dell OME
ome_user:
hostname: "{{ dellome_hostname }}"
username: "{{ dellome_username }}"
password: "{{ dellome_password }}"
state: "{{ requestedState }}"
name: "{{ requstedUserName }}"
This is where i can then add the loop to eliminate users that don't meet the list of names i provide. Any help would be greatly appreciated.
Here are some of the errors i have run into.
TASK [manage_users : debug] *************************************************************************************************************************************************************
fatal: [192.168.1.100]: FAILED! => {"msg": "Unexpected templating type error occurred on ({{users.user_info().value()}}): 'dict' object is not callable"}
TASK [manage_users : debug] *************************************************************************************************************************************************************
fatal: [192.168.1.100]: FAILED! => {"msg": "template error while templating string: expected name or number. String: {{users.user_info.\"192.168.1.100\".value()}}"}
Or as i am looking at this - if i can figure out a way to create a loop that looks for the roleID and when it is not equal to 10 then delete the user.
Use json_query. The tasks below
- set_fact:
users_rm: "{{ users.user_info|
json_query('*.value[].UserName') }}"
- debug:
var: users_rm
give
users_rm:
- admin
- dell
- Domain Users
You are running the query at the host 192.168.1.100 and the dictionary users comprises the users from this single host only. If there are more hosts in the dictionary the asterisk '*' in the query above would select them all. It would be better to select users for the particular host the query is running at. For example, the task below gives the same result
- set_fact:
users_rm: "{{ users.user_info[inventory_hostname].value|
map(attribute='UserName')|
list }}"

How to access duplicate values in a JSON array and set each to a unique variable in ansible?

I am running an ansible playbook which outputs my information in JSON. This array has a loop that has multiple identical keys with different values. Please see below, I am interested in the "intf_id":
"stdout": [
{
"TABLE_cdp_neighbor_brief_info": {
"ROW_cdp_neighbor_brief_info": [
{
"capability": [
"switch",
"IGMP_cnd_filtering"
],
"device_id": "osw1J15",
"ifindex": "83886080",
"intf_id": "mgmt0",
"platform_id": "cisco WS-C2960X-48TS-LL",
"port_id": "GigabitEthernet0/45",
"ttl": "160"
},
{
"capability": [
"router",
"switch",
"Supports-STP-Dispute"
],
"device_id": "spine01",
"ifindex": "436232192",
"intf_id": "Ethernet1/49",
"platform_id": "N9K-C9508",
"port_id": "Ethernet1/11",
"ttl": "159"
},
{
"capability": [
"router",
"switch",
"Supports-STP-Dispute"
],
"device_id": "spine02",
"ifindex": "436232704",
"intf_id": "Ethernet1/50",
"platform_id": "N9K-C9508",
"port_id": "Ethernet1/11",
"ttl": "127"
},
{
"capability": [
"router",
"switch",
"IGMP_cnd_filtering",
"Supports-STP-Dispute"
],
"device_id": "leaf1J1402",
"ifindex": "436234240",
"intf_id": "Ethernet1/53",
"platform_id": "N9K-C93180YC-EX",
"port_id": "Ethernet1/53",
"ttl": "175"
},
{
"capability": [
"router",
"switch",
"IGMP_cnd_filtering",
"Supports-STP-Dispute"
],
"device_id": "leaf1J1402",
"ifindex": "436234752",
"intf_id": "Ethernet1/54",
"platform_id": "N9K-C93180YC-EX",
"port_id": "Ethernet1/54",
"ttl": "175"
}
]
},
"neigh_count": "5"
}
]
Currently I can access the first iteration of "intf_id" with :
- debug: msg="{{ list.stdout[0].TABLE_cdp_neighbor_brief_info.ROW_cdp_neighbor_brief_info[0].intf_id }}"
I feel like I'm close, but cannot figure out how to get each iteration of "intf_id". I can get subsequent ones by changing ROW_cdp_neighbor_brief_info[0] to [1] or [2], etc. I need to be able to access each key, without knowing how many keys there will be. Each value to the keys also need to be individually callable by subsequent tasks.
1) How do I get ansible to debug each iteration?
2) Depending on the answer to 1, how can I assign a particualr variable to each value? (ie. interface1, interface2, interface3...)
ansible-playbook json_query.yml
tasks:
- name:
debug:
msg: "{{ item }}"
loop: "{{ stdout | json_query('TABLE_cdp_neighbor_brief_info.ROW_cdp_neighbor_brief_info[*].intf_id') }}"
(output abridged)
"msg": "mgmt0"
"msg": "Ethernet1/49"
"msg": "Ethernet1/50"
"msg": "Ethernet1/53"
"msg": "Ethernet1/54"
You can use the filter json_query with jmespath syntax to loop over the various elements intf_id this way
---
- hosts: localhost
gather_facts: no
tasks:
- name: populate router data from json
set_fact:
data: "{{ lookup('file','so-router-info.json') }}"
- name: looping over interfaces
debug:
var: item
loop: "{{ data | json_query('TABLE_cdp_neighbor_brief_info.ROW_cdp_neighbor_brief_info[*].intf_id') }}"
it gives this output
…
TASK [looping over interfaces] ********************************************************************************************************
ok: [localhost] => (item=mgmt0) => {
"item": "mgmt0"
}
ok: [localhost] => (item=Ethernet1/49) => {
"item": "Ethernet1/49"
}
ok: [localhost] => (item=Ethernet1/50) => {
"item": "Ethernet1/50"
…
You can use the site http://jmespath.org/ to tests filters

Resources