Terraform-创建多个EBS卷

时间:2019-05-20 16:54:20

标签: amazon-web-services terraform

如何创建一个实例并附加多个EBS卷?

以下代码在附加单个EBS卷时有效。我主要关心的是在EBS卷的大小和设备名称之间创建一个映射。我尝试了各种方法,创建了列表等。但是没有运气。

# Create EBS volume
resource "aws_ebs_volume" "ebs_volume" {
  count                 = "${var.ec2_create_volume == true ? var.ec2_instance_count : 0 }"
  availability_zone     = "${aws_instance.ec2.*.availability_zone[count.index]}"
  size                  = "${var.ec2_ebs_volume_size}"
  type                  = "${var.ec2_ebs_volume_type}"
}

# Attach EBS Volume
resource "aws_volume_attachment" "volume_attachment" {
  count                 = "${var.ec2_create_volume == true ? var.ec2_instance_count : 0 }"
  device_name           = "${var.ec2_device_name}"
  volume_id             = "${aws_ebs_volume.ebs_volume.*.id[count.index]}"
  instance_id           = "${aws_instance.ec2.*.id[count.index]}"
}

1 个答案:

答案 0 :(得分:1)

您快到了,尝试使用element(list, index)-它会遍历列表。例如,此配置将成功创建2个ec2实例,并附加3个ebs卷:

variable "ec2_device_names" {
  default = [
    "/dev/sdd",
    "/dev/sde",
    "/dev/sdf",
  ]
}

variable "ec2_instance_count" {
  default = 2
}

variable "ec2_ebs_volume_count" {
  default = 3
}

resource "aws_instance" "ec2" {
  count         = "${var.ec2_instance_count}"
  ami           = "${var.aws_ami_id}"
  instance_type = "${var.ec2_instance_type}"
}

resource "aws_ebs_volume" "ebs_volume" {
  count             = "${var.ec2_instance_count * var.ec2_ebs_volume_count}"
  availability_zone = "${element(aws_instance.ec2.*.availability_zone, count.index)}"
  size              = "${var.ec2_ebs_volume_size}"
}

resource "aws_volume_attachment" "volume_attachement" {
  count       = "${var.ec2_instance_count * var.ec2_ebs_volume_count}"
  volume_id   = "${aws_ebs_volume.ebs_volume.*.id[count.index]}"
  device_name = "${element(var.ec2_device_names, count.index)}"
  instance_id = "${element(aws_instance.ec2.*.id, count.index)}"
}