DEV Community

Frederick Ollinger
Frederick Ollinger

Posted on

Terraform Parsing Results of a Bash Command

In this example, we will want to take the result of the bash command whoami, and return a variable that Terraform uses as the username which in this example is poweruser.

I found the Terraform documentation to be overly complex and confusing because it requires an input string in valid JSON. Fortunately, this is not so hard to whip up in shell.

NOTE: Many tutorials will suggest using the tool jq, but this just adds more complexity especially if Terraform is run in an arbitrary unix container. Therefore, we'll try to use only standard tools.

Here's the Bash scrip that generates the username in JSON:

#!/bin/env bash

username=`whoami`

echo "{\"value\": \"$username\"}"
Enter fullscreen mode Exit fullscreen mode

Call this whoami.sh and save it in the top level directory of our project.

Here is the output:

{"value": "poweruser"}
Enter fullscreen mode Exit fullscreen mode

Here's the Terraform:

data "external" "username" {
  program = ["bash","whoami.sh"]
  query = {
    p_env = "whoami"
  }
}
Enter fullscreen mode Exit fullscreen mode

In order to use the code use the following as a variable:

  username            = data.external.username.result.value
Enter fullscreen mode Exit fullscreen mode

The way this works can be seen by looking at the top line of terraform which has "data" then "external" then then name, "username".

Finally, "result.value" are hard coded in Terraform when it parses the json output.

This should help to get data from a trivial shell command into Terraform with slightly less effort. Overall, I did find this to be fairly confusing.

Given time, I'll edit this post and add complete working Terrform code.

Top comments (0)