7

I am trying to update "image_id" value in a json structure. Using the below command, how do I change ami-d8cf5cab to ami-a4df7gah So far, I have tried this

cat cog.test.tfstate | jq -r '.modules[].resources[] | select(.type == "aws_launch_configuration") | select(.primary.attributes.name_prefix == "pmsadmin-lc-")'

The JSON data is

{
  "type": "aws_launch_configuration",
  "primary": {
    "id": "pmsadmin-lc-v47thk6rcrdgza6dujfzjatmju",
    "attributes": {
      "associate_public_ip_address": "false",
      "ebs_block_device.#": "0",
      "ebs_optimized": "false",
      "enable_monitoring": "true",
      "ephemeral_block_device.#": "0",
      "iam_instance_profile": "cog-test-pmsadmin",
      "id": "pmsadmin-lc-v47thk6rcrdgza6dujfzjatmju",
      "image_id": "ami-d8cf5cab",
      "instance_type": "t2.small",
      "key_name": "cog-test-internal",
      "name": "pmsadmin-lc-v47thk6rcrdgza6dujfzjatmju",
      "name_prefix": "pmsadmin-lc-",
      "root_block_device.#": "0",
      "security_groups.#": "4",
      "security_groups.1893851868": "sg-7ee7bf1a",
      "security_groups.2774384192": "sg-e2e7bf86",
      "security_groups.2825850029": "sg-86e6bee2",
      "security_groups.3095009517": "sg-f4e7bf90",
      "spot_price": "",
      "user_data": "ed03ac6642af8c97562b065c0b37f211b58ad0a2"
    }
  }
}
Victor Yarema
  • 1,018
  • 12
  • 14
Ebrahim Moshaya
  • 519
  • 3
  • 8
  • 19
  • A long list of jq alternatives can also be found here: https://stackoverflow.com/a/49011455/2440 – Sire Oct 08 '21 at 11:26

2 Answers2

17

Use the |= operator to assign to a property:

jq -r '.modules[].resources[] | select(.type == "aws_launch_configuration") | select(.primary.attributes.name_prefix == "pmsadmin-lc-")| .primary.attributes.image_id |= "ami-a4df7gah"
hek2mgl
  • 143,113
  • 25
  • 227
  • 253
-4

The question and the (to date) only answer in my opinion are nowhere near meeting the quality expectations of the stackoverflow.com community and as such should be closed.

That aside, I have to admit they actually get me the solution I was looking for.

Therefore, for everyone in the same situation, here's hek2mgl's response in a form that actually works and is readable without excessive horizontal scrolling:

Assuming the JSON snippet from the question is in cog.test.tfstate:

jq_filter='. | select(.type == "aws_launch_configuration")'
jq_filter+=' | select(.primary.attributes.name_prefix == "pmsadmin-lc-")'
jq_filter+=' | .primary.attributes.image_id |= "ami-a4df7gah"'

jq "${jq_filter}" cog.test.tfstate

The sample data used is not helpful in spotting the actual change, so here's a before / after diff:

diff cog.test.tfstate <(jq "${jq_filter}" cog.test.tfstate)
13c13
<       "image_id": "ami-d8cf5cab",
---
>       "image_id": "ami-a4df7gah",
Community
  • 1
  • 1
ssc
  • 8,999
  • 8
  • 57
  • 89