CloudFormation Nested Stacks With Git Sync & a GitLab Pipeline

Continuing on from the work in the previous post for setting up GitSync and a GitLab pipeline with CloudFormation. This will detail how to use a Nested Stack that is stored in a GitLab repo and then deploy it with CloudFormation.

In my previous example, CloudFormation would use the CloudFormation template file from the GitLab repo and create the infrastructure as defined. Using a Nested Stack this is a little more complex. The Nested Stack parent template seems to only be able to use templates stored in S3.

To work around this, I have updated my gitlab.ci file so that when there is a merge request, all the files in the repo are sync’d to a specified S3 bucket. This allows CloudFormation to use the parent template from GitLab, but still be able to use the files for the Nested Stack.

There is also an additional file required for the GitSync aspect to this. CloudFormaiton requires the parent template to build the nested stack. However, when using GitSync, that parent template cannot be used, and will fail. There needs to be a parameter deployment file that in its most basic form will merely point to the Nested Stack parent template in the GitLab directory structure.

git-deployment.yaml

deployment.yaml

Creating an Example VPC

This is a a small example to create a VPC with 2 subnets. See the repo for all of the files.

GitLab Pipeline

The GitLab pipeline for this template is following a similar one to the previous post. There are some differences that I will note.

The current way I am running this pipeline is to only use the main branch for all changes. CloudFormation will create a new branch beginning with aws-sync- automatically. This will then be auto merged with main branch. If the merge request is on a branch that does not begin with aws-sync-, then there will be a manual action in the pipeline to merge the branch.

The next step, which is only used if the branch does not begin with aws-sync-, is to sync the GitLab repo to the AWS S3 bucket named ntwklab-cloudformation2. This is how the CloudFormation parent template can be used when pointing all the child templates to S3 URLs.

This is my current gitlab.ci file. It is full of debugging output and a work in progress.

Using the GitLab AWS CLI Image

My gitlab.ci file uses an AWS CLI image to run the S3 sync commands. GitLab provides detailed instructions on how this can be used.
To simply sum it up, use the AWS IAM user AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_DEFAULT_REGION variables in the GitLab CI/CD settings.

The image will be registry.gitlab.com/gitlab-org/cloud-deploy/aws-base:latest

Leave a Comment

Your email address will not be published. Required fields are marked *