user2309838
user2309838

Reputation: 307

Using external variable leads to unexpected object

I would like to get a token from a website then use the token in subsequent resources. I'm using the external provider to get the token from a bash script, then use it in later stages:

data "external" "token" {
  program = ["sh", "./token.sh"]

  query = {
    api_key = var.api_key
  }
}

and token.sh looks like below:

#!/usr/bin/env sh
####################
set -e
TOKEN=`curl -X POST <some url>`
jq -n --arg token "$TOKEN" '{"token":$token}'

To acces the $TOKEN, I'm using data.external.token. I'm getting error: data.external.token is object with 5 attributes

I tried doing just TOKEN='FOO' in the script and got the same error so I don't think my curl string was the problem. I'm not seeing why the script wouldn't work... Also, is there any good way to debug terraform especially run time variables?

Upvotes: 0

Views: 108

Answers (1)

Ervin Szilagyi
Ervin Szilagyi

Reputation: 16805

Let me start with this:

Also, is there any good way to debug terraform especially run time variables?

Yes, you can use Terraform outputs for debugging. For example:

output "token_output" {
  value = data.external.token
}

Will output something like this:

token_output = {
  "id" = "-"
  "program" = tolist([
    "sh",
    "./token.sh",
  ])
  "query" = tomap({
    "api_key" = "foo"
  })
  "result" = tomap({
    "token" = "some token"
  })
  "working_dir" = tostring(null)
}

I think this explains why do you get the following error:

data.external.token is object with 5 attributes

What you are lookin for is the result attribute (which is also documented in the attribute references). You can reference it as such:

output "result" {
  value = data.external.token.result
}

For further debugging, besides of outputs, you can use terraform console command as well. This will start a REPL, where you can see the content of your resources from your state.

Upvotes: 2

Related Questions