如何将Python脚本导入AWS SSM自动化文档(YAML)
解决方案
核心思路
利用YAML的**块式标量(Block Scalar)**保留Python脚本的换行结构,配合Terraform的indent和trimspace函数严格控制缩进层级,确保生成的SSM文档YAML格式合法。
步骤1:拆分文件结构
保持Python脚本独立(比如命名为my-script.py),同时创建SSM文档的YAML模板文件(比如automation-doc.yaml.tpl),避免直接硬编码。
步骤2:Terraform资源配置
在Terraform中通过templatefile传递处理后的Python脚本,用indent匹配YAML层级,trimspace清理脚本首尾冗余空白:
resource "aws_ssm_document" "automation" { name = "custom-python-automation" document_type = "Automation" content = templatefile("${path.module}/automation-doc.yaml.tpl", { # 按YAML中Script字段的缩进要求,给每行代码加4个空格(可根据实际层级调整) python_script = indent(4, trimspace(file("${path.module}/my-script.py"))) }) }
步骤3:YAML模板编写
在模板中使用|块式标量定义脚本内容,确保Terraform注入的代码能保留完整格式:
schemaVersion: '0.3' description: Execute external Python script via SSM Automation mainSteps: - name: RunCustomScript action: 'aws:executeScript' inputs: Runtime: python3.11 Handler: handler # 使用|保留换行和缩进,Terraform注入的代码会自动对齐层级 Script: | ${python_script}
关键注意事项
- 缩进数值调整:
indent(4, ...)中的数字需匹配YAML里Script:字段所在的层级(比如上面示例中Script:是第4级,所以加4个空格)。 - 脚本格式检查:确保独立的Python脚本没有混合空格和制表符,避免YAML解析报错。
- 验证生成结果:添加Terraform输出查看最终生成的SSM内容,确认格式合法性:
执行output "generated_ssm_content" { value = aws_ssm_document.automation.content sensitive = false }terraform apply后查看输出,检查Python脚本的缩进是否与YAML结构一致。
替代方案(临时调试用)
如果模板方式仍有问题,可直接在Terraform中用heredoc配合file函数,但可读性较差:
resource "aws_ssm_document" "automation" { name = "custom-python-automation" document_type = "Automation" content = <<EOF schemaVersion: '0.3' description: Execute external Python script mainSteps: - name: RunCustomScript action: 'aws:executeScript' inputs: Runtime: python3.11 Handler: handler Script: | ${indent(4, trimspace(file("${path.module}/my-script.py")))} EOF }
内容的提问来源于stack exchange,提问作者Leslie Alldridge
相关产品推荐
相关产品推荐

