Json
JQ - 將元素添加到數組並返回完整的 json
我正在嘗試將一個元素添加到這樣的數組中:
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?
.Statement
使用包含先前條目且目標對像已更新的新數組重新分配數組:jq --arg root "arn:aws:iam::$ACCOUNT_ID:root" \ '.Statement |= map(select(.Sid=="Allow use of the key").Principal.AWS |= . + [$root])' <<<$policy