Integrating AWS CloudFormation with Git allows you to treat your infrastructure as code (IaC), enabling version control, collaborative reviews, and automated deployments. To achieve this, you store your YAML or JSON templates in a Git repository and use a CI/CD pipeline—such as AWS CodePipeline, GitHub Actions, or GitLab CI—to trigger the creation or update of your CloudFormation stacks whenever code is pushed to a specific branch. This removes the need to manually upload templates via the AWS Management Console, ensuring that your deployed environment always matches the state of your version-controlled code.
What You'll Need
- An AWS Account with administrative permissions or a specific IAM role allowing CloudFormation and related resource creation.
- A Git provider account (GitHub, GitLab, Bitbucket, or AWS CodeCommit).
- The AWS CLI installed and configured on your local machine.
- A basic CloudFormation template file (YAML or JSON) for your infrastructure.
- An IAM user or role with programmatic access keys (Access Key ID and Secret Access Key) for the CI/CD tool to communicate with AWS.
Step-by-Step
- Initialize Your Local Repository: Create a folder on your local machine for your infrastructure project. Open your terminal, navigate to that folder, and run
git init. This initializes the directory as a Git repository, allowing you to track changes to your CloudFormation templates. - Create Your CloudFormation Template: Create a file named
template.yaml. Define your resources (such as an S3 bucket or an EC2 instance) using standard CloudFormation syntax. Ensure you include aParameterssection for values that change between environments (e.g., Dev, Staging, Production) and anOutputssection to export important data like Load Balancer DNS names. - Push Code to a Remote Repository: Create a new repository on your chosen Git platform (e.g., GitHub). Link your local repository to the remote using
git remote add origin [URL], commit your template withgit add .andgit commit -m "Initial infrastructure commit", and then push the code usinggit push -u origin main. - Configure AWS IAM Permissions: In the AWS Console, navigate to the IAM dashboard. Create a new user or role specifically for your Git integration. Attach a policy that grants
cloudformation:*permissions and the specific permissions required to create the resources defined in your template (e.g.,ec2:*ors3:*). If using a third-party provider like GitHub, create an IAM user with programmatic access and save the credentials securely. - Set Up the CI/CD Pipeline: Choose a tool to bridge Git and AWS. For example, if using GitHub Actions, create a
.github/workflows/deploy.ymlfile. In this file, define a trigger (such ason: pushto the main branch) and a job that uses the AWS CLI or a dedicated Action to deploy the template. The command typically looks likeaws cloudformation deploy --template-file template.yaml --stack-name my-infrastructure-stack. - Define Environment-Specific Parameters: To avoid hardcoding values, create separate parameter files (e.g.,
params-dev.jsonandparams-prod.json). Configure your pipeline to pass the correct parameter file based on the branch being deployed. This ensures that your production environment is isolated from your development environment while using the same base template. - Execute a Test Deployment: Push a small change to your template (such as adding a tag to a resource) and push it to your Git repository. Monitor the pipeline logs to ensure the AWS CLI successfully communicates with the CloudFormation API. Check the AWS CloudFormation console to verify that the stack is in the
UPDATE_COMPLETEstate. - Implement a Pull Request Workflow: To prevent breaking changes from hitting production, protect your main branch. Require that all changes be submitted via a Pull Request (PR). This allows team members to review the YAML changes and run "linting" tools or CloudFormation Guard to check for security vulnerabilities before the code is merged and deployed.
Common Mistakes
One of the most frequent errors is hardcoding sensitive information, such as passwords or API keys, directly into the YAML template. Because Git repositories are often shared among teams, this creates a massive security risk. Always use AWS Secrets Manager or Systems Manager Parameter Store and reference them in your template using dynamic references.
Another common mistake is failing to handle "drift." Drift occurs when someone manually changes a resource in the AWS Console without updating the Git template. When the pipeline next runs, CloudFormation may attempt to overwrite those manual changes or fail entirely because the actual state of the resource differs from the expected state defined in the code.
Users also frequently forget to update their IAM roles when adding new resources to the template. For example, if you add an RDS database to your template but the IAM role used by the CI/CD pipeline only has S3 permissions, the deployment will fail during the resource creation phase, even though the CloudFormation template itself is syntactically correct.
Tips
Use a "linter" like cfn-lint in your local environment or as a step in your Git pipeline. A linter checks your template for syntax errors and best-practice violations before you ever attempt to deploy it to AWS, saving time and reducing the number of failed stack updates.
Implement a naming convention for your stacks that includes the environment name (e.g., app-web-dev and app-web-prod). This prevents accidental overwrites and makes it much easier to manage multiple versions of the same infrastructure across different stages of the development lifecycle.
Consider using AWS CloudFormation Change Sets. Instead of deploying directly, have your pipeline create a Change Set. This allows you to see exactly which resources will be added, modified, or deleted before you execute the update, providing a final layer of safety for production environments.
Troubleshooting
If the pipeline fails with an "Access Denied" error, first verify that the IAM credentials used by the Git provider are correct and have not expired. Check the IAM policy attached to the user to ensure it has permissions for both CloudFormation and the specific resources (like EC2 or Lambda) being created. If you are using a cross-account role, ensure the trust relationship is correctly configured to allow the external entity to assume the role.
When a stack enters the ROLLBACK_IN_PROGRESS state, the deployment has failed. To find the cause, go to the CloudFormation console, select your stack, and click on the "Events" tab. Scroll down to the first "Resource Status: CREATE_FAILED" event. The "Status Reason" column will provide the exact error, such as an invalid VPC ID or a naming conflict with an existing resource.
If the deployment hangs or takes an unusually long time, check for resources that require manual intervention or those with long timeout periods (like CloudFront distributions). If the pipeline times out before AWS finishes, you may need to increase the timeout settings in your GitHub Action or GitLab runner configuration.
If you encounter a "Circular Dependency" error, review your template for resources that reference each other. For example, if Resource A depends on Resource B, and Resource B depends on Resource A, CloudFormation cannot determine which to create first. Resolve this by introducing a third resource or using a different referencing method.
Frequently Asked Questions
Can I use Git with the AWS CDK?
Yes. The AWS Cloud Development Kit (CDK) synthesizes high-level code (TypeScript, Python, etc.) into CloudFormation templates. You version the CDK code in Git, and the pipeline runs cdk deploy to update the stacks.
What happens if I delete a file in Git?
Deleting a template file in Git does not automatically delete the stack in AWS. You must explicitly call the delete-stack command via the CLI or console to remove the actual infrastructure.
How do I handle secrets in a Git-based workflow?
Never commit secrets to Git. Use AWS Secrets Manager and reference the secret ARN in your CloudFormation template, or pass them as encrypted environment variables through your CI/CD tool.
Is it better to use YAML or JSON for Git?
YAML is generally preferred for Git because it is more human-readable and produces cleaner "diffs" during pull requests, making it easier for reviewers to see exactly what changed.
Can I deploy to multiple AWS regions from one Git repo?
Yes. You can configure your pipeline to run the deployment command multiple times, specifying a different --region flag for each target environment.
How do I prevent a resource from being deleted during an update?
Add a DeletionPolicy: Retain attribute to the specific resource in your YAML template. This ensures that even if the resource is removed from the code, AWS will keep the physical resource intact.