Deploying Infrastructure on AWS with Terraform and AWS CodePipeline.
Contents
1. Project Overview
2. Setting IAM Role for CodeBuild and CodePipeline
3. Setting up Terraform
4. Setting up AWS CodePipeline
· Source stage
· Terraform Plan step
· Manual Approval step
· Terraform Apply stage
· Deploy stage
5. Final View Of the Pipeline
1. Project Overview
In this project, we deploy a simple s3 bucket.
To automate the process Terraform is used for IaC (Infrastructure as Code) and AWS CodePipeline is used for CI/CD.
2. Setting IAM Role for CodeBuild and CodePipeline
Here we will create two IAM roles one is for code build and another is for code pipeline.
Go to IAM and create the following roles with permission.
For code build:
For code pipeline:
3. Setting up Codecommit
Here we use code commit as SCM tool . Go to code commit click on create repository and create one repository (I went with terraform-deployment ) which will store your files.
4. Setting up Terraform
The following are the required steps to start working with Terraform on AWS:
Under the terraform-deployment repository add the below files.
Main.tf — contains a simple s3 bucket and backend s3 which will store the terraform states.
Version.tf — contains the required version of terraform.
After creating the above files, the repository must contain a buildspec file that contains the necessary commands. It is shown below –
plan. yaml
Follow a similar process as Terraform plan for Terraform Apply build stage with the following buildspec.yaml and destroy.yaml file.
5. Setting up with CodeBuild
Now we need to configure our build project. Go to CodeBuild click on create build project and do the following configuration.
Give a suitable name for your build project.
Give Source provider as codecommit and repository which you already created. Branch as Reference type and give your corresponding branch.
Select Environment image and operating system , I went with managed image and ubuntu.
Specify the Role that you have created for codebuild and the buildspecfile , for mine it is plan.yaml.
Similarly created two more build projects for apply and destroy, with buildspecfiles as buildspecfile.yaml and destroy.yaml.
6. Setting up AWS CodePipeline
The AWS CodePipeline will be used for CI/CD (Continuous Integration/Continuous Delivery). The AWS free tier allows 1 free pipeline per month. Our pipeline consists of five stages viz source ,build (terraform-plan), build (Manual Approval step), Terraform Apply and Deploy.
Go to CodePipeline and create your pipeline with the following configuration.
And finally our pipeline will looks like this-
Added manual stage (plan-approval) for apply stage.
After successfully applied , added one more manual stage (destroy-approval) for destroy the resources.
Pushing to codecommit repository will trigger the pipeline and the build process can be viewed through the details option on each build action.
Thank you.