如何根据Terraform-AWS中的变量启用/禁用磁盘?

时间:2019-07-16 12:01:00

标签: terraform terraform-provider-aws

我想创建一个AWS实例,然后根据一个变量创建或不创建其他磁盘。这将允许我保留相同的.tf文件,并在需要磁盘时通过命令行变量进行指定。

...
variable "create-extra-disk" {
    default=false
}
...
resource "aws_instance" "my_instance" {
    count           = "${var.instance_count}"
    ami             = "${var.image_id}"
    instance_type   = "${var.type}"
    key_name        = "${aws_key_pair.my-keypair.key_name}"
    security_groups = ["${aws_security_group.basic_sg.name}"]

    ebs_block_device {
        # enable = "${var.create-extra-disk}" # I'd like something like this
        device_name = "/dev/sdb"
        volume_size = 100
        volume_type = "gp2"
        delete_on_termination = true
    }
    ...

2 个答案:

答案 0 :(得分:1)

您可以将单独的资源用于ec2,ebs和ebs附件,以实现可配置性, https://www.terraform.io/docs/providers/aws/r/ebs_volume.html https://www.terraform.io/docs/providers/aws/r/volume_attachment.html

以上代码似乎是Terraform 0.11或更低版本,

variable "create-extra-disk" {
  default = true
} 

resource "aws_instance" "my_instance" {
  count         = "${var.instance_count}"
  ...
}

resource "aws_ebs_volume" "additional" {
  count             = "${var.create-extra-disk == true ? var.instance_count : 0}"
  availability_zone = "${var.region}"
  size              = 100
  type              = "gp2"
}

resource "aws_volume_attachment" "ebs_att" {
  count       = "${var.create-extra-disk == true ? var.instance_count : 0}"
  device_name = "/dev/sdb"
  volume_id   = "${element(aws_ebs_volume.additional.*.id, count.index)}"
  instance_id = "${element(aws_instance.my_instance.*.id, count.index)}"
}

答案 1 :(得分:0)

您需要创建两个资源,并使用count和一个变量来包含运行额外磁盘部分的条件,所有这些都将在单个文件中。

...
variable "create-extra-disk" {
default=false
}
...
resource "aws_instance" "my_instance" {
count           = "${var.instance_count && var.create-extra-disk == true ? 1 : 0}"
ami             = "${var.image_id}"
instance_type   = "${var.type}"
key_name        = "${aws_key_pair.my-keypair.key_name}"
security_groups = ["${aws_security_group.basic_sg.name}"]
}

resource "aws_instance" "my_instance_with_ebs" {
count           = "${var.instance_count && var.create-extra-disk == true ? 1 : 0 }"
ami             = "${var.image_id}"
instance_type   = "${var.type}"
key_name        = "${aws_key_pair.my-keypair.key_name}"
security_groups = ["${aws_security_group.basic_sg.name}"]

ebs_block_device {
    device_name = "/dev/sdb"
    volume_size = 100
    volume_type = "gp2"
    delete_on_termination = true
}