Friday, March 13, 2020

Terraform Cloud current workspace name

Terraform Notes

How to get current workspace name

Working in TF Cloud and you want your tf file to pull your current workspace name. These are what I would call TF Cloud environment variables or global variables or backend data or stuff you can self reference. 

Here is my main.tf under my Github repo that is tied to my Terraform Cloud account. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
variable "ATLAS_WORKSPACE_NAME"{
}

locals{
  version = "1.1"
}

resource "null_resource" "example" {
  triggers = {
      key   = "hello"
      value = formatdate("YYYY-MM-DD hh:mm:ssZZZZZ", timestamp())
  }
}

output "version"{
  value = local.version
}

output "workspace"{
  value = var.ATLAS_WORKSPACE_NAME  
}


The most important part is lines 1-2. Even though I would consider "ATLAS_WORKSPACE_NAME" to be global variable in a traditional sense, Terraform creates a dependency graph that will throw an error that says, "I don't see the variable that you are trying to use." However, declaring a "local" variable that has the same name as a "global" variable does not overwrite the global variable or change the scope the variable. Lines 8-13 is only here to ensure the Apply takes because without any resource TF Cloud will say nothing to do. Line 5 is here so that something actually changes that causes version of the file to change (which triggers a run in TF Cloud).

Here is the end result:


















Wait... there's more. What can I get more than the name of workspace? Run a local-exec for all environment variables. Add this resource block to the above code and re-run it.


resource "null_resource" "envs" {
  provisioner "local-exec" {
      command = "printenv"
  }
}

Based on my sampling, it appears that any variables that begins with "TF_VAR_" can be obtained.


TF_VAR_ATLAS_ADDRESS=https://app.terraform.io
TF_VAR_ATLAS_CONFIGURATION_NAME=Lambchop
TF_VAR_ATLAS_CONFIGURATION_SLUG=my_org_name/Lambchop
TF_VAR_ATLAS_CONFIGURATION_VERSION_GITHUB_BRANCH=master
TF_VAR_ATLAS_CONFIGURATION_VERSION_GITHUB_COMMIT_SHA=99999999999
TF_VAR_ATLAS_RUN_ID=run-J2AHxyXbkcT7VJDD
TF_VAR_ATLAS_WORKSPACE_NAME=Lambchop
TF_VAR_ATLAS_WORKSPACE_SLUG=my_org_name/Lambchop
TF_VAR_TFE_RUN_ID=run-J2AHxyXbkcT7VJDD


Here is the TF code to get couple more environment variables

variable "TFE_RUN_ID"{
}
output "TFE_RUN_ID"{
  value = var.TFE_RUN_ID 
}

variable "ATLAS_ADDRESS"{
}
output "ATLAS_ADDRESS"{
  value = var.ATLAS_ADDRESS
}













No comments:

Post a Comment

AWS WAF log4j query

How to query AWS WAF log for log4j attacks 1. Setup your Athena table using this instruction https://docs.aws.amazon.com/athena/latest/ug/wa...