Terraform - 创建EBS快照,然后将快照转换为EBS并附加到EC2

时间:2018-03-26 09:44:35

标签: amazon-web-services terraform terraform-provider-aws

是否可以创建EBS卷的快照,获取该快照并将其转换回EBS卷并通过Terraform将其附加到EC2?

我目前正在考虑在AWS中自动化我们的生产和测试环境,因此它们是相同的,我发现使用Terraform非常有用,但我找不到任何关于如何实现这一目标的文档。

1 个答案:

答案 0 :(得分:3)

您可以使用aws_ebs_volumeaws_volume_attachment资源从快照创建EBS卷并将其附加到实例,而不会太困难。

您还可以使用aws_ebs_snapshot资源创建快照,或使用aws_ebs_snapshot数据源动态获取快照ID。

一个简单的例子可能是这样的:

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