Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 967
ErnieAndBert Avatar asked Oct 18 '25 17:10

ErnieAndBert


1 Answers

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"]
like image 139
Marcin Avatar answered Oct 20 '25 09:10

Marcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!