Search code examples
jsonamazon-web-servicesenvironment-variablesjqamazon-ecs

How to permanently add data to json file using jq command


Below is my taskdef.json file

{
    "containerDefinitions": [
        {
            "name": "container_name",
            "image": "",
            "essential": true,
            "logConfiguration": {
                "logDriver": "awslogs",
                "options": {
                    "awslogs-group": "/ecs/taskdef",
                    "awslogs-region": "us-east-2",
                    "awslogs-stream-prefix": "ecs"
                }
            }
         }
     ]
  }

I'm using an environment variable to append to this file

export IMAGE=########.dkr.ecr.us-west-1.amazonaws.com/container-repo:latest

I've ran the following command to input the image under containerDefinitions and the output shows it in there but it does not get appended permanently to the taskdef.json file.

jq ".containerDefinitions[].image=\"$IMAGE\"" taskdef.json

I've also tried the following command to add the output to a new file but I have multiple json data injections so this way doesn't work.

jq ".containerDefinitions[].image=\"$IMAGE\"" taskdef.json > taskdef2.json

Is there anyway to inject an input permanently into the json file using the jq command which would be equivalent to sed -i?


Solution

  • jq does not have a command-line option like sed's -i. One way to avoid having to fiddle with a temporary file is to use sponge (part of the moreutils collection) if it is available in your computing environment:

    jq .... taskdef.json | sponge taskdef.json
    

    (Homebrew users can install sponge via: brew install sponge)

    For a PowerShell alternative to sponge, see Powershell equivalent to sponge in moreutils?