Skip to content

Instantly share code, notes, and snippets.

@tsoe77
Last active May 16, 2024 19:33
Show Gist options
  • Select an option

  • Save tsoe77/a5dee8cb12e7c94530a1dc7c4d425c35 to your computer and use it in GitHub Desktop.

Select an option

Save tsoe77/a5dee8cb12e7c94530a1dc7c4d425c35 to your computer and use it in GitHub Desktop.
Gitlab CI example for Gitlab + AWS OIDC integrated role
# gitlab ci template for terraform with webidentity role
# https://docs.gitlab.com/ee/ci/cloud_services/aws/ for how to setup gitlab oidc in aws.
#
# assuming it is a monorepo with vpc/dev and vpc/prod
# assuming AWS_IAM_ROLE_DEV and AWS_IAM_ROLE_PROD with role arn as values configured in the CI/CD settings
#
# setup step is to setup working dir and pass role arn
# validate step is to validate terraform
# terraform plan step runs on any other branch except in main
# terraform apply step runs only on main branch
default:
id_tokens:
GITLAB_OIDC_TOKEN:
aud: "https://gitlab.com"
image:
name: hashicorp/terraform:latest
entrypoint:
- '/usr/bin/env'
- 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
cache:
key: terraform
paths:
- terraform/.terraform
- terraform/.terraform.lock.hcl
interruptible: true
stages:
- setup
- validate
- plan
- deploy
.aws_auth_config:
before_script:
- mkdir -p ~/.aws
- echo "${GITLAB_OIDC_TOKEN}" > /tmp/web_identity_token
- echo -e "[profile oidc]\nrole_arn=${ROLE_ARN}\nweb_identity_token_file=/tmp/web_identity_token" > ~/.aws/config
variables:
WORKING_DIR: "vpc/"
AWS_REGION: eu-central-1
IS_CI: true
setup:
stage: setup
script:
- echo WORKING_DIR="$WORKING_DIR" >> setup.env
- echo ROLE_ARN="$ROLE_ARN" >> setup.env
artifacts:
reports:
dotenv: setup.env
only:
changes:
- $WORKING_DIR/**/*
rules:
- changes:
- $WORKING_DIR/dev/**/*
variables:
WORKING_DIR: "vpc/dev"
ROLE_ARN: ${AWS_IAM_ROLE_DEV}
- changes:
- $WORKING_DIR/prod/**/*
variables:
WORKING_DIR: "vpc/prod"
ROLE_ARN: ${AWS_IAM_ROLE_PROD}
- when: always
validate:
stage: validate
script:
- terraform -chdir=$WORKING_DIR init -backend=false
- terraform -chdir=$WORKING_DIR validate
needs:
- job: setup
artifacts: true
rules:
- when: on_success
only:
changes:
- $WORKING_DIR/**/*
plan:
stage: plan
.extends: .aws_auth_config
script:
- terraform -chdir=$WORKING_DIR init
- terraform -chdir=$WORKING_DIR plan
needs:
- job: setup
artifacts: true
allow_failure: false
only:
changes:
- $WORKING_DIR/**/*
deploy:
stage: deploy
image:
name: hashicorp/terraform:latest
entrypoint: [""]
script:
- terraform -chdir=$WORKING_DIR init
- terraform -chdir=$WORKING_DIR apply -auto-approve
needs:
- job: setup
artifacts: true
- job: plan
allow_failure: false
only:
changes:
- $WORKING_DIR/**/*
@relausen

Copy link
Copy Markdown

This is neat, but I wonder why you don't just write the AWS_... variables directly into the .env file instead of adding the GITLAB_ prefix. I think that if you omit the GITLAB_ prefix then you wouldn't need lines 121-124. Or am I missing something?

@tsoe77

tsoe77 commented Mar 15, 2023 •

Copy link
Copy Markdown
Author

This is neat, but I wonder why you don't just write the AWS_... variables directly into the .env file instead of adding the GITLAB_ prefix. I think that if you omit the GITLAB_ prefix then you wouldn't need lines 121-124. Or am I missing something?

Good call out. I just updated it. Thanks for the feedback @relausen 😊

@relausen

Copy link
Copy Markdown

Good call out. I just updated it. Thanks for the feedback @relausen 😊

You're ever so welcome. Thanks for responding so quickly 😄

@agudecima-sinapsis

Copy link
Copy Markdown

How should I configure my provider? I have it only with the specified region. If I have to configure a profile, how should I do it?
provider "aws" { region = var.region }
Captura de pantalla 2024-05-14 a la(s) 11 01 17 a  m
Captura de pantalla 2024-05-14 a la(s) 11 01 44 a  m

@tsoe77

tsoe77 commented May 14, 2024 •

Copy link
Copy Markdown
Author

@agudecima-sinapsis you can load the backend configuration from your backend config by specifying -backend-config flag for terraform init command.

e.g if you are passing a config file

terraform init -backend-config=./backend.tfvars or terraform init -backend-config=./config.txt depending on what your config file name is.

e.g if you want to pass the config parameters as key and values in the command

sample - terraform init -backend-config="KEY=VALUE"

e.g for http backend - HTTP Backend config parameters

