How to manage VPC association to Route53 hosted zone using CloudFormation

amazon-route53amazon-vpcamazon-web-services

I wrote a CloudFormation template which creates a vpc, subnets, routes, asg's and instances.

I want CloudFormation to handle the association of the newly created vpc with an existing Route53 hosted zone but I can't find how to do it in CloudFormation.

Using the aws cli, this can be achieved by running (in the user_data script):

aws route53 associate-vpc-with-hosted-zone --hosted-zone-id AAZZZ123AA --vpc VPCRegion=us-west-2,VPCId=$vpcid

But I want CloudFormation to manage these associations so when the stack is deleted then the vpc association will be deleted as well.

I couldn't find online how it can be achieved with CloudFormation, so does anybody know if it can be done?

Best Answer

I couldn't find how to associate a VPC to a Route53 hosted zone, so I've added to the user_data script the following code:

aws route53 get-hosted-zone --id XXXAAA12345 | grep -q $vpcid
if [[ ! $? -eq 0 ]]; then
  aws route53 associate-vpc-with-hosted-zone --hosted-zone-id XXXAAA12345 --vpc VPCRegion=us-west-2,VPCId=$vpcid
else
  echo "VPC $vpcid is already associated to hosted zone company-private"
fi

vpcid variable is inherited from the CloudFormation template:

{ "Fn::Join": [ "=", [ "vpcid", { "Ref": "VPC" } ] ] },

Then, I realized that when a VPC is deleted, it's association to the Route53 hosted zone remains.

In order to make sure that old associations are removed, I've added the following code to the user_data script:

defaultvpc="vpc-20AAAA4b"
vpc_array=()
for vpc in $(aws route53 get-hosted-zone --id XXXAAA12345 | grep vpc | awk '{print $2}' | tr -d '\"|,'); do
  vpc_array+=($vpc)
done
for i in ${!vpc_array[@]}; do
  if [[ ! ${vpc_array[$i]} = $vpcid && ! ${vpc_array[$i]} = $defaultvpc ]] ; then
    echo "VPC ${vpc_array[$i]} doesnt exist anymore - removing association to Route53 hosted zone"
    aws route53 disassociate-vpc-from-hosted-zone --hosted-zone-id XXXAAA12345 --vpc VPCRegion=us-west-2,VPCId=${vpc_array[$i]}
  fi
done
Related Topic