Dipendra Dangal
Dipendra Dangal

Reputation: 1183

Multiple Environment Variables in AWS Codebuild with Terraform

I am using Terraform to provision AWS CodeBuild. In the environment section, I have configured the following:

  environment {
    compute_type                = "BUILD_GENERAL1_SMALL"
    image                       = "aws/codebuild/standard:3.0"
    type                        = "LINUX_CONTAINER"
    image_pull_credentials_type = "CODEBUILD"

    environment_variable {
      name  = "SOME_KEY1"
      value = "SOME_VALUE1"
    }

    environment_variable {
      name  = "SOME_KEY2"
      value = "SOME_VALUE2"
    }

  }

I have more than 20 environment variables to configure in my Codebuild Project.

Is it possible to create a list and define a single environment_variable parameter to configure all environment variables?

Upvotes: 3

Views: 3012

Answers (1)

ydaetskcoR
ydaetskcoR

Reputation: 56877

You could achieve this by using dynamic blocks.

variable "env_vars" {
  default = {
    SOME_KEY1 = "SOME_VALUE1"
    SOME_KEY2 = "SOME_VALUE2"
  }
} 

resource "aws_codebuild_project" "test" {
  # ...

  environment {
    compute_type                = "BUILD_GENERAL1_SMALL"
    image                       = "aws/codebuild/standard:3.0"
    type                        = "LINUX_CONTAINER"
    image_pull_credentials_type = "CODEBUILD"

    dynamic "environment_variable" {
      for_each = var.env_vars
      content {
        name  = environment_variable.key
        value = environment_variable.value
      }
    }
  }
}

This will loop over the map of env_vars set in the locals here (but could be passed as a variable) and create an environment_variable block for each, setting the name to the key of the map and the value to the value of the map.

Upvotes: 13

Related Questions