How to fetch multiple values from a nested JSON like output - json

I am looking forward a way to list the value from a nested variable (which has dict and list values) ie register which is response_find and I have that in mostly json format and most of the values inside the json are nested within [] list like construct.
It works somehow if I get individual values from it like below:
var=response_find['json']['results'][0]['content_facet_attributes']
or
var=response_find['json']['results'][0]['certname']
But did not work when I did below:
var=response_find['json']['results'][0]['content_view_id']
Below are few values which I'm looking forward to fetch from this nested output:
"architecture_name": "x86_64",
"name": "satcap.rest.example.com",
"url": "https://satcap.rest.example.com:9090"
"content_source_name": "satcap.rest.example.com",
"name": "ccv-azure-infra-rhel7"
"name": "Prod"
"id": 33485,
"ip": "192.168.88.88",
"name": "invwharn108.test.exampl.com",
"registered_through": "satcap.rest.example.com"
Nested Json output:
{
"response_find": {
"apipie_checksum": "7533ab625c45a3819647f4fb4c9394c2832c0180",
"cookies": {
"_session_id": "25872833d9e2723073797fbd8cfa2d63"
},
"cookies_string": "_session_id=25872833d9e2723073797fbd8cfa2d63",
"foreman_version": "1.24.1.21",
"json": {
"page": 1,
"per_page": 20,
"results": [
{
"architecture_id": 1,
"architecture_name": "x86_64",
"build": false,
"capabilities": [
"build"
],
"certname": "invwharn108.test.exampl.com",
"comment": null,
"content_facet_attributes": {
"applicable_module_stream_count": 0,
"applicable_package_count": 0,
"content_source": {
"id": 17,
"name": "satcap.rest.example.com",
"url": "https://satcap.rest.example.com:9090"
},
"content_source_id": 17,
"content_source_name": "satcap.rest.example.com",
"content_view": {
"id": 67,
"name": "ccv-azure-infra-rhel7"
},
"content_view_id": 67,
"content_view_name": "ccv-azure-infra-rhel7",
"errata_counts": {
"bugfix": 0,
"enhancement": 0,
"security": 0,
"total": 0
},
"id": 32255,
"kickstart_repository": {
"id": 5772,
"name": "Red Hat Enterprise Linux 7 Server Kickstart x86_64 7.8"
},
"kickstart_repository_id": 5772,
"kickstart_repository_name": "5772",
"lifecycle_environment": {
"id": 5,
"name": "Prod"
},
"lifecycle_environment_id": 5,
"lifecycle_environment_name": "Prod",
"upgradable_module_stream_count": 0,
"upgradable_package_count": 0,
"uuid": "dab2d66b-1a73-490a-aa9d-3f036658980a"
},
"created_at": "2020-12-23 13:19:35 UTC",
"disk": null,
"domain_id": 25,
"domain_name": "test.example-aws.example.com",
"enabled": true,
"environment_id": null,
"environment_name": null,
"errata_status": 1,
"errata_status_label": "Could not calculate errata status, ensure host is registered and the katello-host-tools package is installed",
"global_status": 1,
"global_status_label": "Warning",
"hostgroup_id": 982,
"hostgroup_name": "infra",
"hostgroup_title": "NXDI-hg-aws/west-europe/infra",
"id": 33485,
"image_file": "",
"image_id": null,
"image_name": null,
"installed_at": null,
"ip": "192.168.88.88",
"ip6": null,
"last_compile": "2020-12-23 13:19:38 UTC",
"last_report": null,
"location_id": 37,
"location_name": "west-europe",
"mac": "02:78:43:60:ee:fb",
"managed": false,
"medium_id": null,
"medium_name": null,
"model_id": 25,
"model_name": "HVM domU",
"name": "invwharn108.test.exampl.com",
"openscap_proxy": null,
"openscap_proxy_id": null,
"openscap_proxy_name": null,
"operatingsystem_id": 21,
"operatingsystem_name": "RedHat 7.8",
"organization_id": 3,
"pxe_loader": "PXELinux BIOS",
"subnet_id": 65,
"subnet_name": "aws-west-europe-infra",
"subscription_facet_attributes": {
"autoheal": true,
"hypervisor": false,
"id": 33593,
"last_checkin": "2020-12-23 13:19:42 UTC",
"purpose_addons": [],
"purpose_role": "",
"purpose_usage": "",
"registered_at": "2020-12-23 13:19:35 UTC",
"registered_through": "satcap.rest.example.com",
},
"subscription_global_status": 1,
"subscription_status": 1,
"subscription_status_label": "Partially entitled",
}
],
"search": "name=invwharn108.test.exampl.com",
"sort": {
"by": null,
"order": null
},
"subtotal": 1,
"total": 13121
},
"msg": "OK (unknown bytes)",
"x_request_id": "e02dd9b3-b2f8-4c39-8bf5-1ce1897d9548",
}
}
My Play:
---
- hosts: localhost
tasks:
- include_vars: vaults/aws_secrets.yml
no_log: true
- include_vars: requirements.yml
no_log: true
- name: Find the ID of Cloud VM in Satellite
uri:
url: "https://{{ satserver }}/api/v2/hosts?search=name={{ aws_instance_name }}"
method: GET
user: "{{ aws_satuser }}"
password: "{{ aws_satpw }}"
force_basic_auth: yes
validate_certs: no
register: response_find
delegate_to: localhost
changed_when: false
- debug:
var=response_find['json']['results'][0]['content_facet_attributes']
#var=response_find.json.results.0.organization_name
#var=response_find['json']['results'][0]['certname']
Result:
"content_facet_attributes": {
"applicable_module_stream_count": 0,
"applicable_package_count": 0,
"content_source": {
"id": 17,
"name": "satcap.rest.example.com",
"url": "https://satcap.rest.example.com:9090"
},
"content_source_id": 17,
"content_source_name": "satcap.rest.example.com",
"content_view": {
"id": 67,
"name": "ccv-azure-infra-rhel7"
},
"content_view_id": 67,
"content_view_name": "ccv-azure-infra-rhel7",
"errata_counts": {
"bugfix": 0,
"enhancement": 0,
"security": 0,
"total": 0
},
"id": 32255,
"kickstart_repository": {
"id": 5772,
"name": "Red Hat Enterprise Linux 7 Server Kickstart x86_64 7.8"
},
"kickstart_repository_id": 5772,
"kickstart_repository_name": "5772",
"lifecycle_environment": {
"id": 5,
"name": "Prod"
},
"lifecycle_environment_id": 5,
"lifecycle_environment_name": "Prod",
"upgradable_module_stream_count": 0,
"upgradable_package_count": 0,
"uuid": "dab2d66b-1a73-490a-aa9d-3f036658980a"
},

