ErnieAndBert
ErnieAndBert

Reputation: 1702

How to use an AWS cli command in a Terraform external data source

If I run the following command on its own I get the expected result -

This :

aws cloudfront list-cloud-front-origin-access-identities | jq -r ' .CloudFrontOriginAccessIdentityList.Items[] | select(.Comment == "Created for Nackle Shared CF in pprd").Id'

Returns this:

E1P6ZIBDB6I6FZ

How can I use the Terraform external data source to get the same result?

I tried this :

data "external" "json" {
program = ["sh", "-c", "aws cloudfront list-cloud-front-origin-access-identities | jq -r ' .CloudFrontOriginAccessIdentityList.Items[] | select(.Comment == "Created for Nackle Shared CF in pprd").Id'"] 
}

output "map" {
value = ["${values(data.external.json.result)}"] 
}

But it returns this error when I run the Terraform apply -

Expected a comma to mark the beginning of the next item.

I assume when it is written properly the "value" will be E1P6ZIBDB6I6FZ ?

How do I use the value as a variable in another part of my terraform?

Is there a different way to approach this?

I am new to Terraform and have never played with external data sources.

Upvotes: 4

Views: 7719

Answers (1)

Marcin
Marcin

Reputation: 238179

The json parsing ability of external data source is very limited. It should be (escape quote and return new json):

data "external" "json" {
program = ["sh", "-c", "aws cloudfront list-cloud-front-origin-access-identities | jq -r ' .CloudFrontOriginAccessIdentityList.Items[] | select(.Comment == \"Created for Nackle Shared CF in pprd\") |  {id: .Id}'"] 
}

Then you access the Id as:

data.external.json.result["id"]

Upvotes: 7

Related Questions