命令:
create_subnet=$(aws ec2 create-subnet --vpc-id "$create_vpc" --cidr-block 10.0.1.0/24 | jq -r '.subnet[].subnetid')
输出:
"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
}
}
}
我需要采取以下行:subnet-0745e1611cf09a69a并将其存储到变量中创建子网
当我使用 bash -xi 执行脚本时出现以下错误:
++ 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)
也许我写的语法错误或者类似的东西?我的意思是 -jq -r'.子网[].子网id'
答案1
.subnet
不是数组,因此[]
没有必要。
jq -r '.subnet.subnetid'
这对我有用。
答案2
我认为你在第一行漏掉了一个 {,因为如果没有它,你的 json 就无效。它应该是这样的
{ “子网”:{ “availabilityzone”:“us-west-1b”, “availabilityzoneid”:“usw1-az3”, “availableipaddresscount”:251, “cidrblock”:“10.0.1.0/24”, “defaultforaz”:false, “mappubliciponlaunch”:false, “状态”:“可用”, “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} } }
并使用 jq -r '.subnet.subnetid' 来过滤你的子网 ID