Terraform Security: Resource Does Not Have Attribute

In this article:

Detect Security Vulnerabilities in Your Web Apps and APIs
Scan now for free

Resolve a Terraform data source issue


At Crashtest Security, we provision our infrastructure using Terraform. Therefore we can recreate whole Kubernetes clusters within minutes. We use our Terraform setup also to integrate some external tools such as Vault within our cluster.

Vault needs to connect to the Kubernetes API to work properly. Therefore, we create a Kubernetes service account using Terraform and provision Vault with its JWT token.

When you implement this naively, you will create a Kubernetes service account, get its secret (using this provider data source), and then use the secret’s token as input for the Vault configuration.

However, any access will fail if the service account in Kubernetes does not exist yet. You will receive an error message like 

resource data.kubernetes_secret_vault_tokenreviewer does not have attribute data.token

This appears because the data attribute is a map, which does not contain any value until the service account is created.

This issue can be circumvented using the function in Terraform. So instead of accessing, you

access lookup(, "token", "")

So when the secret does not exist yet during the planning phase, it won’t break the plan. During the application phase, the value is calculated correctly.

The following plan runs smoothly then:

resource “kubernetes_service_account” “vault_tokenreviewer” {
metadata {
name = “vault-tokenreviewer”
data “kubernetes_secret” “vault_tokenreviewer” {
metadata {
name = “${kubernetes_service_account.vault_tokenreviewer.default_secret_name}”
resource “vault_auth_backend” “kubernetes_backend” {
type = “kubernetes”
resource “vault_kubernetes_auth_backend_config” “kubernetes_backend_config” {
backend = “${vault_auth_backend.kubernetes_backend.path}”
kubernetes_host = “https://${var.kubernetes_host}”
kubernetes_ca_cert = “${var.kubernetes_cluster_ca_certificate}”
token_reviewer_jwt = “${lookup(, “token”, “”)}”

This script shows a basic aspect of container security. Visit our post on collecting Kubernetes logs on Docker for Mac, as well as our page on continuous security.