Hello, in this post I want to show a code snippet to integrate Terraform with Vault, actually connect to Vault and get credentials.

In this example, for authentication in Vault, I will use an App Role, as we have already created here in the Vault posts. But there are all other forms of authentication: https://registry.terraform.io/providers/hashicorp/vault/latest/docs#provider-arguments

Taking into account that we already have the AppRole and the key that we will use for the test configured as in the post https://devops-db.com/vault-authentication-methods/ , the Terraform code is very simple:

Keep in mind that I use a Docket as Terraform, so the invocation commands may vary a bit. https://devops-db.com/terraform-docker-image-of-k8s/

The post code is at: https://github.com/faustobranco/devops-db/tree/master/knowledge-base/terraform/vault

You can see that it is not possible to output the value of the variable, as it is immediately recognized that it is a secret with sensitive content. There are several ways to show the result, but to illustrate, I chose to “dump” the content to a file on the OS.

locals {
  VAULT_URL       = "https://vault.devops-db.internal:8200/"
  VAULT_ROLE_ID   = "166b7809-2fc6-1825-7620-f2dff60bcbb1"
  VAULT_SECRET_ID = "50558d2c-fb33-f81f-3441-b33413d5bbb4"
}

provider "vault" {
  address = local.VAULT_URL
  skip_child_token = true
  skip_tls_verify = true

  auth_login {
    path = "auth/approle/login"

    parameters = {
      role_id = local.VAULT_ROLE_ID
      secret_id = local.VAULT_SECRET_ID
    }
  }
}

data "vault_kv_secret_v2" "example" {
  mount = "secret"
  name  = "infrastructure/jenkins/test-secret01"
}

output "servers" {
  value = nonsensitive(data.vault_kv_secret_v2.example)
  sensitive = true
}

resource "local_file" "test_output" {
  content  = yamlencode(data.vault_kv_secret_v2.example)
  filename = "test_output.yaml"
}

Then I do Init, plan and apply:

docker run --rm -it -v $PWD:/vault -w /vault ubuntu_terraform:1.0.0 terraform init
docker run --rm -it -v $PWD:/vault -w /vault ubuntu_terraform:1.0.0 terraform plan
docker run --rm -it -v $PWD:/vault -w /vault ubuntu_terraform:1.0.0 terraform apply

The result of apply:

[...]
Apply complete! Resources: 1 added, 0 changed, 1 destroyed.

Outputs:

servers = <sensitive>

So, we see the result of the file created for example purposes only.

 cat test_output.yaml
"created_time": "2025-02-06T15:25:13.602525363Z"
"custom_metadata": null
"data":
  "pwd": "1234qwer"
  "username": "usr-test01"
"data_json": "{\"pwd\":\"1234qwer\",\"username\":\"usr-test01\"}"
"deletion_time": ""
"destroyed": false
"id": "secret/data/infrastructure/jenkins/test-secret01"
"mount": "secret"
"name": "infrastructure/jenkins/test-secret01"
"namespace": null
"path": "secret/data/infrastructure/jenkins/test-secret01"
"version": 1