Retrieve token data from Kubernetes Service Account in Terraform

5/10/2019

I'm creating a Kubernetes Service Account using terraform and trying to output the token from the Kubernetes Secret that it creates.

resource "kubernetes_service_account" "ci" {
  metadata {
    name = "ci"
  }
}

data "kubernetes_secret" "ci" {
  metadata {
    name = "${kubernetes_service_account.ci.default_secret_name}"
  }
}

output "ci_token" {
  value = "${data.kubernetes_secret.ci.data.token}"
}

According to the docs this should make the data block defer getting its values until the 'apply' phase because of the computed value of default_secret_name, but when I run terraform apply it gives me this error:

Error: Error running plan: 1 error(s) occurred:

* output.ci_token: Resource 'data.kubernetes_secret.ci' does not have attribute 'data.token' for variable 'data.kubernetes_secret.ci.data.token'

Adding depends_on to the kubernetes_secret data block doesn't make any difference.

If I comment out the output block, it creates the resources fine, then I can uncomment it, apply again, and everything acts normally, since the Kubernetes Secret exists already.

I've also made a Github issue here.

Update

The accepted answer does solve this problem, but I omitted another output to simplify the question, which doesn't work with this solution:

output "ci_crt" {
  value = "${data.kubernetes_secret.ci.data.ca.crt}"
}
* output.ci_ca: lookup: lookup failed to find 'ca.crt' in:

${lookup(data.kubernetes_secret.ci.data, "ca.crt")}

This particular issue is reported here due to a bug in Terraform, which is fixed in version 0.12.

-- Ellis Percival
kubernetes
terraform

1 Answer

5/14/2019

This works:

resource "kubernetes_service_account" "ci" {
  metadata {
    name = "ci"
  }
}

data "kubernetes_secret" "ci" {
  metadata {
    name = "${kubernetes_service_account.ci.default_secret_name}"
  }
}

output "ci_token" {
  value = "${lookup(data.kubernetes_secret.ci.data, "token")}"
}
-- Patrick Decat
Source: StackOverflow