Create snapshots of multiple EBS volumes using Terraform

◇◆丶佛笑我妖孽 提交于 2020-01-03 04:33:14

问题


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:


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]}"
}


来源:https://stackoverflow.com/questions/53113777/create-snapshots-of-multiple-ebs-volumes-using-terraform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!