Skip to content

Instantly share code, notes, and snippets.

@tkuchiki
Last active July 17, 2020 02:20
Show Gist options
  • Save tkuchiki/f0b804f2bae96e8676e5d86c0ee2bcb8 to your computer and use it in GitHub Desktop.
Save tkuchiki/f0b804f2bae96e8676e5d86c0ee2bcb8 to your computer and use it in GitHub Desktop.
terraform の external data source を使って外部コマンドの実行結果を variable として使用する
variable "foo" {
type = "string"
default = "baz"
}
data "external" "example" {
program = ["bash", "test.sh"]
query = {
foo = "${var.foo}"
}
}
output "example" {
value = "${data.external.example.result["bar"]}"
}
  • query に指定した値を json として コマンドに渡している
  • 外部コマンドは json を出力する
  • 値の参照は data.external.example.result["bar"] のように、 .result[KEY]
$ echo '{"foo":"baz"}' | bash test.sh
{
  "bar": "baz qux"
}
$ terraform apply
data.external.example: Refreshing state...

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

example = baz qux

$ terraform apply -var 'foo=foo bar baz'
data.external.example: Refreshing state...

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

example = foo bar baz qux
#!/bin/bash
set -e
eval "$(jq -r '@sh "VAL=\(.foo)"')"
BAR="${VAL} qux"
jq -n --arg bar "${BAR}" '{"bar":$bar}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment