Customize EBS volume attachment on aws_instance, from an AMI with multiple volumes


I am deploying an aws_instance from a pre-existing custom AMI. That AMI has 3 different volumes, the root device, plus two additional EBS volumes.

I am able to map the three EBS volumes within the aws_instance using root_block_device plus a dynamic block on ebs_block_device:

aws_instance "myinstance" {
  root_block_device {

  dynamic "ebs_block_device" {
    for_each = [
      for block_device in data.aws_ami.myami.block_device_mappings : {
        device_name = block_device.device_name
        volume_type = var.volume_type
        volume_size = var.volume_size
        (...other attributes...)
      if block_device.device_name != data.aws_ami.myami.root_device_name
    content {
      device_name           = ebs_block_device.value.device_name
      volume_type           = ebs_block_device.value.volume_type
      volume_size           = ebs_block_device.value.volume_size
      (...other attributes...)

However, this approach runs into Terraform’s limitation of not detecting any changes (see “NOTE”) if I wanted to change volume_size or volume_type for the EBS volumes.

What I would like is to map those two additional EBS volumes from the AMI using aws_ebs_volume and aws_volume_attachment, so that I could in the future easily change, add, or remove them using only Terraform (not a mix of changing them manually and then adjusting the Terraform configuration).

I am able to come up with the resource definition to pull the correct details for aws_ebs_volume and aws_volume_attachment (namely pointing to the correct snapshot_id from the AMI), but if I specify the ami attribute on aws_instance, that immediately attaches all three volumes when the instance is deployed, making Terraform fail when it tries to do my volume attachment.

Is this possible somehow? How can I tell Terraform to attach only the root device, but let me take care of attaching the additional volumes from the AMI?

Thank you,

Hi @ttaveira,

There is 1option in terraform to ignore the additional volumes attachment to the ec2 instance using ephemeral_block_device. Below is the sample code.

Example: AMI below has root volume and an additional EBS volume with device name “/dev/sdg” attached to it. When we run the below config terraform will skip mounting the second volume “/dev/sdg” and deploy instance with only 1 volume and you can use aws_ebs_volume and aws_volume_attachment to add additonal volumes.

resource "aws_instance" "node1" {

    ami = "ami-XXX"
    instance_type = "m5.2xlarge"
    key_name = "XXXXX"
    vpc_security_group_ids = ["XXXXX"]
    subnet_id = "XXXXX"
    root_block_device {
        delete_on_termination = true
        encrypted = true
        volume_size = "70"
        volume_type = "gp3"
    # will Ignore the second additional volume "/dev/sdg"  to be added to my instance.
    ephemeral_block_device {
        device_name = "/dev/sdg"
        no_device = true

Hope this helps.