How to use external data source in terraform with bash script
12,355
Got it working with:
#!/bin/bash
amiid=$(curl -s "someurl" | jq -r 'map(select(.tags.osVersion | startswith("someos"))) | max_by(.tags.creationDate) | .id')
echo -n "{\"ami_id\":\"${amiid}\"}"
which returns
{"ami_id":"ami-xxxyyyzzz"}
Then in the terraform resource, we call it by:
image_id = "${element(split(",", data.external.amiid.result["ami_id"]), count.index)}"
Related videos on Youtube
Author by
sho
Updated on June 04, 2022Comments
-
sho almost 2 years
I have a bash script that will return a single AMI ID. I want to use that AMI ID returned from the bash script as an input for my launch configuration.
data "external" "amiid" { program = ["bash", "${path.root}/scripts/getamiid.sh"] } resource "aws_launch_configuration" "bastion-lc" { name_prefix = "${var.lc_name}-" image_id = "${data.external.amiid.result}" instance_type = "${var.instance_type}" placement_tenancy = "default" associate_public_ip_address = false security_groups = ["${var.bastion_sg_id}"] iam_instance_profile = "${aws_iam_instance_profile.bastion-profile.arn}" lifecycle { create_before_destroy = true } }
When I run this with terraform plan I get an error saying
* module.bastion.data.external.amiid: 1 error(s) occurred: * module.bastion.data.external.amiid: data.external.amiid: command "bash" produced invalid JSON: invalid character 'a' looking for beginning of object key string
Here's the getamiid.sh script:
#!/bin/bash amiid=$(curl -s "https://someurl" | jq -r 'map(select(.tags.osVersion | startswith("os"))) | max_by(.tags.creationDate) | .id') echo -n "{ami_id:\"${amiid}\"}"
when running the script it returns:
{ami_id:"ami-xxxyyyzzz"}
-
Conor Mongey over 5 yearsCan you please supply the getamiid.sh script. It must produce valid json output, as per terraform.io/docs/providers/external/…
-
sho over 5 yearsedited the post with the getamiid.sh script
-