6

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"}
2
  • Can you please supply the getamiid.sh script. It must produce valid json output, as per terraform.io/docs/providers/external/… Commented Sep 10, 2018 at 16:57
  • edited the post with the getamiid.sh script Commented Sep 10, 2018 at 17:24

1 Answer 1

9

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)}"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.