JSON object argument to bash script

JSON object argument to bash script

Vikash Kumar

2 minute read

JSON object argument to bash script

Recently, I was writing a Terraform deployment. I was supposed to pass a JSON object as input to my bash script. Usually, out-of-bound scipt is used when there is no appropriate provider with terraform. These scripts can be in any scripting language supported by terraform. For me, it was bash script. For more details, please read about Terraform External Data Source.

I wrote a sample bash script for demo purpose. The gist can be found here data_source.sh. With terraform, it is convenient to use external data source which requires to pass argument as JSON object to script (in my case it’s bash script) and returns output in form of JSON object. Other handy tool is ‘jq’, which is very useful to parse JSON object in sh terminal.

To test data_source.sh before using in terraform. I tried passing JSON string to the script in following way:

    $ bash data_source.sh \
    '{"key_pair" : "key.pem", "public_ip": "34.34.211.138"}'

    The script hanged indefinitely,

    O/P:
    + parse_json_input
    ++ jq -r '@sh "KEY_PAIR=\(.key_pair) PUBLIC_IP=\(.public_ip)"'

After trying few things, I figured out the way to input JSON string to bash from stdin.

    $ echo  '{ "key_pair" : "key.pem", "public_ip": "34.34.211.138" }' | \
     bash data_source.sh

    O/P:
    KEY_PAIR: key.pem
    PUBLIC_IP: 34.34.211.138

This way, I was able to test my script before I used it with terraform.

References:

  1. https://www.terraform.io/
  2. https://www.terraform.io/docs/providers/external/data_source.html
comments powered by Disqus