Search code examples
jsonbashjq

Edit JSON property file for use in bash script


I have a .sh script and a .json properties file for use with AWS CLI v2 to create a CF Stack. I have a parameters file in JSON that I need to substitute one value, but all th key/value pairs are the same and I cannot figure out how to get it to pick the right one, the variable MY_ENV in defined in the script and the line below is what I need to pass the edited JSON file into. I believe it will also take it s a full String Blob instead of file if that is easier. I was trying jq with no luck but maybe there's an even easier solution

aws cloudformation create-stack --capabilities CAPABILITY_NAMED_IAM --stack-name $lambda-$env --template-url <url> --output json --parameter $property_file <-- file I am passing in

property_file

[
  {"ParameterKey":"RuleState", "ParameterValue": "DISABLED"},
  {"ParameterKey":"LambdaSchedule", "ParameterValue":"rate(20 minutes)"},
  {"ParameterKey":"EnvironmentParam", "ParameterValue":"$MY_ENV"}, <-- the string I need changed
  {"ParameterKey":"Method", "ParameterValue":"POST"},
  {"ParameterKey":"LambdaName", "ParameterValue":"TestLambda"}
]

Solution

  • If you map over the outer array, select the item where .ParameterKey == "EnvironmentParam", and set .ParameterValue = env.MY_ENV.

    map(select(.ParameterKey == "EnvironmentParam").ParameterValue = env.MY_ENV)
    

    To import the name (not the value of) MY_ENV from the shell, use the --arg flag:

    jq --arg e MY_ENV 'map(select(…).ParameterValue = env[$e])'