'terraform attach root EBS volume which is generated from a snapshot to an EC2 instance created from AMI

I have the following code where I am trying to spin up an instance from an AMI and then replace the root volume with a volume I created from an earlier backup snapshot since we do not have periodic AMI created but we do create periodic snapshot. But it failing with error

Error: Error attaching volume (vol-klsdfjlskdf) to instance (i-kjsdhfdsl), message: "Invalid value '/dev/xvda' for unixDevice. Attachment point /dev/xvda is already in use", code: "InvalidParameterValue"

My terraform code is below

     resource "aws_instance" "sampleinstance" {
      ami                    = "ami-089c6f2e386612345"
      instance_type          = "t2.micro"
      key_name               = "blabla"
      subnet_id              = "subnet-65812345"
      private_ip             = "177.78.98.98"
      vpc_security_group_ids = ["sg-0e5a15e71234567"]
      tags = {
        "Name" = "aip poc instance"
      }
    }

    data "aws_ebs_snapshot" "ebs_volume" {
      most_recent = true
      owners      = ["self"]
      filter {
        name   = "tag:Name"
        values = ["poc"]
      }
    }

    resource "aws_volume_attachment" "this" {
      device_name = "/dev/xvda"
      volume_id   = aws_ebs_volume.myvol.id
      instance_id = aws_instance.aipsampleinstance.id
    }

    resource "aws_ebs_volume" "myvol" {
      availability_zone = "us-east-2c"
      size              = 8
      snapshot_id       = data.aws_ebs_snapshot.ebs_volume.id
      tags = {
        "Name" = "poc"
      }

    }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source