如何在Argo Workflows的单个循环中传入多个列表生成IAM策略
Argo Workflows多列表并行遍历循环解决方案
原生支持情况
Argo Workflows 目前没有原生提供多列表按索引配对遍历的循环语法,仅支持withItems、withParams、withSequence三类单数据源循环,你尝试使用的自定义withTogether配置不被官方识别,无法生效。
可行替代方案
方案1:预合并为对象列表(最推荐)
在向Argo传入参数前,先将三个列表按索引配对,合并为单个对象列表,直接作为循环数据源。
你示例中的三个列表合并后格式如下:
[ {"effect": "Allow", "action": "ec2:CreateTags", "resource": "*"}, {"effect": "Allow", "action": "ec2:DescribeInstances", "resource": "*"}, {"effect": "Allow", "action": "ec2:AuthorizeSecurityGroupIngress", "resource": "*"} ]
后续直接使用withParams遍历即可,取值逻辑更清晰,不易出错:
- name: generate-policy withParams: "{{inputs.parameters.merged_policy_items}}" script: image: alpine command: [sh] source: | cat << EOP { "Effect": "{{item.effect}}", "Action": "{{item.action}}", "Resource": "{{item.resource}}" } EOP
方案2:内置表达式动态合并
如果无法提前合并参数,可以使用Argo内置的sprig函数库的zip方法,在配置中动态完成列表配对:
- name: generate-policy withParams: "{{=zip(inputs.parameters.effect, inputs.parameters.action, inputs.parameters.resource)}}" script: image: alpine command: [sh] source: | cat << EOP { "Effect": "{{item[0]}}", "Action": "{{item[1]}}", "Resource": "{{item[2]}}" } EOP
注意:
zip返回的子项是数组格式,索引从0开始计数,需和你传入列表的顺序对应。另外要保证三个列表长度完全一致,zip会自动按最短列表的长度截断结果。
方案3:前置步骤合并列表
如果你使用的Argo版本不支持在表达式中调用zip函数,可以新增一个前置任务专门完成列表合并:
# 前置合并任务 - name: merge-lists inputs: parameters: - name: effect - name: action - name: resource script: image: python:3.10-slim command: [python] source: | import json effect = json.loads('{{inputs.parameters.effect}}') action = json.loads('{{inputs.parameters.action}}') resource = json.loads('{{inputs.parameters.resource}}') merged = [{"effect": e, "action": a, "resource": r} for e,a,r in zip(effect, action, resource)] print(json.dumps(merged)) outputs: parameters: - name: merged_items valueFrom: stdout: {} # 后续策略生成任务 - name: generate-policy dependencies: [merge-lists] withParams: "{{tasks.merge-lists.outputs.parameters.merged_items}}" script: image: alpine command: [sh] source: | cat << EOP { "Effect": "{{item.effect}}", "Action": "{{item.action}}", "Resource": "{{item.resource}}" } EOP
内容的提问来源于stack exchange,提问作者Karamchand
相关产品推荐
相关产品推荐

