如何在AWS SAM模板中引用外部配置文件的变量?
解决AWS SAM模板从config.json引用IAM角色ARN的问题
AWS SAM本身不支持Serverless框架那样直接通过${file(./config.json):IAMROLE}读取外部JSON文件变量的语法,以下是两种可行的实现方案:
方案一:使用SAM参数+参数文件
- 修改SAM模板,将硬编码的Role替换为参数引用:
Parameters: StateMachineRoleArn: Type: String Description: IAM角色ARN,用于Step Functions状态机 Resources: OcxDataLoadMachine: Type: AWS::Serverless::StateMachine Properties: Name: ocx_data_load_scripts_machine DefinitionUri: ./stepfunctions/ocx_data_load_scripts_machine.asl.json Role: !Ref StateMachineRoleArn
- 在
config.json中定义对应参数值(也可命名为parameters.json,SAM部署时可直接识别):
{ "StateMachineRoleArn": "arn:aws:iam::875221978636:role/service-role/StepFunctions-postgres_fact_data_load-role-0f4a24d5" }
- 执行部署命令时加载参数文件:
sam deploy --template-file template.yaml --parameter-overrides file://config.json
方案二:使用部署脚本提取JSON变量
如果要直接读取config.json中指定字段(比如你提到的IAMROLE),可以用jq工具提取后作为参数传递:
- 保持方案一中的SAM模板(定义
StateMachineRoleArn参数) - 调整
config.json结构:
{ "IAMROLE": "arn:aws:iam::875221978636:role/service-role/StepFunctions-postgres_fact_data_load-role-0f4a24d5" }
- 执行部署命令时通过
jq提取值:
sam deploy --template-file template.yaml --parameter-overrides StateMachineRoleArn=$(jq -r '.IAMROLE' config.json)
内容的提问来源于stack exchange,提问作者Dhivakhar Venkatachalam
相关产品推荐
相关产品推荐

