如何使用Terraform的aws_ssm_document在目标VM运行PowerShell脚本
Terraform实现SSM下发PowerShell脚本可运行配置
前置校验要求
- 目标Windows EC2实例已正常运行SSM Agent
- 实例关联的IAM角色已附加
AmazonSSMManagedInstanceCore托管策略,具备SSM命令接收、执行、日志回传权限 - 项目目录下已存放待执行的PowerShell脚本,示例路径为
./scripts/install_iis.ps1
两种可落地实现方案
方案1:直接复用AWS官方预配置文档(无需自定义SSM文档)
该方案不需要调用aws_ssm_document资源,直接将本地PowerShell脚本内容通过参数传入官方现成的AWS-RunPowerShellScript文档,配置如下:
# SSM关联:直接绑定官方PowerShell执行文档 resource "aws_ssm_association" "run_official_powershell" { # 直接引用平台上预置的官方文档名称 name = "AWS-RunPowerShellScript" # 绑定目标实例,支持按标签、实例ID等维度圈定目标 targets { key = "InstanceIds" # 替换为实际的目标Windows实例ID列表 values = [aws_instance.windows_target_instance.id] } parameters = { # 读取本地PowerShell脚本,按行拆分后序列化为SSM要求的StringList格式 commands = jsonencode(split("\n", file("${path.module}/scripts/install_iis.ps1"))) # 指定实例上的执行工作目录 workingDirectory = "C:\\Windows\\Temp" # 指定执行超时时间,单位秒 executionTimeout = "3600" } # 可选:配置触发规则,比如实例上线后执行、定时重复执行 # schedule_expression = "rate(1 hour)" }
方案2:创建符合官方规范的自定义SSM文档
适合需要封装固定执行逻辑、跨项目复用的场景,通过aws_ssm_document资源创建完全对齐AWS-RunPowerShellScript参数规范的自定义文档,同时结合file函数内置默认脚本内容,配置如下:
# 自定义SSM文档:严格遵循官方Schema 1.2规范 resource "aws_ssm_document" "custom_powershell_runner" { name = "Custom-Windows-IIS-Install-Runner" document_type = "Command" document_format = "JSON" # 文档结构完全匹配官方AWS-RunPowerShellScript的参数定义 content = jsonencode({ schemaVersion = "1.2" description = "自定义执行Windows IIS安装脚本的SSM命令文档" parameters = { commands = { type = "StringList" description = "待执行的PowerShell命令列表" # 内置默认脚本,读取本地PowerShell文件内容作为默认执行命令 default = split("\n", file("${path.module}/scripts/install_iis.ps1")) } workingDirectory = { type = "String" description = "实例上的命令执行工作目录" default = "C:\\Windows\\Temp" } executionTimeout = { type = "String" description = "命令执行超时阈值,单位秒" default = "3600" } } # 配置文档执行步骤,调用SSM原生PowerShell执行插件 mainSteps = [ { action = "aws:runPowerShellScript" name = "executePowerShell" inputs = { commands = "{{commands}}" workingDirectory = "{{workingDirectory}}" executionTimeout = "{{executionTimeout}}" } } ] }) tags = { Scenario = "CustomScriptDeployment" } } # SSM关联:将自定义文档绑定到目标实例 resource "aws_ssm_association" "run_custom_powershell" { name = aws_ssm_document.custom_powershell_runner.name targets { key = "InstanceIds" values = [aws_instance.windows_target_instance.id] } # 可选:按需覆盖自定义文档的默认参数 parameters = { executionTimeout = "7200" } }
配置注意事项
- 文档中
aws:runPowerShellScript是SSM官方插件的固定动作标识,必须与官方文档的插件调用逻辑保持一致,不可随意修改 - 本地PowerShell脚本路径需相对于Terraform的执行工作目录配置,避免路径解析失败
- SSM命令下发基于SSM Agent主动拉取机制,目标实例安全组无需额外开放入站端口
- 若目标实例处于离线状态,关联任务会在实例上线完成SSM Agent注册后自动触发执行
内容的提问来源于stack exchange,提问作者jlo-gmail
相关产品推荐
相关产品推荐

