4 minutes
Managing Secrets as Environment Variable in Gitlab CI/CD
Introduction
Recently i was working with terraform to manage and configure Pagerduty and need to setup a Gitlab CI/CD pipeline to automate the whole process and yes that also enables team collaboration . I wrote same pipeline script shared in previous post and it was ready to be pushed until then when i had to hide my pagerduty token (obviously you don't want it to be exposed there) . I read some docs and gave it a try but couldn't manage to get it working , i read some more docs till 3AM in morning because i knew it was too small changes to implement but i was not able to do it . At last i managed to get it working and to be surprised it was a small naming mistake of mine in first place .
That's how it's done
The solution starts with editing your .tf
file it could be your main.tf
or provider.tf
depending on where you have/want to define your credential block in my case i am going to edit main.tf and append a code block like this :-
- In the above code Your provider could be whatever but make sure to pass a variable as credential (in my case to token, depends on provider) , you can name your variable to whatever you want if your provider hasn't documented any specific syntax . Now next we need to define this variable on
variables.tf
:- - Append this block of code in variables.tf file , here we have defined few attributes . The Type attributes tells what type of variable it is and sensitive attributes asks wether this variable should be masked or not . Now we have defind variable and passed it to our credentials, we need to make our final changes to
.gitlab-ci.yaml
:- - You need to export variable as enviromental variable in Gitlab Pipeline . Make sure you use same names everywhere and append this export command under
before_script:
Now Let's add our variables in Gitlab with same name . - To store variables in Gitlab , Goto Project > Settings > CI/CD > Variable > Expand > Use the same name for key and paste your value .
# Configure the PagerDuty provider
provider "pagerduty" {
token = "${var.PAGERDUTY_TOKEN}"
}
terraform {
required_providers {
pagerduty = {
source = "PagerDuty/pagerduty"
version = ">= 2.5.2"
}
}
}
variable "PAGERDUTY_TOKEN" {
type = string
description = "The V2 token"
sensitive = true
}
before_script:
- export TF_VAR_PAGERDUTY_TOKEN=${PAGERDUTY_TOKEN}
Counting Words
2022-10-07 3:25