3

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?

2
  • 2
    What version of Terraform are you using? You could use dynamic blocks in Terraform 0.12+ to do this if you had a map of environment variables or a list of maps. Commented Sep 23, 2020 at 8:19
  • @ydaetskcoR Yeah, I am using terraform 0.13. Commented Sep 23, 2020 at 8:32

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, can you please help me to take the list of environment variables from the variables section rather than the locals?
That's a pretty trivial change but I've made it nonetheless. In general you shouldn't expect answers to 100% solve your problem and instead deal with the very specific issue you had (in this case how to loop over the environment_variable block). Whether the input is a variable or a local isn't all that important.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.