如何使用 CloudFormation 在现有 EC2 实例上启动容器?

How do I start a container on an existing EC2 instance using CloudFormation?

场景如下:我有 3 个 EC2 实例(A、B 和 C),所有实例都 运行使用 ECS 优化的 AMI。我想编写一个带有任务定义的 CloudFormation 模板,只允许任务 运行 在 A 上。我该怎么做?

我见过的所有 CloudFormation 示例都需要创建一个新的 EC2 实例,这不是我想要的。

将任务固定到主机的唯一方法是使用 start-task 通过 AWS CLI 执行此操作:http://docs.aws.amazon.com/cli/latest/reference/ecs/start-task.html

至于 运行 通过 Cloudformation 的 ECS 任务,在 CFT 模板范围内创建 启动它的唯一方法是创建服务.这是一个未经测试的 CFT 模板:

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Curator runner",
    "Parameters": {
        "CpuUnits": {
            "Type": "Number",
            "Default": 0,
            "Description": "The number of CPU Units to allocate."
        },
        "Memory": {
            "Type": "Number",
            "Default": 256,
            "Description": "The amount of Memory (MB) to allocate."
        },
        "ClusterName": {
            "Type": "String",
            "Description": "The cluster to run the ecs tasks on."
        },
        "DockerImageUrl": {
            "Type": "String",
            "Description": "The URL for the docker image. Example: 354500939573.dkr.ecr.us-east-1.amazonaws.com/something:latest"
        }
    },
    "Resources": {
        "SomeTask": {
            "Type": "AWS::ECS::TaskDefinition",
            "Properties": {
                "ContainerDefinitions": [{
                    "Memory": {
                        "Ref": "Memory"
                    },
                    "Name": "something",
                    "Image": {
                        "Ref": "DockerImageUrl"
                    },
                    "Cpu": {
                        "Ref": "CpuUnits"
                    }
                }],
                "Volumes": []
            }
        },
        "service": {
            "Type": "AWS::ECS::Service",
            "Properties": {
                "Cluster": {
                    "Ref": "ClusterName"
                },
                "DesiredCount": "1",
                "TaskDefinition": {
                    "Ref": "SomeTask"
                }
            }
        }
    }
}