【问题标题】:Dynamically creating resources in terraform在 terraform 中动态创建资源
【发布时间】:2019-09-06 20:27:24
【问题描述】:

如何将资源块(例如:资源“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"
}

【问题讨论】:

  • 什么意思?您能否提供一个更大的工作示例并解释您在这里尝试做什么?你也在使用 Terraform 0.12+ 吗?
  • 好的我已经编辑了这个问题通常terraform允许我们在tf文件之外输入变量值而不在tf文件中明确给出有没有办法像我们为变量一样提供资源块??
  • 您为什么要这样做,而不是在该目录的.tf 文件中添加卷附件?

标签: amazon-web-services terraform


【解决方案1】:

您将无法单独使用 terraform 脚本动态添加新资源(我之所以说“alone”是因为在我的情况下,我使用 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

【讨论】:

  • 那是完美的 Sajeer,非常感谢您的回复
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 2021-07-10
  • 1970-01-01
  • 2022-07-24
  • 2014-04-01
  • 2020-11-07
  • 2021-05-09
相关资源
最近更新 更多