Last active
October 27, 2022 04:16
-
-
Save archmangler/6a837011f0c5c562c208bafb2139ca72 to your computer and use it in GitHub Desktop.
Parsing Terraform JSON output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Terraform: Using JSON with JQ to filter and extract output values | |
================================================================= | |
- Sometimes we need clean, elegant extraction of values from the terraform output to pass data to a next stage pipeline. | |
- JSON and JQ make this reliable, simple and fun! | |
``` | |
gmonkey@tfvm:~/Ship/5ncn$ terraform output -json cluster_slave_private_addresses| jq .value | |
[ | |
"192.168.101.6", | |
"192.168.101.7" | |
] | |
gmonkey@tfvm:~/Ship/5ncn$ terraform output -json cluster_slave_private_addresses| jq .value[0] | |
"192.168.101.6" | |
gmonkey@tfvm:~/Ship/5ncn$ | |
gmonkey@tfvm:~/Ship/5ncn$ terraform output -json cluster_slave_private_addresses| jq .value[1] | |
"192.168.101.7" | |
``` | |
- But we'd like to integrate this better, so why not use python: | |
``` | |
#!/usr/bin/env python | |
#filter out inventory data | |
#for the next stage pipeline | |
import json | |
import subprocess | |
import os | |
debug = 0 | |
inventory=[] | |
stuff = subprocess.check_output(['terraform', 'output', '-json','cluster_slave_private_addresses']) | |
if debug ==1: | |
print stuff | |
j = json.loads(stuff) | |
if debug==1: | |
print j['value'] | |
inventory=list(j['value']) | |
for i in inventory: | |
print i | |
``` | |
- Elabourating a little: | |
``` | |
#!/usr/bin/env python | |
#filter out inventory data | |
#for the next stage pipeline | |
import json | |
import subprocess | |
import os | |
debug = 0 | |
inventory=[] | |
def exec_some_random_command(item): | |
cmd = "tower-cli add this to an ansible inventory "+item | |
return cmd | |
stuff = subprocess.check_output(['terraform', 'output', '-json','cluster_slave_private_addresses']) | |
if debug ==1: | |
print stuff | |
j = json.loads(stuff) | |
if debug==1: | |
print j['value'] | |
inventory=list(j['value']) | |
for i in inventory: | |
cmd = exec_some_random_command(i) | |
print cmd | |
``` | |
(https://gist.github.com/6a837011f0c5c562c208bafb2139ca72) | |
(git@github.com:archmangler/5ncn.git) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment