如何在 CloudFormation 模板中将数据从 AWS S3 复制到 EC2?

Dor*_*bre 2 amazon-s3 amazon-ec2 amazon-web-services aws-cloudformation

我创建了一个 CloudFormation 模板来启动 AutoScaling 组。在启动期间,允许s3:GetObject访问的策略附加到每个 EC2 实例。之后,我使用 User Data 安装 Apache Web 服务器和 PHP,然后更改相关文件夹的设置。然后,我需要在每个实例中将多个文件从 S3 存储桶(没有公共访问权限)复制到 /var/www/html 文件夹,但是如果不恢复到手动复制或同步CloudFormation 堆栈完成后使用 CLI 生成文件 - 这必须是一个完全自动化的过程。

模板中的用户数据如下:

"UserData": {
    "Fn::Base64": {
        "Fn::Join": [
            "\n",
            [
                "#!/bin/bash",
                "yum update -y",
                "yum install -y httpd24 php56",
                "service httpd start",
                "chkconfig httpd on",
                "groupadd DMO",
                "usermod -a -G DMO ec2-user",
                "chgrp -R DMO /var/www",
                "chmod 2775 /var/www",
                "find /var/www -type d -exec chmod 2775 {} +",
                "find /var/www -type f -exec chmod 0664 {} +"
            ]
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

为了坚持您已经在做的事情,您可以从您的用户数据脚本中运行 AWS CLI:

"UserData": {
    "Fn::Base64": {
        "Fn::Join": [
            "\n",
            [
                "#!/bin/bash",
                "yum update -y",
                "yum install -y httpd24 php56",
                "service httpd start",
                "chkconfig httpd on",
                "groupadd DMO",
                "usermod -a -G DMO ec2-user",
                "chgrp -R DMO /var/www",
                "chmod 2775 /var/www",
                "aws s3 cp s3://MYBUCKET/MYFILE.zip /tmp",
                "unzip -d /var/www /tmp/MYFILE.zip",
                "rm /tmp/MYFILE.zip",
                "find /var/www -type d -exec chmod 2775 {} +",
                "find /var/www -type f -exec chmod 0664 {} +"
            ]
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

为此,您的 EC2 实例配置文件必须授予从 S3 读取文件的权限。

另一种方法是使用AWS::CloudFormation::Init:它是一个预定义的元数据密钥,您可以将其附加到EC2::InstanceAutoScaling::LaunchConfiguration资源,它允许您配置包、服务和单个文件(包括从 S3 检索和解压缩文件) .

有一个教程在这里