如何使用 CloudFormation 脚本将文件上传到 S3 存储桶?

Ayu*_*arg 9 amazon-web-services amazon-cloudformation

如何将文件上传到我的 AWS S3 存储桶 CloudFormation 模板?

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  S3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: PublicRead
      BucketName: s3bucketuser
      VersioningConfiguration:
        Status: Enabled
Run Code Online (Sandbox Code Playgroud)

Ala*_*vey 13

AWS 提供了一个示例,可能会有所帮助,具体取决于您的用例:https : //github.com/awslabs/aws-cloudformation-templates/tree/a11722d/aws/services/CloudFormation/MacrosExamples/S3Objects

  1. 使用macro.template创建一个单独的CloudFormation堆栈。这将创建变换宏“S3Objects”,然后可用于该区域中的任何其他堆栈。该README.md解释了如何“包装”加入CloudFormation之前的宏模块(它需要包括lambda函数单独的源文件)。
  2. 文件example.template提供了示例用法。请注意引用的顶级Transform部分S3Objects,它允许使用Type: AWS::S3::Object.

在提供的示例中,该Body属性允许直接在 YAML 或 JSON 模板中输入文本。为了扩展这一点,可以使用Fn::Sub创建一个文件,其中包含来自其他资源的参数或属性:

---
AWSTemplateFormatVersion: '2010-09-09'

Transform: S3Objects

Parameters:
  ANameField:
    Type: String

Resources:
  S3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: PublicRead
      BucketName: s3bucketuser
      VersioningConfiguration:
        Status: Enabled

  S3Object:
    Type: AWS::S3::Object
    Properties:
      Target:
        Bucket: !Ref S3Bucket
        Key: README.md
        ContentType: text/markdown
      Body: !Sub |
        # My text file

        This is my text file for ${ANameField}.
        The region is ${AWS::Region} and my account ID is ${AWS::AccountId}.
        This file is in the ${S3Bucket} bucket. The bucket ARN is ${S3Bucket.Arn},
        and its website endpoint is ${S3Bucket.WebsiteURL}
Run Code Online (Sandbox Code Playgroud)


MLu*_*MLu 5

您无法通过 CloudFormation 上传文件,这是不受支持的,因为 CFN 无权访问您的本地文件系统。

我通常做什么:

  • cloudformationAnsible调用任务
  • CFN 创建存储桶并在Outputs导出存储桶名称
  • s3_sync一旦 CFN 完成,Ansible 就会上传在下一个任务中使用的文件。

希望有帮助:)

  • 查看其他答案,完全可行。还可以在模板内定义一个 Lambda 函数,该函数可以执行并执行您想要的任何操作。无论如何使用自定义资源。另请参阅 https://aws.amazon.com/premiumsupport/knowledge-center/cloudformation-s3-custom-resources/ (2认同)