如何自动将EC2实例添加到现有安全组,弹性IP和VPC?

时间:2016-11-29 15:11:15

标签: cloud amazon-cloudformation

我为我的图片(AMI)中的新实例创建了新模板(*.json- see ettach)

如何将实例自动添加到现有的安全组,弹性IP和VPC

由于

{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Ec2 block device mapping",
"Resources": {
    "MyEC2Instance": {
        "Type": "AWS::EC2::Instance",
        "Properties": {
            "ImageId": "ami-1ff5111",
            "AvailabilityZone": "us-west-1a",
            "KeyName": "Test",
            "Tags": [{
                "Key": "Name",
                "Value": "RoiTest"
            }]
        }
    },

1 个答案:

答案 0 :(得分:1)

Resource Types Reference section CloudFormation User Guide是一个很好的起点,可以搜索您要询问的详细信息。具体来说,您应该查看AWS:EC2:InstanceAWS::EC2::EIPAssociation引用。

要将EC2实例与VPC安全组关联,请添加SecurityGroupIds属性。要在VPC内创建实例,您实际上必须定义其子网(后者又与VPC相关联),因此您添加了SubnetId属性。最后,将弹性IP与您创建EIP关联资源的实例相关联。

这就是您的模板的样子:

{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "Ec2 block device mapping",
  "Resources": {
    "MyEC2Instance": {
      "Type": "AWS::EC2::Instance",
      "Properties": {
        "ImageId": "ami-1ff5111",
        "AvailabilityZone": "us-west-1a",
        "SubnetId": "<your existing subnet id here>",
        "SecurityGroupIds": [ "<your existing security group id here>" ],
        "KeyName": "Test",
        "Tags": [{
          "Key": "Name",
            "Value": "RoiTest"
        }]
      }
    },
    "MyEIPAssociation": {
      "Type": "AWS::EC2::EIPAssociation",
      "Properties": {
        "AllocationId": "<your existing elastic IP allocation id here>",
        "InstanceId": { "Ref": "MyEC2Instance" }
      }
    },
    ... (other resources in your template)
  }
}

指出SecurityGroupIds属性值是一个数组可能很有用,因此您可以拥有一个包含多个安全组的实例。