Reputation: 601
I have a .env that is used to create k8s secrets as a file. Before creating the secret, I have to set the values in it as per the environment for the respective keys. I am trying to use Terraform's Kubernetes provider for secret creation. Outside of Terraform, we have ways like scripting to set the.env file, and then pass it for the secret creation. However, is there a way of setting up a .env file using terraform?
Terraform secret construct
data "kubernetes_secret" "test-env" {
metadata {
name = "app-env"
}
data = {
"app.env" = filebase64("./tomcat/app.env")
}
}
resource "kubernetes_secret" "test-env" {
metadata {
name = "app-env"
namespace = "test-deployment"
}
type = "Opaque"
data = "{data.kubernetes_secret.test-env.template}"
}
app.env (*_value to be replaced before the secret creation)
JAVA_OPTS ="java_opts_value"
NGINX_VERSION="nginx_version_value"
TOMCAT_VERSION="tomcat_version_value"
POSTGRES_VERSION="postgres_version_value"
I am new to Terraform and any guidance would be appreciated.
Upvotes: 1
Views: 1473
Reputation: 74134
Terraform has no explicit support for "env files", since that isn't a standard format with a specification that Terraform could implement.
However, if you take care with escaping then you can potentially construct any text-based file format using Terraform's string template features.
Exactly what format is acceptable inside an "env file" will depend on which language and library you are using to interpret it, but assuming a format like what you showed in your question you could construct the contents of such a file like this:
locals {
env_values = {
JAVA_OPTS = "java_opts_value"
NGINX_VERSION = "nginx_version_value"
TOMCAT_VERSION = "tomcat_version_value"
POSTGRES_VERSION = "postgres_version_value"
}
env_file_content = <<EOT
%{ for k, v in local.env_values ~}
${k}=${format("%q", v)}
%{ endfor ~}
EOT
}
With the above, local.env_file_content
will be a string containing the following content:
JAVA_OPTS="java_opts_value"
NGINX_VERSION="nginx_version_value"
TOMCAT_VERSION="tomcat_version_value"
POSTGRES_VERSION="postgres_version_value"
I used Terraform's format
function to cause the values to be written in quotes, with some escaping if needed. Terraform interprets the %q
verb as requesting JSON-style string quoting and escaping, which may or may not match the expectations of whatever software will be parsing this file. You may therefore need to select a different escaping strategy if your target software has different expectations.
Upvotes: 1
Reputation: 238139
You can use local-exec to perform any custom processing of files in your TF script.
Upvotes: 2