![JQ - 将元素添加到数组并返回完整的 json](https://linux22.com/image/165832/JQ%20-%20%E5%B0%86%E5%85%83%E7%B4%A0%E6%B7%BB%E5%8A%A0%E5%88%B0%E6%95%B0%E7%BB%84%E5%B9%B6%E8%BF%94%E5%9B%9E%E5%AE%8C%E6%95%B4%E7%9A%84%20json.png)
我正在尝试向数组中添加一个元素,如下所示:
jq --arg root "arn:aws:iam::$ACCOUNT_ID:root" \
'.Statement[] | select(.Sid=="Allow use of the key") \
| .Principal.AWS |= . + [$root]' \
<<<$policy
虽然这有效,但它只输出特定部分,因为我正在执行select
.
内容$policy
:
{
"Version": "2012-10-17",
"Id": "key-consolepolicy-3",
"Statement": [
{
"Sid": "Enable IAM User Permissions",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::*:root"
},
"Action": "kms:*",
"Resource": "*"
},
{
"Sid": "Allow access for Key Administrators",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::*:user/*"
},
"Action": [
"kms:Create*",
"kms:Describe*",
"kms:Enable*",
"kms:List*",
"kms:Put*",
"kms:Update*",
"kms:Revoke*",
"kms:Disable*",
"kms:Get*",
"kms:Delete*",
"kms:TagResource",
"kms:UntagResource"
],
"Resource": "*"
},
{
"Sid": "Allow use of the key",
"Effect": "Allow",
"Principal": {
"AWS": [
"arn:aws:iam::*:root"
]
},
"Action": [
"kms:Encrypt",
"kms:Decrypt",
"kms:DescribeKey",
"kms:ReEncrypt*",
"kms:GenerateDataKey*",
"kms:CreateGrant"
],
"Resource": "*"
}
]
}
预期结果:
{
"Version": "2012-10-17",
"Id": "key-consolepolicy-3",
"Statement": [
{
"Sid": "Enable IAM User Permissions",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::*:root"
},
"Action": "kms:*",
"Resource": "*"
},
{
"Sid": "Allow access for Key Administrators",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::*:user/*"
},
"Action": [
"kms:Create*",
"kms:Describe*",
"kms:Enable*",
"kms:List*",
"kms:Put*",
"kms:Update*",
"kms:Revoke*",
"kms:Disable*",
"kms:Get*",
"kms:Delete*",
"kms:TagResource",
"kms:UntagResource"
],
"Resource": "*"
},
{
"Sid": "Allow use of the key",
"Effect": "Allow",
"Principal": {
"AWS": [
"arn:aws:iam::*:root",
"arn:aws:iam::$root:root" <-------------
]
},
"Action": [
"kms:Encrypt",
"kms:Decrypt",
"kms:DescribeKey",
"kms:ReEncrypt*",
"kms:GenerateDataKey*",
"kms:CreateGrant"
],
"Resource": "*"
}
]
}
如何取回添加元素的初始 json?
答案1
.Statement
使用包含先前条目并更新了目标对象的新数组重新分配数组:
jq --arg root "arn:aws:iam::$ACCOUNT_ID:root" \
'.Statement |= map(select(.Sid=="Allow use of the key").Principal.AWS |= . + [$root])' <<<$policy