0

The command:

create_subnet=$(aws ec2 create-subnet --vpc-id "$create_vpc" --cidr-block 10.0.1.0/24 | jq -r '.subnet[].subnetid')

The output:

"subnet": {
"availabilityzone": "us-west-1b",
"availabilityzoneid": "usw1-az3",
"availableipaddresscount": 251,
"cidrblock": "10.0.1.0/24",
"defaultforaz": false,
"mappubliciponlaunch": false,
"state": "available",
"subnetid": "subnet-0745e1611cf09a69a",
"vpcid": "vpc-07c1508663040cbf7",
"ownerid": "232856593288",
"assignipv6addressoncreation": false,
"ipv6cidrblockassociationset": [],
"subnetarn": "arn:aws:ec2:us-west-1:232856593288:subnet/subnet-0745e1611cf09a69a",
"enabledns64": false,
"ipv6native": false,
"privatednsnameoptionsonlaunch": {
  "hostnametype": "ip-name",
  "enableresourcenamednsarecord": false,
  "enableresourcenamednsaaaarecord": false
}

} }

I need to take the line which is: subnet-0745e1611cf09a69a and store it into the variable create_subnet

When i execute the script with bash -x i get the follow error:

++ jq -r '.subnet[].subnetid'
++ aws ec2 create-subnet --vpc-id vpc-09399bbc31c98efe7 --cidr-block 10.0.1.0/24
jq: error (at <stdin>:24): Cannot iterate over null (null)

Maybe i writed the syntax wrong or something like that? I mean for this - jq -r '.subnet[].subnetid'

Gerald Schneider
  • 26,582
  • 8
  • 65
  • 97
rikorey
  • 15

2 Answers2

0

.subnet is not an array, so the [] is not necessary.

jq -r '.subnet.subnetid'

This works for me.

Gerald Schneider
  • 26,582
  • 8
  • 65
  • 97
0

I think you have missed a { in the first line as your json is not valid without it. It should be something like

{ "subnet": { "availabilityzone": "us-west-1b", "availabilityzoneid": "usw1-az3", "availableipaddresscount": 251, "cidrblock": "10.0.1.0/24", "defaultforaz": false, "mappubliciponlaunch": false, "state": "available", "subnetid": "subnet-0745e1611cf09a69a", "vpcid": "vpc-07c1508663040cbf7", "ownerid": "232856593288", "assignipv6addressoncreation": false, "ipv6cidrblockassociationset": [], "subnetarn": "arn:aws:ec2:us-west-1:232856593288:subnet/subnet-0745e1611cf09a69a", "enabledns64": false, "ipv6native": false, "privatednsnameoptionsonlaunch": { "hostnametype": "ip-name", "enableresourcenamednsarecord": false, "enableresourcenamednsaaaarecord": false } } }

and use jq -r '.subnet.subnetid' to filter your subnet id