如果count.index = 0,则使用terraform为aws_instance设置network_interface

时间:2018-03-30 21:24:18

标签: terraform terraform-provider-aws

我正在使用terraform创建2个ec2实例,我想给第一个terraform创建的实例提供辅助IP地址。

我正在使用下面的代码块

resource "aws_network_interface" "floating_private" {
  subnet_id       = "${var.subnet_cluster_one}"
  private_ips_count = 2
}

resource "aws_instance" "instance_attrix_cluster_one" {
    count = 2
    instance_type = "${var.aws_instance_type}"
    ami = "${var.attrix_ami}"
    subnet_id = "${var.subnet_cluster_one}"
    security_groups = "${var.aws_security_groups}"
    key_name = "${var.ssh_key}"
    tags = "${merge(var.default_tags, map("Name", "${format("attrix%02d", 
count.index + 1)}-${var.env_name}"))}"
}

我尝试在“aws_instance”块中添加以下代码

network_interface = "${floating_private.id ? count.index == 0 : count.index >= 0}"

但是,我看到下面的错误 -

 Error reading config for aws_instance[instance_attrix_cluster_one]: floating_private.id: resource variables must be three parts: TYPE.NAME.ATTR in:

 ${floating_private.id ? count.index == 0 : count.index >= 0}

如果count == 0?

,如何设置network_interface属性

1 个答案:

答案 0 :(得分:0)

我没有创建两个自定义ENI并将它们附加到第一个实例,而是略微改变了方法,因为默认的ENI是使用实例创建的,我们在创建实例后的第一个实例附加了一个ENI。

允许Terraform为实例创建默认ENI,然后为第一个实例创建附件。见下文。

resource "aws_network_interface" "floating_private" {
  subnet_id = "${data.aws_subnet.example.id}"
}

resource "aws_instance" "instance_attrix_cluster_one" {
  count         = 2
  instance_type = "t2.micro"
  subnet_id     = "${data.aws_subnet.example.id}"
  ami           = "${data.aws_ami.ubuntu.id}"

  tags {
      Name = "test-${count.index}"
  }
}

resource "aws_network_interface_attachment" "test" {
  instance_id          = "${element(aws_instance.instance_attrix_cluster_one.*.id, count.index)}"
  network_interface_id = "${element(aws_network_interface.floating_private.*.id, count.index)}"
  device_index         = "${count.index + 1}"
}

略微修改以在我的机器上进行一些测试,但希望您能够理解并适用于您的解决方案。