terraform init -backend-config="address=https://api.example.com/foo" -backend-config="lock_address=https://api.example.com/lock" -backend-config="unlock_address=https://api.example.com/unlock"

e.g if you want to leverage TF_CLI_ARGS_init environment variable,

export TF_CLI_ARGS_init="-backend-config='address=https://api.example.com/foo' -backend-config='lock_address=https://api.example.com/lock' -backend-config='unlock_address=https://api.example.com/unlock'"
terraform init

Terraform Backend Configuration

I hope it helps!

@agudecima-sinapsis

agudecima-sinapsis commented May 14, 2024 •

Copy link
Copy Markdown

Thank you very much for your help. Actually my problem is when executing the terraform plan command, it does not take my aws credentials. For init, fmt or validate everything goes wonderfully. But I still can't understand why it doesn't take my credentials from the environment variable

Captura de pantalla 2024-05-14 a la(s) 4 33 22 p  m

and this is my env file

env = "dev" region = "us-east-1"

This works for me locally because I have a profile configured in AWS CLI and when I use it, it works wonders. But I still can't get the credentials to fit correctly within the hashicorp/terraform image.

Thanks for your time

@tsoe77

tsoe77 commented May 14, 2024

Copy link
Copy Markdown
Author

@agudecima-sinapsis could you share your gitlab-ci file so I can help you a little better? I don't think you need export AWS_* part in the plan script. It is already done by dotenv.

@agudecima-sinapsis

Copy link
Copy Markdown

@tsoe77 I just made a fork to be able to pass it on to you in a better way, in the authenticate part I am not using sls at the moment because I have loaded my credentials as variables in gitlab. First I want to solve why the terraform plan does not take my credentials

link to gitlab-ci

@tsoe77

tsoe77 commented May 16, 2024

Copy link
Copy Markdown
Author

@agudecima-sinapsis assuming you have your AWS_* configured in the CI/CD variables, you don't need authenticate step in your gitlab-ci.yml

It can just be as simple as this.

default:
  image:
    name: hashicorp/terraform:latest
    entrypoint:
      - '/usr/bin/env'
  interruptible: true

stages:
  - setup
  - validate
  - plan

variables:
  TF_DIR: ${CI_PROJECT_DIR}
  TF_CLI_CONFIG_FILE: $CI_PROJECT_DIR/.terraformrc
  STATE_NAME: 'dev'
  ADDRESS: 'https://gitlab.com/api/v4/projects/${CI_PROJECT_ID}/terraform/state/${STATE_NAME}'
  AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID
  AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY
  AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION

validate:
  stage: validate
  script:
    - echo -e "credentials \"$CI_SERVER_HOST\" {\n  token = \"$CI_JOB_TOKEN\"\n}" > $TF_CLI_CONFIG_FILE
    - terraform init  -reconfigure -backend-config="address=${ADDRESS}" -backend-config="lock_address=${ADDRESS}/lock" -backend-config="unlock_address=${ADDRESS}/lock" -backend-config="username=agudecima-sinapsis" -backend-config="password=$GITLAB_ACCESS_TOKEN" -backend-config="lock_method=POST" -backend-config="unlock_method=DELETE" -backend-config="retry_wait_min=5"
    - terraform validate
  artifacts:
    reports:
      dotenv: validate.env

plan:
  stage: plan
  script:
    - echo -e "credentials \"$CI_SERVER_HOST\" {\n  token = \"$CI_JOB_TOKEN\"\n}" > $TF_CLI_CONFIG_FILE
    - terraform init  -reconfigure -backend-config="address=${ADDRESS}" -backend-config="lock_address=${ADDRESS}/lock" -backend-config="unlock_address=${ADDRESS}/lock" -backend-config="username=agudecima-sinapsis" -backend-config="password=$GITLAB_ACCESS_TOKEN" -backend-config="lock_method=POST" -backend-config="unlock_method=DELETE" -backend-config="retry_wait_min=5"
    - terraform plan -var-file=env.${STATE_NAME}.tfvars
  needs:
    - job: validate
  allow_failure: false

@agudecima-sinapsis

agudecima-sinapsis commented May 16, 2024 •

Copy link
Copy Markdown

@tsoe77 Thank you very much for your contribution, I tried this thing you gave me but I keep getting the same errors I had before.
I don't know if I should configure my provider in some other way?
Maybe it is related to some permission that the access keys are missing, but I can deploy locally with them.

Captura de pantalla 2024-05-16 a la(s) 4 15 39 p  m Captura de pantalla 2024-05-16 a la(s) 4 23 31 p  m

@tsoe77

tsoe77 commented May 16, 2024

Copy link
Copy Markdown
Author

@agudecima-sinapsis you can see the error is not No valid credential source found anymore but STS error with 403 status code. I would double check ACCESS_KEY and SECRET_KEY to start with. You can include TF_LOG=DEBUG before the terraform command to see the exact error. Underlying issue doesn't seem like Gitlab CI but ACCESS KEY. If you are running it in a Project, check if you have any project level CI/CD variables which could interfere with your Repo level CI/CD variables, etc. I hope it helps.

e.g TF_LOG=DEBUG terraform plan -var-file=env.${STATE_NAME}.tfvars

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment