Created
April 23, 2020 18:13
-
-
Save dontlaugh/e2f7340f8930693f18313fa2a99c146c to your computer and use it in GitHub Desktop.
JQ reshape json
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
#!/bin/bash | |
# Requires gcloud and jq to be installed | |
# Get instance name and zone, required for our gcloud query | |
INSTANCE_NAME=$(curl --silent "http://metadata.google.internal/computeMetadata/v1/instance/name" -H "Metadata-Flavor: Google") | |
ZONE=$(curl --silent "http://metadata.google.internal/computeMetadata/v1/instance/zone" -H "Metadata-Flavor: Google") | |
# Get a giant blob of json with our instance's metadata | |
METADATA=$(gcloud compute instances describe $INSTANCE_NAME --zone $ZONE --format json) | |
# Extract our environment name. There is only ever one of these, per instance. | |
ENVIRONMENT=$(echo $METADATA | jq -r '.labels.environment') | |
# Extract our roles. These are "labels" keys with an empty string value. | |
# Also build and echo our result json object: | |
# 1. transform our roles into an array for the "roles" key | |
# 2. add in our $ENVIRONMENT value as the "environment" key | |
# JSON from the .labels field that looks like this (for example) | |
# | |
# "labels": { | |
# "elasticsearch": "", | |
# "environment": "deploy_test", | |
# "postgres": "", | |
# "rabbitmq": "", | |
# "redis": "" | |
# } | |
# | |
# ... will be reshaped into our desired output that looks like this | |
# | |
# { | |
# "roles": [ | |
# "elasticsearch", | |
# "postgres", | |
# "rabbitmq", | |
# "redis" | |
# ], | |
# "environment": "deploy_test" | |
# } | |
# | |
# This is the structure our bolt plans expect. | |
echo $METADATA | jq --arg env $ENVIRONMENT '.labels | with_entries(select(.value == "")) | {roles: [keys[]], environment: $env }' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment