Skip to content

Instantly share code, notes, and snippets.

@robinbowes
Created January 11, 2019 20:21
Show Gist options
  • Save robinbowes/c01275094747650033f6ddbe235be4ed to your computer and use it in GitHub Desktop.
Save robinbowes/c01275094747650033f6ddbe235be4ed to your computer and use it in GitHub Desktop.
Given input.json, I'd like to extract all the variable names and any default values
{
"variable": {
"cloud": {
"description": "The cloud for this service"
},
"cluster": {
"default": "default",
"description": "The cluster name to use for this service"
},
"cost_center": {
"default": "unknown",
"description": "Used to set Cost Center tag, for accounting purposes"
},
"owner": {
"default": "unknown",
"description": "Used to set Owner tag, for accounting purposes"
},
"region": {
"description": "The region for this service"
},
"service": {
"default": "netbox",
"description": "The service name"
},
"site": {
"description": "The site for this service"
},
"ssm_region": {
"description": "The region to use for the SSM parameter store"
},
"stage": {
"description": "The stage for this service"
}
}
}
{
"cloud": "",
"cluster": "default",
"cost_center": "unknown",
"owner": "unknown",
"region": "",
"service": "netbox",
"site": "",
"ssm_region": "",
"stage": ""
}
@robinbowes
Copy link
Author

robinbowes commented Jan 14, 2019

Actually, the input file is terraform code. I first converted to JSON using hcltool.

This is variables.tf:

variable "cloud" {
  description = "The cloud for this service"
}

variable "cluster" {
  default     = "default"
  description = "The cluster name to use for this service"
}

variable "cost_center" {
  default     = "unknown"
  description = "Used to set Cost Center tag, for accounting purposes"
}

variable "owner" {
  default     = "unknown"
  description = "Used to set Owner tag, for accounting purposes"
}

variable "region" {
  description = "The region for this service"
}

variable "service" {
  default     = "netbox"
  description = "The service name"
}

variable "site" {
  description = "The site for this service"
}

variable "ssm_region" {
  description = "The region to use for the SSM parameter store"
}

variable "stage" {
  description = "The stage for this service"
}

This is how I converted it:

jq '.variable | with_entries(.value |= if .default then .default else "" end)' < <(hcltool variables.tf)

Output:

{
  "cloud": "",
  "cluster": "default",
  "cost_center": "unknown",
  "owner": "unknown",
  "region": "",
  "service": "netbox",
  "site": "",
  "ssm_region": "",
  "stage": ""
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment