如何通过 bash 脚本在 terraform 中使用外部数据源 [英] How to use external data source in terraform with bash script

查看:25
本文介绍了如何通过 bash 脚本在 terraform 中使用外部数据源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将返回单个 AMI ID 的 bash 脚本.我想使用从 bash 脚本返回的 AMI ID 作为启动配置的输入.

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

当我使用 terraform plan 运行它时,我收到一条错误消息

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

这是 getamiid.sh 脚本:

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

运行脚本时返回:

{ami_id:"ami-xxxyyyzzz"}

推荐答案

得到它的工作:

#!/bin/bash
amiid=$(curl -s "someurl" | jq -r 'map(select(.tags.osVersion | startswith("someos"))) | max_by(.tags.creationDate) | .id')
echo -n "{"ami_id":"${amiid}"}"

返回

{"ami_id":"ami-xxxyyyzzz"}

然后在 terraform 资源中,我们调用它:

Then in the terraform resource, we call it by:

image_id = "${element(split(",", data.external.amiid.result["ami_id"]), count.index)}"

这篇关于如何通过 bash 脚本在 terraform 中使用外部数据源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