Terraform in Gitlab for AWS
This post goes through the steps explained in this presentation:
- Cumulus Circles: Automate AWS Infra Deployment using Terraform and GitHub Actions (2022), github
Steps:
- Create a
code
AWS account inAWS Organizations
. - Assign your user as admin to the
code
AWS account inIAM Identity Center
- Log into the
code
AWS account as yourself - In
IAM
, createterraform
user, and give it Admin privileges - Create Access Keys for the
terraform
user- In the user details page, navigate to the
Security credentials
tab.- Under the “Access keys” section, click on
Create access key
. - Download and Store the Keys Safely:
- Under the “Access keys” section, click on
- Once the access key is created, AWS will offer you the option to download the key as a .csv file. This file contains the Access Key ID and Secret Access Key.
- Download and save this file in a secure location. This is the only time AWS will display the Secret Access Key. If you lose it, you’ll have to create a new access key.
- In the user details page, navigate to the
- Create Gitlab repo
aws-terraform
- In repo, click
Settings
, clickSecrets and variables->Actions
,New repository secrets
- Add
AWS_ACCESS_KEY_ID
and `AWS_SECRET_ACCESS_KEY
- In repo, click
- Copy contents of github
- Copy
src/*
at the top level of theaws-terraform
sandbox- Change the bucket name. It must be unique across AWS.
- Copy
.gitignore
to the top level of theaws-terraform
sandbox - Don’t copy the
.github
folder with the git actions just yet - Run
git add
at the top, check in and commit
- Copy
- In
main.tf
- Comment out the terraform backend config for now
- Comment out
vpc-infra
module for now
- Install
terraform
e.g. using these instructions - Source the AWS environment variables
- Run these commands:
terraform init
terraform validate
terraform plan
terraform apply
- Comment in the backend
- Update the bucket name in the back end to match the configured bucket
- Run these commands:
terraform init
- Enter
yes
to copy your state to the S3 backend
- Enter
terraform plan
- Don’t run
terraform apply
. We will apply the changes through Github Actions.
- Copy the
.gitlab
folder from the original sandbox- Change the path from
src
to.
in theterraform.yaml
- Change the path from
- Enable the vpc module
- Check in. The changes will be applied through Gitlab Actions
- Review the Gitlab Actions log in the web UI
- Disable the vpc module, setting a
count=0
variable (instead of commenting the module out) - Apply the changes again.