将EBS卷附加到每个terraform的EC2实例

时间:2020-08-20 17:08:17

标签: amazon-web-services foreach terraform ebs

我在使用Terraform的专用子网中创建了实例。每个实例位于其自己的可用区中。为每个实例创建了实例。现在,我将ebs卷附加到每个实例,并且在指定为每个实例创建实例时遇到错误。以下是资源和错误的代码和变量。任何建议将不胜感激。

   resource "aws_instance" "private" {
      for_each      = var.priv_subnet
      ami           = var.ec2_amis[var.region]
      instance_type = each.value.instance_type
      key_name      = aws_key_pair.main.key_name
      subnet_id     = aws_subnet.private[each.key].id
      vpc_security_group_ids = [
        aws_security_group.main_sg.id,
        aws_security_group.instance_sg.id
      ]
    
      tags = {
        Name = each.value.tag
      }
    }
    
    resource "aws_ebs_volume" "partition" {
      for_each          = var.volumes
      availability_zone = each.value.availability_zone
      size              = each.value.size
    
      tags = {
        Name = each.key
      }
    }

resource "aws_volume_attachment" "ebs_att" {
  for_each    = aws_ebs_volume.partition
  device_name = contains(["Primary", "Worker1", "Worker2"], each.key) ? "/dev/sdf" : "/dev/sdg"
  volume_id   = each.value.id
  instance_id = aws_instance.private.id
}

变量

variable "volumes" {
  type = map(object({
    size              = string
    availability_zone = string
  }))
  default = {
    "Primary" = {
      size              = "200"
      availability_zone = "us-west-2a"
    }
    "PrimarySecondary" = {
      size              = "100"
      availability_zone = "us-west-2a"
    }
    "Worker1" = {
      size              = "200"
      availability_zone = "us-west-2b"
    }
    "Worker1Secondary" = {
      size              = "100"
      availability_zone = "us-west-2b"
    }
    "Worker2" = {
      size              = "200"
      availability_zone = "us-west-2c"
    }
    "Worker2Secondary" = {
      size              = "100"
      availability_zone = "us-west-2c"
    }
  }
}

variable "priv_subnet" {
  type = map(object({
    instance_type = string
    subnet        = string
    tag           = string
  }))
  default = {
    "us-west-2a" = {
      instance_type = "m4.2xlarge"
      subnet        = 4
      tag           = "Primary"
    }
    "us-west-2b" = {
      instance_type = "m4.4xlarge"
      subnet        = 5
      tag           = "Worker1"
    }
    "us-west-2c" = {
      instance_type = "m4.4xlarge"
      subnet        = 6
      tag           = "Worker2"
    }
  }
}

错误

Error: Unsupported attribute

  on vpc.tf line 51, in resource "aws_volume_attachment" "ebs_att":
  51:   instance_id = aws_instance.private[each.value.tag].id
    |----------------
    | each.value is object with 12 attributes

This object does not have an attribute named "tag".

1 个答案:

答案 0 :(得分:1)

得到我自己的答案。我必须指定:

instance_id = aws_instance.private[each.value.availability_zone].id

在aws_volume_attachment资源中