How to set up Gitlab CI pipeline to deploy aws infra using Terraform?

Hi folks,

I have been trying to do poc with Gitlab CI in order to deploy my ec2 instance using Terrafrom.
I have created a main.tf file and pused into my gitlab repo, but I am not quite sure how to provide terraform provider crednetials in order to deploy ec2 on aws.

Can soneone guide me how I can deploy my infra using Terrafrom using Gitlab CI?

Notes:

  • I am running a shared runner on Linux with ‘Shell’ executor
  • Runner is running file and able to delopy NodeJs application

Here are some resources that might help:

http://aethereal.io/2017/11/12/managing-AWS.html

Thanks for sharing the articles; however, none of them helped in terms of setting up very simple terraform pipeline to deploy EC2 on AWS. I am only not sure about credentials (aws keys) settings on Gitlab CI.
Can anyone please help?

Thanks for sharing the articles; however, none of them helped in terms of setting up very simple terraform pipeline to deploy EC2 on AWS. I am only not sure about credentials (aws keys) settings on Gitlab CI.
Can anyone please help?

My job getting stuck and pending

I have following in my Gitlab repo.

.gitlab-ci.yml

image:
name: hashicorp/terraform:light
entrypoint:
- ‘/usr/bin/env’
- ‘PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin’

stages:

  • plan
  • apply

cache:
paths:
- .terraform
key: “$CI_BUILD_REPO”

plan:
stage: plan
script:
- terraform init -backend=true -get=true -input=false
- terraform plan -out planfile
when: always
artifacts:
paths:
- planfile

apply:
stage: apply
script:
- terraform init -backend=true -get=true -input=false
- terraform apply
when: manual
dependencies:

  • plan

main.tf

resource “aws_instance” “test_web” {
ami = “ami-09b42976632b27e9b”
instance_type = “t2.micro”

tags {
Name = “test”
}
}

provider.tf
provider “aws” {

}

I set mine up by adding 3 variables in GitLab CI/CD:

  • AWS_ACCESS_KEY_ID
  • AWS_SECRET_ACCESS_KEY
  • AWS_DEFAULT_REGION

Then adding them to the entrypoint:

entrypoint:
- ‘/usr/bin/env’
- ‘PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID} AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY} AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION}’

That should take care of your issue :smiley:

2 Likes

Following article gives a step by step guide for spinning up AWS resources via terraform in gitlab ci.

“Beginners guide to using terraform via Gitlab CI/CD pipelines for AWS.” by Naveed Q. https://link.medium.com/zcb5C2xHp7