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

如何通过CloudFormation模板将已有S3传递给SSM文档实现文件拷贝

实现S3文件复制到Windows实例的SSM文档方案

要通过CloudFormation创建SSM文档并传递S3相关信息,核心是利用SSM文档的参数化机制,结合CloudFormation的参数传递能力来实现。下面是具体的步骤和模板示例:

1. 定义带参数的SSM文档

在SSM文档中预先定义接收S3信息的参数(桶名、文件路径、实例目标路径),这样调用文档时可以动态传入值,也能在CloudFormation模板中预设默认值。

2. CloudFormation模板完整示例

AWSTemplateFormatVersion: '2010-09-09'
Parameters:
  S3BucketName:
    Type: String
    Default: ssm-test
    Description: 存储待复制文件的S3桶名称
  S3FileKey:
    Type: String
    Description: S3中文件的完整键(例如:installers/setup.msi)
  InstanceTargetPath:
    Type: String
    Default: C:\Temp\
    Description: Windows实例上的文件存放路径

Resources:
  CopyS3FileToWindowsSSMDoc:
    Type: AWS::SSM::Document
    Properties:
      Content:
        schemaVersion: '2.2'
        description: 从指定S3桶复制文件到Windows实例
        parameters:
          S3Bucket:
            type: String
            description: S3存储桶名称
          S3Key:
            type: String
            description: S3文件的键(路径)
          TargetPath:
            type: String
            description: Windows实例上的目标路径
        mainSteps:
          - action: aws:runPowerShellScript
            name: copyS3FileToInstance
            inputs:
              runCommand:
                - |
                  # 检查目标目录是否存在,不存在则创建
                  if (-not (Test-Path -Path "{{TargetPath}}")) {
                      New-Item -ItemType Directory -Path "{{TargetPath}}" | Out-Null
                  }
                  # 使用AWS CLI执行S3文件复制
                  aws s3 cp s3://{{S3Bucket}}/{{S3Key}} "{{TargetPath}}"
      DocumentType: Command
      Name: CopyS3FileToWindows
      Tags:
        - Key: Function
          Value: S3FileCopy

模板说明

  • CloudFormation的Parameters部分允许你在部署栈时灵活指定S3相关信息,也可以直接用默认值
  • SSM文档的parameters节点定义了三个关键参数,PowerShell命令中通过{{参数名}}的语法引用这些参数,调用时会自动替换为传入的值
  • 使用aws:runPowerShellScript类型适配Windows实例,通过AWS CLI完成S3文件复制(实例需预装AWS CLI,或通过SSM Agent自动处理依赖)

3. 传递参数的几种方式

方式一:部署CloudFormation栈时传入

在部署CFN栈的过程中,直接填写S3BucketName、S3FileKey、InstanceTargetPath的值,SSM文档会默认使用这些值作为参数的默认值。

方式二:调用SSM文档时动态传入

创建完SSM文档后,通过Run Command或AWS CLI调用时指定参数:

AWS CLI示例

aws ssm send-command \
  --document-name "CopyS3FileToWindows" \
  --targets "Key=InstanceIds,Values=i-0123456789abcdef0" \
  --parameters "S3Bucket=ssm-test,S3Key=docs/config.ini,TargetPath=C:\AppConfig\" \
  --region cn-north-1

方式三:结合EC2实例自动触发

如果是和EC2实例一起创建,可以通过实例的UserData或SSM State Manager自动触发文档执行,并传递参数。

4. 必要权限配置

  • 确保Windows实例关联的IAM角色包含AmazonSSMManagedInstanceCore策略,以允许实例和SSM服务通信
  • 给实例IAM角色添加s3:GetObject权限,允许访问ssm-test桶中的目标文件,示例权限策略:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": "arn:aws-cn:s3:::ssm-test/*"
    }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 10:17:48