You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS SAM模板中引用外部配置文件的变量?

解决AWS SAM模板从config.json引用IAM角色ARN的问题

AWS SAM本身不支持Serverless框架那样直接通过${file(./config.json):IAMROLE}读取外部JSON文件变量的语法,以下是两种可行的实现方案:

方案一:使用SAM参数+参数文件

  1. 修改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
  1. 在config.json中定义对应参数值(也可命名为parameters.json,SAM部署时可直接识别):
{
  "StateMachineRoleArn": "arn:aws:iam::875221978636:role/service-role/StepFunctions-postgres_fact_data_load-role-0f4a24d5"
}
  1. 执行部署命令时加载参数文件:
sam deploy --template-file template.yaml --parameter-overrides file://config.json

方案二:使用部署脚本提取JSON变量

如果要直接读取config.json中指定字段(比如你提到的IAMROLE),可以用jq工具提取后作为参数传递:

  1. 保持方案一中的SAM模板(定义StateMachineRoleArn参数)
  2. 调整config.json结构:
{
  "IAMROLE": "arn:aws:iam::875221978636:role/service-role/StepFunctions-postgres_fact_data_load-role-0f4a24d5"
}
  1. 执行部署命令时通过jq提取值:
sam deploy --template-file template.yaml --parameter-overrides StateMachineRoleArn=$(jq -r '.IAMROLE' config.json)

内容的提问来源于stack exchange,提问作者Dhivakhar Venkatachalam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 14:16:21