首页 > 解决方案 > 在 terraform 中动态创建资源

问题描述

如何将资源块(例如:资源“aws 卷附件”“ebs att”)作为 tf 文件的输入发送

resource "aws_volume_attachment" "ebs_att" {
device_name = "/dev/sdh"
volume_id   = "${aws_ebs_volume.example.id}"
instance_id = "${aws_instance.example.id}"
force_detach = "true"
}

假设,下面是我的 terraform .tf 文件

provider "aws" {
region     = "${var.region}"
access_key = "${var.access_key}"
secret_key = "${var.secret_key}"

}

resource "aws_key_pair" "deployer" {
key_name   = "testkey-${var.hostname}"
public_key = "${file(var.public_key_path)}"
}

对于这个文件,我必须发送资源块->

resource "aws_volume_attachment" "ebs_att"

这样最终的 .tf 文件看起来像

provider "aws" {
region     = "${var.region}"
access_key = "${var.access_key}"
secret_key = "${var.secret_key}"

}

resource "aws_key_pair" "deployer" {
key_name   = "testkey-${var.hostname}"
public_key = "${file(var.public_key_path)}"
}
resource "aws_volume_attachment" "ebs_att" {
device_name = "/dev/sdh"
volume_id   = "${aws_ebs_volume.example.id}"
instance_id = "${aws_instance.example.id}"
force_detach = "true"
}

标签: amazon-web-servicesterraform

解决方案


您将无法单独使用 terraform 脚本动态添加新资源(我之所以说“单独”是因为在我的情况下,我使用 python 类作为配置并从它们动态生成 terraform 文件并从 python 脚本运行应用命令

您可以通过向资源添加计数并将默认变量值设置为 0 来以另一种方式实现此目的,这样通常不会创建资源,除非您专门将计数值设置为 1

variable "create_ebs_resource" {
  type = number
  default = 0
}

resource "aws_volume_attachment" "ebs_att" {
  device_name = "/dev/sdh"
  volume_id   = "${aws_ebs_volume.example.id}"
  instance_id = "${aws_instance.example.id}"
  force_detach = "true"
  count = var.create_ebs_resource
}

然后运行应用命令,就 terraform apply -var="create_ebs_resource=1"好像您想创建资源一样,只需运行terraform apply


推荐阅读