Skip to content

Instantly share code, notes, and snippets.

@Carlovo
Created May 2, 2022 17:51
Show Gist options
  • Save Carlovo/42dcf2b2f62972891e374699552c14c2 to your computer and use it in GitHub Desktop.
Save Carlovo/42dcf2b2f62972891e374699552c14c2 to your computer and use it in GitHub Desktop.
Input Variables per Local Terraform Workspace
workspace_variables = {
dev = {
instance_count = 2
ami_id = "ami-abc123"
instance_type = "t2.micro"
}
test = {
instance_count = 3
ami_id = "ami-a1b2c3"
instance_type = "t2.medium"
}
prod = {
instance_count = 5
ami_id = "ami-1a2b3c"
instance_type = "t2.large"
}
}
resource "aws_instance" "this" {
count = local.instance_count
ami = local.ami_id
instance_type = local.instance_type
tags = {
Name = "project-xyz-${terraform.workspace}-${count.index}"
}
}
variable "instance_count" {
type = number
default = null
}
variable "ami_id" {
type = string
default = null
}
variable "instance_type" {
type = string
default = null
}
variable "env" {
type = string
default = null
}
variable "workspace_variables" {
type = map(object({
instance_count = number
ami_id = string
instance_type = string
}))
default = {}
}
locals {
default_vars = lookup(var.workspace_variables, terraform.workspace, {
instance_count = 2
ami_id = "ami-abc123"
instance_type = "t2.micro"
})
instance_count = var.instance_count != null ? var.instance_count : local.default_vars["instance_count"]
ami_id = var.ami_id != null ? var.ami_id : local.default_vars["ami_id"]
instance_type = var.instance_type != null ? var.instance_type : local.default_vars["instance_type"]
}
@dale-c-anderson
Copy link

Clever! There is a bit of a bug as written though - all variables are required for all workspaces in tfvars_demo.auto.tfvars (thus defeating the ability to use defaults), unless you add optional() around the workspace_variables map items in tfvars_demo_vars.tf, like so:

variable "workspace_variables" {
  type = map(object({
    instance_count = optional(number)
    ami_id         = optional(string)
    instance_type  = optional(string)
  }))
  default = {}
}

@Carlovo
Copy link
Author

Carlovo commented Mar 29, 2023

It's not a bug, it's a feature ;) Anyway, you are right, your code suggestion makes it better! The reason optionals aren't in here is because they were still an experimental feature in Terraform when I wrote this.

Also, the defaults aren't useless. When you are not using a vars file or input variables at all, they will kick in. As the code is now, it's all or nothing on the vars file.

@dale-c-anderson
Copy link

Ahhh ok that makes sense.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment