Pass output (database password) from Terraform to Kubernetes manifest in CICD pipeline

11/14/2019

I am using Terraform to provision resources in Azure, one of which is a Postgres database. My Terraform module includes the following to generate a random password and output to console.

resource "random_string" "db_master_pass" {
  length            = 40
  special           = true
  min_special       = 5
  override_special  = "!-_"
  keepers           = {
    pass_version  = 1
  }
}

# For postgres
output "db_master_pass" {
  value = "${module.postgres.db_master_pass}"
}

I am using Kubernetes deployment manifest to deploy the application to Azure managed Kubernetes service. Is there a way of passing the database password to Kubernetes in the deployment pipeline? I am using CircleCI for CICD. Currently, I'm copying the password, encoding it to base64 and pasting it to the secrets manifest before running the deployment.

-- Confounder
circleci
configuration
kubernetes
postgresql
terraform

1 Answer

11/15/2019

One solution is to generate the Kubernetes yaml from a template.

The pattern uses templatefile function in Terraform 0.12 or the template provider earlier versions to read and local_file resource to write. For example:

data "template_file" "service_template" {
  template = "${file("${path.module}/templates/service.tpl")}"
  vars {
    postgres_password = ""${module.postgres.db_master_pass}"
  }
}

resource "local_file" "template" {
  content  = "${data.template_file.service_template.rendered}"
  filename = "postegres_service.yaml"
}

There are many other options, like using to the Kubernetes provider, but I think this better matches your question.

-- Giulio Vian
Source: StackOverflow