WildWilyWilly
WildWilyWilly

Reputation: 141

Terraform variable from gitlab CI/CD variables

I understand that CI/CD variables can be used in HCL by counting on the fact that having them declared them with a TF_VAR_ prefix in the environment will enable me to look them up as input variables, then use them in the .tf file where I need them.

I did:

This is my main.tf file:

variable ibm_api_key {
}

terraform {
  required_version = ">= 0.13"
required_providers {
    ibm = {
    source = "IBM-Cloud/ibm"
    }
 }
}

provider "ibm" {
  ibmcloud_api_key = var.ibm_api_key
}

Expected behavior: the variable is passed from the CI/CD and added to the HCL code.

Current behavior: during ´plan´, the job falls with error code 1

$ terraform plan
var.ibm_api_key
  Enter a value: ╷
│ Error: No value for required variable
│ 
│   on main.tf line 1:
│    1: variable ibm_api_key {
│ 
│ The root module input variable "ibm_api_key" is not set, and has no default
│ value. Use a -var or -var-file command line argument to provide a value for
│ this variable.
╵

which does not result in an error, but are not being printed either. Only the "echo" commands appear in the output.

$ echo ${output_check}
$ echo ${TF_VAR_ibm_api_key}
Cleaning up project directory and file based variables 00:01
Job succeeded

Upvotes: 1

Views: 5079

Answers (2)

WildWilyWilly
WildWilyWilly

Reputation: 141

The error was in the CI/CD settings. The variables were set to be exclusively passed to protected branches. I was pushing my code to an unprotected one, which prevented variables being passed. When merging the code to a protected branch, the variables showed up correctly. Variables are also correctly imported to Terraform, with the expected exclusion of the TF_VAR_ prefix.

TL;DR If you're having this issue in GitLab's CI/CD check your CICD variables' setting for protected branches, and if the branch you're pushing to corresponds to that setting.

Upvotes: 3

Matthew Schuchard
Matthew Schuchard

Reputation: 28774

Providers typically have intrinsic environment variables configured in their schema and/or associated bindings for authentication. This situation is, according to the provider authentication documentation, no different. You can authenticate the provider with an IBM API key from the GitlabCI project environment variables settings with:

IAAS_CLASSIC_API_KEY="iaas_classic_api_key"

Upvotes: 5

Related Questions