johnny3210
johnny3210

Reputation: 61

volume attachment on for_each ec2 creation

I am new to terraform and been trying to figure out how to attach a volume when doing a for_each on ec2 creation.

resource "aws_instance" "test_directory_controller" {
    for_each = aws_network_interface.test_directory_controller

ami = local.test_ami_id
key_name = var.test_instance_key_name
instance_type = var.test_instance_type

iam_instance_profile = module.test_manager.test_instance_profile_name

network_interface {
    network_interface_id = each.value.id
    device_index         = 0
}

root_block_device {
    volume_size = 120
    encrypted = true
}

ebs_block_device  {
    device_name = "/dev/sdh"
    volume_size = 40
    encrypted = true
}

Here is the new code that I have added :

resource "aws_ebs_volume" "test_directory_d_drive" {
  availability_zone = "us-east-1a"
  size = 40
  encrypted = true

  tags = {
      Name = "Local Disk"
      DriveLetter = "D"
  }
}

resource "aws_volume_attachment" "test_volume_attachment" {
  device_name = "xvdf"
  volume_id = aws_ebs_volume.test_directory_d_drive.id
  instance_id = aws_instance.test_directory_controller.id
}

The error states that because of the "for_each" set, it requires a aws_instance.test_directory_controller[each.key].id to resolve it but that seems to cause more errors. What am I missing?

Upvotes: 0

Views: 758

Answers (1)

Helder Sepulveda
Helder Sepulveda

Reputation: 17594

If you need to use a for_each in the aws_instance resource you will have to use it on the volume as well, it is easy to reference those using the key

Here is an example:

data "aws_ami" "suse12" {
  owners      = ["amazon"]
  most_recent = true
  filter {
    name   = "name"
    values = ["*suse*"]
  }
}

locals {
  instances = toset(["one", "two"])
}

resource "aws_instance" "suse12" {
  for_each          = local.instances
  ami               = data.aws_ami.suse12.id
  instance_type     = "m5d.large"
  availability_zone = "us-east-1a"
  tags              = { Name = each.value }
}

resource "aws_ebs_volume" "data-ndj" {
  for_each          = local.instances
  type              = "gp2"
  size              = 110
  availability_zone = "us-east-1a"
}

resource "aws_volume_attachment" "data-ndj" {
  for_each    = local.instances
  device_name = "/dev/sdj"
  instance_id = aws_instance.suse12[each.key].id
  volume_id   = aws_ebs_volume.data-ndj[each.key].id
}

Upvotes: 1

Related Questions