Search code examples
terraformkube-proxy

Terraform external data in metadata_startup_script


I'm going to parsing a token value from other .tf file into other .tf file

I have tried to understand this link and also from this article

data.tf

data "external" "get_token" {
  program = ["/bin/sh", "${path.module}/get-token.sh"]
}

get-token.sh

#!/bin/bash
token=$(kubectl -n kube-system exec [POD_NAME] cat /var/lib/kube-proxy/kubeconfig 2>/dev/null | grep token | awk '{print $2}'

proxy.tf

...
metadata_startup_script = <<-EOT
- name: kube-proxy
  user:
    token: ${lookup(data.external.get_token.result, "token")}
    certificate-authority-data: ${google_container_cluster.new_container_cluster.master_auth.0.cluster_ca_certificate}
...
EOT

My expectation is token has the value as same as with certificate-authority-data. certificate-authority-data has a exact value like i expect but the token is nil or blank. I have run my get-token.sh manually and it's good. But when terraform want to parse it, the value is not parsed successfully. I have added ' before and after the variable ${lookup(data.external.get_token.result, "token")}. Seems not to work.


Solution

  • https://www.terraform.io/docs/providers/external/data_source.html

    The program must then produce a valid JSON object on stdout, which will be used to populate the result attribute exported to the rest of the Terraform configuration. This JSON object must again have all of its values as strings. On successful completion it must exit with status zero.

    So the script should return a json object.

    #!/bin/bash
    ...
    # add below line for make a json result
    jq -n --arg token "$token" '{"token":$token}'
    

    or if there is no jq,

    #!/bin/bash
    ...
    #add below
    echo -n "{\"token\":\"${token}\"}"