首页 > 解决方案 > 如何仅将私有 IP 分配给 EC2 实例?

问题描述

下面是在公共子网中创建 EC2 实例的 cloudformation 代码,取自这里

"EC2Instance":{ "Type": "AWS::EC2::Instance", "Properties":{ "ImageId": "ami-05958d7635caa4d04", "InstanceType": "t2.micro", "SubnetId": { "Ref": "SubnetId"}, "KeyName": { "Ref": "KeyName"}, "SecurityGroupIds": [ { "Ref": "EC2InstanceSecurityGroup"} ], "IamInstanceProfile": { "Ref" : "EC2InstanceProfile"}, "UserData":{ "Fn::Base64": { "Fn::Join": ["", [ "#!/bin/bash\n", "echo ECS_CLUSTER=", { "Ref": "EcsCluster" }, " >> /etc/ecs/ecs.config\n", "groupadd -g 1000 jenkins\n", "useradd -u 1000 -g jenkins jenkins\n", "mkdir -p /ecs/jenkins_home\n", "chown -R jenkins:jenkins /ecs/jenkins_home\n" ] ] } }, "Tags": [ { "Key": "Name", "Value": { "Fn::Join": ["", [ { "Ref": "AWS::StackName"}, "-instance" ] ]} }] } },

默认情况下,公共 IP 被分配给 EC2 实例:

如何让 EC2 实例只分配私有 IP?

标签: amazon-web-servicesamazon-ec2amazon-cloudformation

解决方案


这很容易。

设置AssociatePublicIpAddressfalse.

"Ec2Instance" : {
  "Type" : "AWS::EC2::Instance",
  "Properties" : {
    "ImageId" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "AMI" ]},
    "KeyName" : { "Ref" : "KeyName" },
    "NetworkInterfaces": [ {
      "AssociatePublicIpAddress": false,
      "DeviceIndex": "0",
      "GroupSet": [{ "Ref" : "myVPCEC2SecurityGroup" }],
      "SubnetId": { "Ref" : "PublicSubnet" }
    } ]
  }
}

参考: https ://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html


推荐阅读