How to use external data source in terraform with

2019-08-12 05:28发布

问题:

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"}

回答1:

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)}"


标签: terraform