Search code examples
jenkinsterraformjenkins-pipelineterraform-provider-aws

Different Terraform plan for specific environments


I need to pass to Terraform apply specific environment variables like dev, prod, staging from *.tfstate file. So far what I did is to create 3 Workspaces and variables for them. In the variables.tf file I have:

My folder structure is:

dev.tfvars
prod.tfvars
staging.tfvars
main.tf
variables.tf

variables.tf

variable "env_dev" {
  type    = string
}

variable "env_prod" {
  type    = string
}

variable "env_staging" {
  type    = string
}

In *.tfvars for dev, prod and staging I have:

env_dev = "dev"
env_prod = "prod"
env_staging = "staging"

What I want to achieve is to update lambda aliases for the specific environment not all at the same time:

resource "aws_lambda_alias" "prod_lambda_alias" {
  name     = var.env_dev
  description      = "Release candidate -"
  function_name    = var.function_name
  function_version = aws_lambda_function.payload.version
}

resource "aws_lambda_alias" "dev_lambda_alias" {
  name             = var.env_dev
  description      = "Release candidate - "
  function_name    = var.function_name
  function_version = var.function_version != "" ? var.function_version : "$LATEST"
}

resource "aws_lambda_alias" "staging_lambda_alias" {
  name             = var.env_staging
  description      = "Release candidate - "
  function_name    = var.function_name
  function_version = aws_lambda_function.payload.version
}

And for the pipeline to use export for the specific workspace, below is for dev:

export TF_WORKSPACE=dev

Then to use Terraform apply as below to apply the changes:

terraform apply plan.out

I want to apply the changes just for specific resource. Example: If I want to update dev "resource aws_lambda_alias" "dev_lambda_alias" to update just that one and not the other 2 resources for prod and staging.

Regards


Solution

  • If the name of the alias is going to have the same name as the workspace, this should do the trick:

    resource "aws_lambda_alias" "lambda_alias" {
      name             = terraform.workspace
      description      = "Release candidate -"
      function_name    = var.function_name
      function_version = terraform.workspace == "dev" ? "$LATEST" : aws_lambda_function.payload.version
    }
    

    More information about terraform.workspace syntax can be found in documentation.