Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform - Create Snapshot of EBS and then convert Snapshot to EBS and attach to an EC2

Is it possible to create a snapshot of an EBS Volume, take that Snapshot and convert it back into an EBS Volume and attach it to an EC2 via Terraform?

I am currently looking at automating our production and test environment in AWS so they are identical and I found using Terraform quite useful but I can't find any documentation on how achieve this.

like image 449
Muhammed_Khan Avatar asked Oct 19 '25 05:10

Muhammed_Khan


1 Answers

You can create an EBS volume from a snapshot and attach that to an instance without too much difficulty using the aws_ebs_volume and the aws_volume_attachment resources.

You can also create a snapshot using the aws_ebs_snapshot resource or pick up a snapshot ID dynamically using the aws_ebs_snapshot data source.

A quick example might be something like this:

data "aws_ebs_volume" "production_volume" {
  most_recent = true

  filter {
    name   = "volume-type"
    values = ["gp2"]
  }

  filter {
    name   = "tag:Name"
    values = ["Production"]
  }
}

resource "aws_ebs_snapshot" "production_snapshot" {
  volume_id = "${data.aws_ebs_volume.prod_volume.id}"

  tags {
    Name = "Production"
  }
}

resource "aws_ebs_volume" "from_production_snapshot" {
  availability_zone = "us-west-2a"
  snapshot_id       = "${aws_ebs_snapshot.production_snapshot.id}"
  size              = 40

  tags {
    Name = "Non-Production"
  }
}

resource "aws_instance" "non_production" {
  ami               = "ami-21f78e11"
  availability_zone = "us-west-2a"
  instance_type     = "t2.micro"

  tags {
    Name = "Non-Production"
  }
}

resource "aws_volume_attachment" "non_production" {
  device_name = "/dev/xvdf"
  volume_id   = "${aws_ebs_volume.from_production_snapshot.id}"
  instance_id = "${aws_instance.non_production.id}"
}
like image 179
ydaetskcoR Avatar answered Oct 21 '25 19:10

ydaetskcoR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!