How to specify VPC and subnet in AWS CloudFormation template
If you want to continue using default VPC you deleted you will have to contact AWS support to create it again. AWS resources from the template you are using depnd on it.
Otherwise you have to customize it a bit so it can be used with your non-default VPCs. There are suggested changes:
0) Pass your VPC ID and your subnet IDs as CloudFormation parameters:
"myVPC": {
"Description" : "Id of my VPC",
"Type" : "String",
"Default" : "vpc-XXXXXXXX"
},
"MySubnet": {
"Description" : "My subnet from my VPC",
"Type": "String",
"Default": "subnet-YYYYYYYY"
},
"RDSSubnets": {
"Description" : "RDS subnets from my VPC",
"Type": "CommaDelimitedList",
"Default": "subnet-YYYYYYY1,subnet-YYYYYY2"
},
1) Security groups have to be created within your new VPC identified by VPC ID:
"DBSecurityGroup": {
"Type": "AWS::RDS::DBSecurityGroup",
"Properties": {
===>>> "EC2VpcId" : { "Ref" : "myVPC" }, <<<====
"DBSecurityGroupIngress": { "EC2SecurityGroupName": { "Ref": "WebServerSecurityGroup"} },
"GroupDescription" : "Frontend Access"
}
},
"WebServerSecurityGroup" : {
"Type" : "AWS::EC2::SecurityGroup",
"Properties" : {
===>>> "VpcId" : {"Ref" : "myVPC"}, <<<====
"GroupDescription" : "Enable HTTP access via port 80 and SSH access",
"SecurityGroupIngress" : [
{"IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "CidrIp" : "0.0.0.0/0"},
{"IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "CidrIp" : { "Ref" : "SSHLocation"}}
]
}
}
2) change your EC2 instance to use your VPC subnet1:
"WebServer": {
"Type": "AWS::EC2::Instance",
...
"Properties": {
"SubnetId": { "Ref": "MySubnet1" },
...
3) Create RDS DB subnet group with your VPC subnets dedicated for RDS (you need to create a subnet in the VPC in at least two of the Availability Zones of the region where the VPC exists):
"MyDBSubnetGroup" : {
"Type" : "AWS::RDS::DBSubnetGroup",
"Properties" : {
"DBSubnetGroupDescription" : "Subnets available for the RDS DB Instance",
"SubnetIds" : { "Ref" : "RDSSubnets" },
}
},
4) change your RDS instance to use your VPC subnet and security group (replace DBSecurityGroups
parameter with VPCSecurityGroups
):
"DBInstance" : {
"Type": "AWS::RDS::DBInstance",
"Properties": {
"DBSubnetGroupName" : { "Ref" : "MyDBSubnetGroup" },
"VPCSecurityGroups" : [ { "Ref" : "DBSecurityGroup" } ],
...
You can find more details about used parameters in AWS documentation:
- http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-ec2.html
- http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-rds.html
- http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html
- http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html
- http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html
- http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbsubnet-group.html