Reputation: 1370
I'm trying to launch instance using cfn template.The instance needs to be launched on a specific existing subnet and also in a security group created in template.
I have the following parameter to get list with subnets:
"Subnet": {
"Description": "Subnet to put Instance",
"Type": "AWS::EC2::Subnet::Id",
},
I have the following reosurce to create security group:
"InstanceSecurityGroup": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupDescription": "Enables access to instance by port 80",
"SecurityGroupIngress": [
{
"IpProtocol": "tcp",
"FromPort": "80",
"ToPort": "80",
"CidrIp": {
"Ref": "ClientCIDR"
}
}
]
},
And I have the following resource to create instance:
"WebServer": {
"Type": "AWS::EC2::Instance",
"Properties": {
"IamInstanceProfile": "access-profile",
"SecurityGroupIds": [
{ "Fn::GetAtt": [
"InstanceSecurityGroup",
"GroupId"
]
}
],
"SubnetId": {
"Ref": "Subnet"
},
When i'm trying to create instance and choose existing subnet a got the following error:
Security group sg-**** and subnet subnet-**** belong to different networks.
Please help to solve this issue..
Upvotes: 1
Views: 4600
Reputation: 1039
The AWS::EC2::Subnet your are adding to the AWS::EC2::Instance is in a different AWS::EC2::VPC to the AWS::EC2::SecurityGroup.
When creating your InstanceSecurityGroup
Resource you should use the AWS::EC2::SecurityGroup VpcId
property to create the AWS::EC2::SecurityGroup in a particular AWS::EC2::VPC. The documentation for this property states
VpcId
The physical ID of the VPC. Can be obtained by using a reference to an AWS::EC2::VPC, such as: { "Ref" : "myVPC" }.
For more information about using the Ref function, see Ref.
Required: Yes, for VPC security groups
Your account uses EC2-VPC, you can only omit the VpcId
parameter if you are using ec2-classic, here are the differences between ec2-classic and ec2-vpc.
Cloud Formation Templates can accept the AWS Specific Parameter Type AWS::EC2::VPC::Id
eg
"VPCId": {
"Type": "AWS::EC2::VPC::Id"
"Description": "The VPC Id to where this instance is being created"
}
and this Parameter can then use the intrinsic Ref function to reference the VPCId
Parameter in the AWS::EC2::SecurityGroup
"InstanceSecurityGroup": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupDescription": "Enables access to instance by port 80",
"VPCId": {
"Ref": "VPCId"
},
"SecurityGroupIngress": [
{
"IpProtocol": "tcp",
"FromPort": "80",
"ToPort": "80",
"CidrIp": {
"Ref": "ClientCIDR"
}
}
]
}
}
Upvotes: 3