Home How to always trigger an ebs snapshot in terraform
Post
Cancel

How to always trigger an ebs snapshot in terraform

How to always trigger an ebs snapshot in terraform

Imagine you have a scenario that whenever you are going to use terraform apply, you want to always make sure you create a snapshot of a given volume. In this small tutorial we will be creating a trigger to always make sure you snapshot first your volume.

How to obtain an EBS volume programmatically with Terraform

In order to obtain a given volume id, we will make use of a data object to obtain data from our aws account.

1
2
3
4
5
6
7
8
9
10
11
12
data "aws_ebs_volume" "ebs_volume" {
  most_recent = true

  filter {
    name   = "tag:Name"
    values = ["pet-instance-alpha"]
  }
  filter {
    name   = "tag:Env"
    values = ["production"]
  }
}

We then use a filter to obtain our volume that has a tag named “pet-instance-alpha” that is also tagged as “production” for the env tag value.

How to create an ebs snapshot

1
2
3
resource "aws_ebs_snapshot" "ebs_snapshot" {
  volume_id   = data.aws_ebs_volume.ebs_volume.id
}

This is how we can create a simple snapshot resource from our given volume.

How to make sure we always create the snapshot with terraform

We can add a description, as it is part of the resource.

Unfortunately, in AWS ebs snasphots have the name attached only by the tag Name, and are not part of the resource attributes.

So this how we would do it.

1
2
3
4
5
6
7
resource "aws_ebs_snapshot" "ebs_snapshot" {
  volume_id   = data.aws_ebs_volume.ebs_volume.id
  description = "${timestamp()}"
  tags = {
    "Name": "Pet Snapshot"
  }
}

And that’s it, now whenever terraform applying, the changes will make the resource drift, deleting and recreating the snapshot.

Caveats

This approach will keep the state with eternal changes.

Conclusion

That’s it for this simple tutorial, we can now make usage of the aws_ebs_snapshot as an attachment to our ASGs, EC2, etc..

This post is licensed under CC BY 4.0 by the author.