Preparraform for Terraform
Written: 2018-06-25
Author: WhatsARanjit
Link: WhatsARanjit/terraform-preparraform
The problem
You service your enterprise company’s business units by creating organizations and workspaces for them on demand. They largely need the same types of workspaces. You find yourself manually creating workspaces in the Terraform Enterprise UI, or copying and pasting an API call for your needs. What you really need is a template that you can use a customized workspace name and maybe some customized variable names, to avoid naming collisions.
The fix
If we view the process of creating a workspace separate from the values necessary to create it, we have a separation of execution and data. Mostly, it’s the data we care about- what is the workspace name, the connected repository, and the variables that go along with it? The process of implementing it is the same. We can use WhatsARanjit/terraform-preparraform
in order to get this done. This let’s us express workspaces in HCL format so they are repeatably created. We have an option to prefix the workspace name and/or variables so that we don’t have any naming collisions.
Setup
The necessary gems are outlined in the repository’s Gemfile
.
We do need to provide Terraform Enterprise with some information like an authentication token and the name of the organization we’re using, for example. We do this by creating environment variables. Here is the list:
TFE_TOKEN
Authentication token for TFE user.
TFE_ORG
The name of the organization you would like to manage.
TFE_OAUTH_TOKEN
The OAuth token that can be used. This can be found from tfe oauth_tokens list --organization=$TFE_ORG --only=id --value
.
TFE_PREFIX
This can be used to prefix the workspace name and/or variables/values within the workspace (optional).
Data
# workspaces.hcl
"myworkspace" {
prefix = true
auto-apply = false
terraform-version = "0.11.7"
working-directory = "path/to/subfolder"
vcs-repo {
identifier = "WhatsARanjit/terraform-project"
branch = "master"
ingress-submodules = false
}
variables {
helloworld = "foo"
mypassword {
value = "secret"
sensitive = true
}
AWS_ACCESS_KEY {
value = "AWS Secret Key ID"
sensitive = true
category = "env"
}
structured_data {
value = "{ 'count': 1 }"
hcl = true
prefix = true
}
CONFIRM_DESTROY {
value = "1"
category = "env"
}
}
}
Usage
Generally using prefix = true
anywhere will use the prefix you’ve given in the environment variable in the format $prefix_$value
. All options are shown in the sample.
Terraform variables can be specified as var = "value"
for simple variables. In order to specify, environment variables, hcl
or sensitive
, or use prefixing, an HCL block must be used.
$ ./preparraform.rb
By default, it will look for a file called workspaces.hcl
in your current working directory. An alternate file can be specified as an argument:
$ ./preparraform.rb path/to/another/file.hcl
Deleting workspaces
Workspaces can be deleted by setting a TFE_DELETE
environment variable to any value.