Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve token data from Kubernetes Service Account in Terraform

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.

like image 802
Ellis Percival Avatar asked May 10 '19 15:05

Ellis Percival


1 Answers

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" {
  sensitive = true
  value = lookup(data.kubernetes_secret.ci.data, "token")
}
like image 168
Patrick Decat Avatar answered Oct 14 '22 13:10

Patrick Decat