Create snapshots of multiple EBS volumes using Terraform

1k views Asked by At

I am trying to create snapshots of certain EBS volumes based on tags in a particular AWS region using Terraform. I have tried filtering EBS volumes based on Tags. I can get a clear output of EBS volume id when only one tag value is specified in the filter attribute but for more than one values, i get the following error:

data.aws_ebs_volume.ebs_volume: data.aws_ebs_volume.ebs_volume: Your query returned more than one result. Please try a more specific search criteria, or set most_recent attribute to true.

Below is my terraform template:

data "aws_ebs_volume" "ebs_volume" {
  filter {
    name   = "tag:Name"
    values = ["EBS1","EBS2","EBS3"]
  }
}
output "ebs_volume_id" {
  value = "${data.aws_ebs_volume.ebs_volume.id}"
}

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

Is there a clear way to create snapshots of multiple EBS volumes using any kind of looping statement in terraform?

1

There are 1 answers

1
ydaetskcoR On BEST ANSWER

You can use the count meta parameter to loop over lists, creating multiple resources or data sources.

In your case you could do something like this:

variable "ebs_volumes" {
  default = [
    "EBS1",
    "EBS2",
    "EBS3",
  ]
}

data "aws_ebs_volume" "ebs_volume" {
  count = "${length(var.ebs_volumes)}"

  filter {
    name   = "tag:Name"
    values = ["${var.ebs_volumes[count.index]}"]
  }
}

output "ebs_volume_ids" {
  value = ["${data.aws_ebs_volume.ebs_volume.*.id}"]
}

resource "aws_ebs_snapshot" "ebs_volume" {
  count     = "${length(var.ebs_volumes)}"
  volume_id = "${data.aws_ebs_volume.ebs_volume.*.id[count.index]}"
}