gpt4 book ai didi

aws-cloudformation - 如何在具有标签和特殊字符值的对象的字段上选择包含?

转载 作者:行者123 更新时间:2023-12-03 07:39:22 29 4
gpt4 key购买 nike

我需要将 ManagedPolicyArns 添加到许多 cloudformation.yaml 文件中的许多 IAM 角色。有些已经添加了此策略,因此我需要仅选择那些没有添加的策略。我正在使用 yq ( https://github.com/mikefarah/yq/ ) 版本 4.27.3,非常棒。

命令:

yq --from-file add_policy.yq cloudformation.yaml

cloudformation.yaml:

AWSTemplateFormatVersion: "2010-09-09"
Parameters:
MyPrefix:
Description: MyPrefix
Type: String
Resources:
MyRole:
Type: AWS::IAM::Role
Properties:
ManagedPolicyArns:
- Fn::ImportValue: !Sub "${MyPrefix}-my-policy-arn"
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- ecs-tasks.amazonaws.com
- lambda.amazonaws.com
Action:
- sts:AssumeRole
- sts:TagSession
Path: /

部分工作是因为它总是添加创建重复项的策略,add_policy.yq:

( .Resources[] |= 
select(
(.Properties.AssumeRolePolicyDocument.Statement[].Principal.Service.[] == "ecs-tasks.amazonaws.com"
or .Properties.AssumeRolePolicyDocument.Statement[].Principal.Service.[] == "lambda.amazonaws.com")
and (.Properties.ManagedPolicyArns | contains([{"Fn::ImportValue": "${MyPrefix}-my-policy-arn"}]) | not ) )
.Properties.ManagedPolicyArns += {"Fn::ImportValue": "${MyPrefix}-my-policy-arn" | . tag = "!Sub" }
)

根本不添加策略并默默失败,add_policy.yq

( .Resources[] |= 
select(
(.Properties.AssumeRolePolicyDocument.Statement[].Principal.Service.[] == "ecs-tasks.amazonaws.com"
or .Properties.AssumeRolePolicyDocument.Statement[].Principal.Service.[] == "lambda.amazonaws.com")
and (.Properties.ManagedPolicyArns[]."Fn::ImportValue" | contains("${MyPrefix}-my-policy-arn" | . tag = "!Sub") | not) )
.Properties.ManagedPolicyArns += {"Fn::ImportValue": "${MyPrefix}-my-policy-arn" | . tag = "!Sub" }
)

我无法从文档中的更简单的示例中看到,如何保持 ManagedPolicyArns 的唯一性,并且如果新条目已存在,则不向其中添加新条目?

最佳答案

感谢问题“https://stackoverflow.com/questions/42097410/how-to-check-for-presence-of-key-in-jq-before-iteating-over-the-values”以及尝试一些不同的查询来查看 .Resources.Properties.ManagedPolicyArns[] 返回的输出(即空值),我弄清楚了。

它正在迭代一个空值列表,这会导致表达式只是中断而不计算。我需要为空或不匹配的项目返回 true,然后所有项目都将被处理,并且表达式将完全评估为 true 或 false。

add_policy.yq:

( .Resources[] |= 
select(
(.Properties.AssumeRolePolicyDocument.Statement[].Principal.Service.[] == "ecs-tasks.amazonaws.com"
or .Properties.AssumeRolePolicyDocument.Statement[].Principal.Service.[] == "lambda.amazonaws.com")
and (
.Properties.ManagedPolicyArns[] == null
or ( .Properties.ManagedPolicyArns[]."Fn::ImportValue" == "${MyPrefix}-my-policy-arn" | not )
)
)
.Properties.ManagedPolicyArns += {"Fn::ImportValue": "${MyPrefix}-my-policy-arn" | . tag = "!Sub" }
)

关于aws-cloudformation - 如何在具有标签和特殊字符值的对象的字段上选择包含?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73551977/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com