Skip to content

Instantly share code, notes, and snippets.

@luckylittle
Last active April 7, 2022 05:34
Show Gist options
  • Save luckylittle/e53c65a91d0d4a826cb201d89e5e7938 to your computer and use it in GitHub Desktop.
Save luckylittle/e53c65a91d0d4a826cb201d89e5e7938 to your computer and use it in GitHub Desktop.
Elegant way to append to a JSON file
---
# Example of constructing & appending to a JSON file
# Required JSON payload:
#
# [
# {
# "id": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
# "type": "host"
# },
# {
# "id": "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
# "type": "host"
# }
# ]
- hosts: localhost
become: no
vars:
type: "host"
tasks:
- name: 1.0 | Set the initial fact `uids`
set_fact:
uids:
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
- "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
- name: 2.0 | Construct the `data`
set_fact:
data: "{{ ( data | default([]) ) + [ { 'uid': item, 'type': type } ] }}"
with_items: "{{ uids }}"
# The `data` will look like:
#
# [
# {
# "type": "host",
# "uid": "aaa-aaaaaa-aaaaaaa-aaaaa"
# },
# {
# "type": "host",
# "uid": "bbb-bbbbbb-bbbbbbb-bbbbb"
# }
# ]
- name: 3.0 | Set another fact `add_uids`
set_fact:
add_uids:
- "cccccccc-cccc-cccc-cccc-cccccccccccc"
- "dddddddd-dddd-dddd-dddd-dddddddddddd"
- name: 4.0 | Construct the `new_data`
set_fact:
new_data: "{{ ( new_data | default([]) ) + [ { 'uid': item, 'type': type } ] }}"
with_items: "{{ add_uids }}"
- name: 5.0 | Append `add_uids` to the initial `uids`
set_fact:
combined: "{{ data + new_data }}"
# The `combined` will look like:
#
# [
# {
# "type": "host",
# "uid": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
# },
# {
# "type": "host",
# "uid": "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
# },
# {
# "type": "host",
# "uid": "cccccccc-cccc-cccc-cccc-cccccccccccc"
# },
# {
# "type": "host",
# "uid": "dddddddd-dddd-dddd-dddd-dddddddddddd"
# }
# ]
- name: 6.0 | Patch hosts with uids
uri:
url: "https://{{ cloud_redhat }}/compliance/v1/profiles/{{ profile_id }}"
method: 'PATCH'
user: "{{ insight_username }}"
password: "{{ insight_password }}"
force_basic_auth: true
validate_certs: 'no'
status_code: "200"
return_content: 'yes'
body_format: 'json'
body: "{\"data\":{\"relationships\": {\"hosts\": {\"data\": {{ combined }} }}}}"
environment:
http_proxy: http://proxy:80
https_proxy: http://proxy:80
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment