So, I have just started my journey with Terraform as it looks like a nice tool for IaC and configuration. Coming from Ansible background requires me to readjust my thinking slightly.
While in terraform all basic examples show a main.tf file which has all the logic I wanted to find a way that will allow me to separate variables from the main file for portability and abstraction purposes as I was practicing creating kubernetes secret to represent a username and password.
Normally local variables are enclosed in the locals clause like so:
locals {
my_vars = "some_value"
}
Let's say that I would like to pull a file with sectet details from an external location like git repo, etc. I would have to modify the main.tf file which wouldn't be too convenient. For this I have created a my-vars.yaml file with the following content.
username: "my-secret-user"
password: "my-secret-password"
It is a plain and simple yaml file so the structure is nice and easy. This is where one of the Terraforms' filesystem functions comes in - file function which allows me to pull variables from another file with the below close. As it is a yaml file we can use yamldecode function to parse it.
locals {
my_vars = yamldecode(file("${path.module}/my-vars.yaml"))
}
Then I go with my usual terraform init to pull required providers and check if variables are read properly. For this I can use a nice handy feature of terraform - The Console which is a nice and interactive way of checking what is going on in your terraform deployment.
terraform console
> local.my_vars
{
"password" = "my-secret-password"
"username" = "my-secret-user"
}
> local.my_vars.username
"my-secret-user"
> local.my_vars.password
"my-secret-password"
>
So now I can refer to imported variables and assign them to other ones by using a dotted notation like so.
my_username = local.my_vars.username
Ok, it is time to test it out. Here is my main.tf terraform file that will create a kubernetes secret.
locals {
my_vars = yamldecode(file("${path.module}/my-vars.yaml"))
}
provider "kubernetes" {
config_path = "./config"
config_context = "default"
host = "https://192.168.0.10:6443"
}
resource "kubernetes_secret" "deleteme-secret" {
metadata {
name = "my-deleteme-secret"
}
data = {
username = local.my_vars.username
password = local.my_vars.password
}
type = "Opaque"
}
Now for the nice terraform plan and terraform apply and we should be good to go. Now all that is left is to login to my Raspberry Pi 4 where my k3s is running and check.
~]$ kubectl get secret my-deleteme-secret -o jsonpath="{.data.password}" | base64 --decode
my-secret-password
I had to run base64 --decode as kubernetes secrets are encoded with base64.
So far, so good. The journey continues.