If you want to do a dictionary out of those data you listed, you could use the filter json_query, which is using JMESPath to parse and process JSON.
In order to extract a dictionary looking like:
{
"architecture_name": "x86_64",
"content_source_name": "satcap.rest.example.com",
"content_source_url": "https://satcap.rest.example.com:9090",
"content_view_name": "ccv-azure-infra-rhel7",
"egistered_through": "satcap.rest.example.com",
"id": 33485,
"ip": "192.168.88.88",
"lifecycle_environment_name": "Prod",
"name": "invwharn108.test.exampl.com"
}
You could use JMESPath to filter multiselect hashes.
Here is a JMESPath query that would give this result:
json.results[*].{
"architecture_name": architecture_name,
"content_source_name": content_facet_attributes.content_source.name,
"content_source_url": content_facet_attributes.content_source.url,
"content_view_name": content_facet_attributes.content_view.name,
"lifecycle_environment_name": content_facet_attributes.lifecycle_environment.name,
"id": id,
"ip": ip,
"name": name,
"egistered_through": subscription_facet_attributes.registered_through
}
Here is an example playbook using this:
- hosts: localhost
gather_facts: no
tasks:
- debug:
msg: >-
{{
(
response_find | json_query('
json.results[*].{
"architecture_name": architecture_name,
"content_source_name": content_facet_attributes.content_source.name,
"content_source_url": content_facet_attributes.content_source.url,
"content_view_name": content_facet_attributes.content_view.name,
"lifecycle_environment_name": content_facet_attributes.lifecycle_environment.name,
"id": id,
"ip": ip,
"name": name,
"egistered_through": subscription_facet_attributes.registered_through
}
')
).0
}}
vars:
{
"response_find": {
"apipie_checksum": "7533ab625c45a3819647f4fb4c9394c2832c0180",
"cookies": {
"_session_id": "25872833d9e2723073797fbd8cfa2d63"
},
"cookies_string": "_session_id=25872833d9e2723073797fbd8cfa2d63",
"foreman_version": "1.24.1.21",
"json": {
"page": 1,
"per_page": 20,
"results": [{
"architecture_id": 1,
"architecture_name": "x86_64",
"build": false,
"capabilities": [
"build"
],
"certname": "invwharn108.test.exampl.com",
"comment": null,
"content_facet_attributes": {
"applicable_module_stream_count": 0,
"applicable_package_count": 0,
"content_source": {
"id": 17,
"name": "satcap.rest.example.com",
"url": "https://satcap.rest.example.com:9090"
},
"content_source_id": 17,
"content_source_name": "satcap.rest.example.com",
"content_view": {
"id": 67,
"name": "ccv-azure-infra-rhel7"
},
"content_view_id": 67,
"content_view_name": "ccv-azure-infra-rhel7",
"errata_counts": {
"bugfix": 0,
"enhancement": 0,
"security": 0,
"total": 0
},
"id": 32255,
"kickstart_repository": {
"id": 5772,
"name": "Red Hat Enterprise Linux 7 Server Kickstart x86_64 7.8"
},
"kickstart_repository_id": 5772,
"kickstart_repository_name": "5772",
"lifecycle_environment": {
"id": 5,
"name": "Prod"
},
"lifecycle_environment_id": 5,
"lifecycle_environment_name": "Prod",
"upgradable_module_stream_count": 0,
"upgradable_package_count": 0,
"uuid": "dab2d66b-1a73-490a-aa9d-3f036658980a"
},
"created_at": "2020-12-23 13:19:35 UTC",
"disk": null,
"domain_id": 25,
"domain_name": "test.example-aws.example.com",
"enabled": true,
"environment_id": null,
"environment_name": null,
"errata_status": 1,
"errata_status_label": "Could not calculate errata status, ensure host is registered and the katello-host-tools package is installed",
"global_status": 1,
"global_status_label": "Warning",
"hostgroup_id": 982,
"hostgroup_name": "infra",
"hostgroup_title": "NXDI-hg-aws/west-europe/infra",
"id": 33485,
"image_file": "",
"image_id": null,
"image_name": null,
"installed_at": null,
"ip": "192.168.88.88",
"ip6": null,
"last_compile": "2020-12-23 13:19:38 UTC",
"last_report": null,
"location_id": 37,
"location_name": "west-europe",
"mac": "02:78:43:60:ee:fb",
"managed": false,
"medium_id": null,
"medium_name": null,
"model_id": 25,
"model_name": "HVM domU",
"name": "invwharn108.test.exampl.com",
"openscap_proxy": null,
"openscap_proxy_id": null,
"openscap_proxy_name": null,
"operatingsystem_id": 21,
"operatingsystem_name": "RedHat 7.8",
"organization_id": 3,
"pxe_loader": "PXELinux BIOS",
"subnet_id": 65,
"subnet_name": "aws-west-europe-infra",
"subscription_facet_attributes": {
"autoheal": true,
"hypervisor": false,
"id": 33593,
"last_checkin": "2020-12-23 13:19:42 UTC",
"purpose_addons": [],
"purpose_role": "",
"purpose_usage": "",
"registered_at": "2020-12-23 13:19:35 UTC",
"registered_through": "satcap.rest.example.com"
},
"subscription_global_status": 1,
"subscription_status": 1,
"subscription_status_label": "Partially entitled"
}],
"search": "name=invwharn108.test.exampl.com",
"sort": {
"by": null,
"order": null
},
"subtotal": 1,
"total": 13121
},
"msg": "OK (unknown bytes)",
"x_request_id": "e02dd9b3-b2f8-4c39-8bf5-1ce1897d9548"
}
}
Which gives the recap:
PLAY [localhost] *************************************************************************************************
TASK [debug] *****************************************************************************************************
ok: [localhost] => {
"msg": {
"architecture_name": "x86_64",
"content_source_name": "satcap.rest.example.com",
"content_source_url": "https://satcap.rest.example.com:9090",
"content_view_name": "ccv-azure-infra-rhel7",
"egistered_through": "satcap.rest.example.com",
"id": 33485,
"ip": "192.168.88.88",
"lifecycle_environment_name": "Prod",
"name": "invwharn108.test.exampl.com"
}
}
PLAY RECAP *******************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

Related

json jq request format

I need help to extract data from this JSON file using jq.
The app flv then verify the streamname mystrame is active and extract meta.video.height
I did try lot of queries without success and my jq knowledge is poor.
{
"port": 1935,
"server_index": 0,
"applications": [{
"name": "hls",
"live": {
"streams": [{
"name": "donbosco",
"time": 2380739,
"bw_in": 2112440,
"bytes_in": 541618713,
"bw_out": 0,
"bytes_out": 0,
"bw_audio": 35544,
"bw_video": 2076888,
"clients": [{
"id": 453,
"address": "127.0.0.1",
"time": 2380959,
"flashver": "FMLE/3.0 (compatible; Lavf57.83.100)",
"dropped": 0,
"avsync": 28,
"timestamp": 2382635,
"publishing": true,
"active": true
}],
"records": [],
"meta": {
"video": {
"width": 1168,
"height": 720,
"frame_rate": 25,
"codec": "H264",
"profile": "High",
"level": 3.1
},
"audio": {
"codec": "AAC",
"profile": "LC",
"channels": 2,
"sample_rate": 16000
}
},
"nclients": 1,
"publishing": true,
"active": true
}],
"nclients": 1
},
"recorders": {
"count": 0,
"lists": []
}
},
{
"name": "flv",
"live": {
"streams": [{
"name": "mystream",
"time": 2382811,
"bw_in": 2059096,
"bytes_in": 541841549,
"bw_out": 2059096,
"bytes_out": 543351459,
"bw_audio": 35472,
"bw_video": 2023624,
"clients": [{
"id": 452,
"address": "127.0.0.1",
"time": 2382727,
"flashver": "LNX 9,0,124,2",
"dropped": 0,
"avsync": -12,
"timestamp": 2384520,
"publishing": false,
"active": true
},
{
"id": 451,
"address": "127.0.0.1",
"time": 2383031,
"flashver": "FMLE/3.0 (compatible; Lavf58.74.100)",
"dropped": 0,
"avsync": -12,
"timestamp": 2384520,
"publishing": true,
"active": true
}
],
"records": [],
"meta": {
"video": {
"width": 1168,
"height": 720,
"frame_rate": 25,
"codec": "H264",
"profile": "High",
"level": 3.1
},
"audio": {
"codec": "AAC",
"profile": "LC",
"channels": 2,
"sample_rate": 16000
}
},
"nclients": 2,
"publishing": true,
"active": true
}],
"nclients": 2
},
"recorders": {
"count": 0,
"lists": []
}
}
]
}
Are you asking for help with the command-line JSON processor jq or the JavaScript library jQuery? They are not the same. For jq, try
jq '
.applications
| map(select(.name == "flv"))[].live.streams
| map(select(.name == "mystream" and .active))[].meta.video.height
'
720
Demo

Python 3 - Extracting value from key in nested dictionary

Hoping for some pointers here as I'm striking out with my attempts. Am working with python 3.8.5.
I'm querying a Car Park booking system that returns a json list of availability. The result has lots of nested dictionaries and I'm struggling to extract just the values i want.
This is what I've been doing:
import requests
import json
enquiry = requests.post(url.....) #queries api, this works fine
results = enquiry.text #extracts response data
dictionary = json.loads(results) #convert response to python dict
If there is one slot available, I get this output (apologies for length). If there are multiple slots available, i get the same output repeated:
{
"data": {
"services": [{
"id": null,
"name": null,
"services": [{
"id": null,
"name": "Car Park",
"met": true,
"filterCount": 1,
"primary": true,
"options": [{
"id": "9",
"images": [],
"available": true,
"calendarId": "AAAA",
"templateId": "BBBB",
"capacity": 0,
"name": "Car Park Slot 3",
"sessionId": "CCCC",
"functions": null,
"startDate": "2020-08-18T13:30:00Z", <--this is what I want to extract
"endDate": "2020-08-18T14:30:00Z",
"geo": {
"lat": 0.0,
"lng": 0.0
},
"selected": false,
"linkedServices": [],
"tiers": null
}]
}],
"currentBookingId": null,
"startDate": {
"ms": 1597757400000,
"year": 2020,
"month": 8,
"day": 18,
"dayOfWeek": 2,
"time": {
"seconds": 0,
"minutes": 30,
"hours": 14,
"days": 0
}
},
"endDate": {
"ms": 1597761000000,
"year": 2020,
"month": 8,
"day": 18,
"dayOfWeek": 2,
"time": {
"seconds": 0,
"minutes": 30,
"hours": 15,
"days": 0
}
},
"sessionId": "2222222",
"chargeType": 1,
"hasPrimaryBookable": false,
"hasBookable": false,
"hasDiscounts": false,
"hasMultipleTiers": false,
"isPreferred": false,
"primaryServiceAvailable": true,
"primaryServiceId": null,
"primaryServiceType": "undefined",
"unavailableAttendees": []
}],
"bookingLimit": null
},
"success": true,
"suppress": false,
"version": "2.3.293",
"message": null,
"result": null,
"errors": null,
"code": null,
"flags": 0,
"redirect": null
}
I want to extract:
"startDate": "2020-08-18T13:30:00Z"
from each key, value pair in any of the returned slots. However, I cant work it out.
Extracting the whole of this nested dictionary would also contain the same data, but would then involve more work to tidy it up after.
"startDate": {
"ms": 1597757400000,
"year": 2020,
"month": 8,
"day": 18,
"dayOfWeek": 2,
"time": {
"seconds": 0,
"minutes": 30,
"hours": 14,
"days": 0
}
I've tried loads of dictionary.get and dictionary.items variations, but cant seem to get anywhere.
I tried something like
key = ('startDate')
availability = dictionary.get(key)
print(availability)
this just returns 'none', so think im way off
Any pointers?
Thanks in advance!
Thanks for the full data. It makes testing easier :)
I had to replace null -> None, true -> True, false -> False
slot = {
"data": {
"services": [{
"id": None,
"name": None,
"services": [{
"id": None,
"name": "Car Park",
"met": True,
"filterCount": 1,
"primary": True,
"options": [{
"id": "9",
"images": [],
"available": True,
"calendarId": "AAAA",
"templateId": "BBBB",
"capacity": 0,
"name": "Car Park Slot 3",
"sessionId": "CCCC",
"functions": None,
"startDate": "2020-08-18T13:30:00Z", # <--this is what I want to extract
................
print("Start Date:", slot['data']['services'][0]['services'][0]['options'][0]['startDate'])
Output
Start Date: 2020-08-18T13:30:00Z

How to extract multiple correlating variables from a JSon

I have to extract multiple correlating variables from a response (which is json) in JMeter. Part of the response is listed below:
[
{
"data": {
"id": "efaa6876-7a8d-4723-9d85-1ed99e822f06",
"type": "courses",
"attributes": {
"created-at": "2019-02-07T16:38:50.735Z",
"contents-count": 267,
"units": [
{
"id": "31b5fcb1-24ee-441e-a0ee-ca859fc9a89d",
"position": null,
"progress": 0,
"completed": false,
"show_name": false,
"node_id": "1",
"children": [
{
"id": "b8ed75a3-0390-4273-82c3-03ee6eba729c",
"position": null,
"image": null,
"progress": 0,
"completed": false,
"show_name": true,
"node_id": "2",
"children": [],
"contents": [
{
"id": "fa1bdc2f-4330-425c-9c10-3734d07125aa",
"link": {
"url": "#",
"target": "_blank",
"class": "learning-object-link",
"data": {
"id": "fa1bdc2f-4330-425c-9c10-3734d07125aa",
"user-role": "teacher",
"open-method-tablet": "newtab",
"open-method-desktop": "modal",
"content-open-method": null,
"modal-size-method": "fully_responsive",
"fixed-width": null,
"fixed-height": null,
"aspect-ratio": null
}
},
"is_work": false,
"is_fun": false,
"completed": false,
"total_activities": 2,
"completed_activities": 0,
"progress": 0,
"updated_at": false,
"attempts": 0,
"duration": null
},
{
"id": "ceceabfd-5151-4656-af5d-3392c5a4c04c",
"link": {
"url": "#",
"target": "_blank",
"class": "learning-object-link",
"data": {
"id": "ceceabfd-5151-4656-af5d-3392c5a4c04c",
"user-role": "teacher",
"open-method-tablet": "newtab",
"open-method-desktop": "modal",
"content-open-method": null,
"modal-size-method": "fully_responsive",
"fixed-width": null,
"fixed-height": null,
"aspect-ratio": null
}
},
"is_work": false,
"is_fun": false,
"completed": false,
"total_activities": 2,
"completed_activities": 0,
"progress": 0,
"updated_at": false,
"attempts": 0,
"duration": null
}
]
},
{
"id": "60639cbd-f872-492d-b8e9-db83f8789fcf",
"position": null,
"image": null,
"progress": 0,
"completed": false,
"show_name": true,
"node_id": "3",
"children": [],
"contents": [
{
"id": "1825f834-7099-4bb4-b7a2-fc634faffc86",
"link": {
"url": "#",
"target": "_blank",
"class": "learning-object-link",
"data": {
"id": "1825f834-7099-4bb4-b7a2-fc634faffc86",
"user-role": "teacher",
"open-method-tablet": "newtab",
"open-method-desktop": "modal",
"content-open-method": null,
"modal-size-method": "fully_responsive",
"fixed-width": null,
"fixed-height": null,
"aspect-ratio": null
}
},
To proceed with the next request, I have to extract unit id (e.g. 31b5fcb1-24ee-441e-a0ee-ca859fc9a89d), children id (e.g. b8ed75a3-0390-4273-82c3-03ee6eba729c) and contents id (e.g. fa1bdc2f-4330-425c-9c10-3734d07125aa). There are several units, each unit has several children and each children has several contents. Each content id matches just one children id and each children id matches just one unit id. Ids have to be selected on a random basis.
I've tried to extract all ids from the response and use them randomly, but it doesn't work this way.
To extract only Unit Ids, you can use following JSON Path Expressions:
$..data.attributes.units[?(#.id)].id
Random Value for Unit Id also can be extracted using JMeter JSON Extractor:

Network IP addresses with jq bash command from docker inspect

I want to process docker inspect <container1> <container2> out to retrieve via jq command exposed ports and IPAddresses assigned to defined networks. So far I've got jq '{(.[].Name): getpath(path(.[].NetworkSettings.Networks)) | .[].IPAddress}' which is clearly far from enough.
p.s. I know its easy to write a script that would give such output but I'm curious how to do that using jq
Expected output
{
# .[].Name
"/prometheus_prometheus_1": [
[
# .[].Config.ExposedPorts
"9090/tcp"
],
{
# key = .[].NetworkSettings.Networks.<index>
# value = .[].NetworkSettings.Networks[].IPAddress
"prometheus_internal": "172.21.0.4",
"system-information": "172.28.0.2"
}
]
}
Input:
[
{
"Id": "c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa",
"Created": "2018-06-12T05:33:19.811448302Z",
"Path": "/bin/prometheus",
"Args": [
"--config.file=/etc/prometheus/prometheus.yml",
"--storage.tsdb.path=/prometheus",
"--web.console.libraries=/usr/share/prometheus/console_libraries",
"--web.console.templates=/usr/share/prometheus/consoles"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 13217,
"ExitCode": 0,
"Error": "",
"StartedAt": "2018-06-12T05:33:20.264845701Z",
"FinishedAt": "0001-01-01T00:00:00Z"
},
"Image": "sha256:44a4c1c270dcb5e8caf51e3205fa23343cc903f3823eab53ae204f304d16f62a",
"ResolvConfPath": "/var/lib/docker/containers/c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa/hostname",
"HostsPath": "/var/lib/docker/containers/c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa/hosts",
"LogPath": "/var/lib/docker/containers/c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa/c2f86bce68441f50f973ae89a835d052e74c083e35b5438f3cec2497bcac79fa-json.log",
"Name": "/prometheus_prometheus_1",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "",
"ExecIDs": null,
"HostConfig": {
"Binds": [
"prometheus_prometheus-data:/prometheus:rw",
"/home/sebastian/projects/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:rw"
],
"ContainerIDFile": "",
"LogConfig": {
"Type": "json-file",
"Config": {}
},
"NetworkMode": "prometheus_internal",
"PortBindings": {},
"RestartPolicy": {
"Name": "always",
"MaximumRetryCount": 0
},
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": [],
"CapAdd": null,
"CapDrop": null,
"Dns": null,
"DnsOptions": null,
"DnsSearch": null,
"ExtraHosts": null,
"GroupAdd": null,
"IpcMode": "shareable",
"Cgroup": "",
"Links": null,
"OomScoreAdj": 0,
"PidMode": "",
"Privileged": false,
"PublishAllPorts": false,
"ReadonlyRootfs": false,
"SecurityOpt": null,
"UTSMode": "",
"UsernsMode": "",
"ShmSize": 67108864,
"Runtime": "runc",
"ConsoleSize": [
0,
0
],
"Isolation": "",
"CpuShares": 0,
"Memory": 0,
"NanoCpus": 0,
"CgroupParent": "",
"BlkioWeight": 0,
"BlkioWeightDevice": null,
"BlkioDeviceReadBps": null,
"BlkioDeviceWriteBps": null,
"BlkioDeviceReadIOps": null,
"BlkioDeviceWriteIOps": null,
"CpuPeriod": 0,
"CpuQuota": 0,
"CpuRealtimePeriod": 0,
"CpuRealtimeRuntime": 0,
"CpusetCpus": "",
"CpusetMems": "",
"Devices": null,
"DeviceCgroupRules": null,
"DiskQuota": 0,
"KernelMemory": 0,
"MemoryReservation": 0,
"MemorySwap": 0,
"MemorySwappiness": null,
"OomKillDisable": false,
"PidsLimit": 0,
"Ulimits": null,
"CpuCount": 0,
"CpuPercent": 0,
"IOMaximumIOps": 0,
"IOMaximumBandwidth": 0
},
"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/docker/overlay2/73c16b0735eb15494741e5b821a9df3be8cebb716219ac206d9ee0042e4166ac-init/diff:/var/lib/docker/overlay2/03c66042305488fea2fe693246e90374743fbb7836ab31e4ee5cdbfbb1c97785/diff:/var/lib/docker/overlay2/80821a00b79334493729e671dfb66cc878aec19fe2d0dfbaf4cde187522b06e8/diff:/var/lib/docker/overlay2/f5071cce5513fb3c465ad883297157271ef48c6f59cd88768068224d850c6903/diff:/var/lib/docker/overlay2/c9a0cc617abb45fbd4572abb41c7281c96bc9d59c109270c7f1ec7a99f5b055b/diff:/var/lib/docker/overlay2/5b425f8a440139a8fdcdd7f7fee8189565e9e00304e96f4cfee86ff6b861e068/diff:/var/lib/docker/overlay2/e85740d997591d2f60bfa61ea0c82a58636bccaaba970e55f12cf0ff24565c70/diff:/var/lib/docker/overlay2/e9c362d971c460b02111122b241888392d77c5b8545ed520c3d74660b16db9b2/diff:/var/lib/docker/overlay2/5001184fc8ddd25204626f419c1530b970cb37f936a196fb1173f2774310085e/diff:/var/lib/docker/overlay2/ed2e676f09a4583f2194e752083a7c95be80131f055891dc39f9fed5560f5a73/diff",
"MergedDir": "/var/lib/docker/overlay2/73c16b0735eb15494741e5b821a9df3be8cebb716219ac206d9ee0042e4166ac/merged",
"UpperDir": "/var/lib/docker/overlay2/73c16b0735eb15494741e5b821a9df3be8cebb716219ac206d9ee0042e4166ac/diff",
"WorkDir": "/var/lib/docker/overlay2/73c16b0735eb15494741e5b821a9df3be8cebb716219ac206d9ee0042e4166ac/work"
},
"Name": "overlay2"
},
"Mounts": [
{
"Type": "volume",
"Name": "prometheus_prometheus-data",
"Source": "/var/lib/docker/volumes/prometheus_prometheus-data/_data",
"Destination": "/prometheus",
"Driver": "local",
"Mode": "rw",
"RW": true,
"Propagation": ""
},
{
"Type": "bind",
"Source": "/home/sebastian/projects/prometheus/prometheus.yml",
"Destination": "/etc/prometheus/prometheus.yml",
"Mode": "rw",
"RW": true,
"Propagation": "rprivate"
}
],
"Config": {
"Hostname": "c2f86bce6844",
"Domainname": "",
"User": "nobody",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"ExposedPorts": {
"9090/tcp": {}
},
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"Cmd": [
"--config.file=/etc/prometheus/prometheus.yml",
"--storage.tsdb.path=/prometheus",
"--web.console.libraries=/usr/share/prometheus/console_libraries",
"--web.console.templates=/usr/share/prometheus/consoles"
],
"Image": "prom/prometheus:v2.3.0",
"Volumes": {
"/etc/prometheus/prometheus.yml": {},
"/prometheus": {}
},
"WorkingDir": "/prometheus",
"Entrypoint": [
"/bin/prometheus"
],
"OnBuild": null,
"Labels": {
"com.docker.compose.config-hash": "b8ff39fd239739ae66051752c1b49b0119862b8f21678fb42400c907d25b1c57",
"com.docker.compose.container-number": "1",
"com.docker.compose.oneoff": "False",
"com.docker.compose.project": "prometheus",
"com.docker.compose.service": "prometheus",
"com.docker.compose.version": "1.16.1",
"maintainer": "The Prometheus Authors <prometheus-developers#googlegroups.com>"
}
},
"NetworkSettings": {
"Bridge": "",
"SandboxID": "7be77954d0e6990f565a8526b157236140238cabf0954629598ce3bb9aaae885",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
"9090/tcp": null
},
"SandboxKey": "/var/run/docker/netns/7be77954d0e6",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "",
"Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"MacAddress": "",
"Networks": {
"prometheus_internal": {
"IPAMConfig": null,
"Links": null,
"Aliases": [
"prometheus",
"c2f86bce6844"
],
"NetworkID": "145c59986c16003f9a3a30e6b671c34b56225d90243fba88fc295c49b4dcfff6",
"EndpointID": "8e3ac8bd4719ea85358c20a8141c37377dd327265916d41ee5d1db6b7496898c",
"Gateway": "172.21.0.1",
"IPAddress": "172.21.0.4",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:15:00:04",
"DriverOpts": null
},
"system-information": {
"IPAMConfig": null,
"Links": null,
"Aliases": [
"prometheus",
"c2f86bce6844"
],
"NetworkID": "f6e67721cb73da7e8d4eacdb709de240014af9af35e66216e6186300c72de330",
"EndpointID": "2c31369f8175f2b38a5bc966a8306c8f0f11ac4c264e6ce735d00c87b8a6f44f",
"Gateway": "172.28.0.1",
"IPAddress": "172.28.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:1c:00:02",
"DriverOpts": null
}
}
}
}
]
jq solution:
jq '.[] | {(.Name) : [(.Config.ExposedPorts | keys),
(.NetworkSettings.Networks | to_entries
| map({(.key): .value.IPAddress}) | add)
]
}' input
The output:
{
"/prometheus_prometheus_1": [
[
"9090/tcp"
],
{
"prometheus_internal": "172.21.0.4",
"system-information": "172.28.0.2"
}
]
}

Ansible: EC2 provisioning and Iterations

I am trying to start a bunch of EC2 instances, then install something on them based on the IP given by AWS. With only one EC2, I can add the host and proceed without any issue,but when I chain them using with_dict, I can't achieve it anymore...
The following runs as I want, but I can't understand how to deal with the registered variable ec2_infos I got from the provisioning...
- name: Create Test EC2 instances
ec2:
group: default
image: ami-40d28157
instance_type: '{{item.value.type}}'
instance_tags:
Name: "{{ tag+'-'+item.value.name }}"
key_name: privatekey
region: us-west-1
vpc_subnet_id: subnet-REDACTD
wait: yes
with_dict: '{{ec2_stack}}'
register: ec2_infos
With a dictionary like
ec2_stack:
serv1:
type: t2.micro
name: server1
serv2:
type: t2.small
name: server2
ec2_infos is structures like:
"ec2_infos": {
"changed": true,
"msg": "All items completed",
"results": [
{
"_ansible_item_result": true,
"_ansible_no_log": false,
"_ansible_parsed": true,
"changed": true,
"instance_ids": [
"i-0fewq09812ddq6"
],
"instances": [
{
"ami_launch_index": "0",
"architecture": "x86_64",
"block_device_mapping": {
"/dev/sda1": {
"delete_on_termination": true,
"status": "attached",
"volume_id": "vol-0987654"
}
},
"dns_name": "",
"ebs_optimized": false,
"groups": {
"sg-qdwdww": "default"
},
"hypervisor": "xen",
"id": "i-083665656521dwq6",
"image_id": "ami-40d28157",
"launch_time": "2016-11-24T20:38:53.000Z",
"placement": "us-west-1d",
"private_ip": "x.x.x.x",
"public_dns_name": "",
"public_ip": null,
"ramdisk": null,
"region": "us-east-1",
"root_device_name": "/dev/sda1",
"root_device_type": "ebs",
"state": "running",
"state_code": 16,
"tags": {
"Name": "server1",
"Team": "blah"
},
"tenancy": "default","tenancy": "default",
"virtualization_type": "hvm"
}
],
"invocation": {
"module_args": {
"assign_public_ip": false,
"exact_count": null,
"group": [
"default"
],
"group_id": null,
"id": null,
"image": "ami-40d28157",
"instance_ids": null,
"instance_initiated_shutdown_behavior": null,
"instance_profile_name": null,
"instance_tags": {
"Name": "server1",
"Team": "blah"
},
"instance_type": "t2.micro",
"kernel": null,
"volumes": null,
"vpc_subnet_id": "subnet-abcdfed",
"wait": true,
"wait_timeout": "300",
"zone": null
},
"module_name": "ec2"
},
"item": {
"key": "serv1",
"value": {
"name": "server1",
"type": "t2.micro"
}
},
"tagged_instances": []
},
{
"_ansible_item_result": true,
"_ansible_no_log": false,
"_ansible_parsed": true,
"changed": true,
"instance_ids": [
"i-0971278624334fd"
],
"instances": [
{
"ami_launch_index": "0",
"architecture": "x86_64",
"block_device_mapping": {
"/dev/sda1": {
"delete_on_termination": true,
"status": "attached",
"volume_id": "vol-9999999"
}
},
"dns_name": "",
"ebs_optimized": false,
"groups": {
"sg-redactd": "default"
},
"launch_time": "2016-11-24T20:39:21.000Z",
"private_ip": "y.y.y.y",
"public_dns_name": "",
"public_ip": null,
"ramdisk": null,
"state": "running",
"state_code": 16,
"tags": {
"Name": "serv2",
"Team": "blah"
},
"tenancy": "default",
"virtualization_type": "hvm"
}
],
"invocation": {
"module_args": {
"assign_public_ip": false,
"wait_timeout": "300",
"zone": null
},
"module_name": "ec2"
},
"item": {
"key": "server2",
"value": {
"name": "serv2",
"type": "t2.small"
}
},
"tagged_instances": []
}
]
}
I tried with_items and with_subelements in different ways, but I can't manage to get every IPs of the new EC2. I don't even need to sort them just extract them from the instances part and feed them to add_host so I can proceed.
Anybody knows a clean way to do so, or would be kind enough to explain to me how to deal with a registered variable after a loop properly ?
Answer from the comments:
ec2_infos.results | map(attribute='instances') | sum(start=[]) | map(attribute='private_ip') | list