amazon-ec2 - 通过 terraform 终止 EC2 实例时删除 EBS 卷
问题描述
我的 .tf 文件中有以下内容
provider "aws" {
region = "${var.aws_region}"
}
resource "aws_ebs_volume" "agent-xvdf" {
count = "${var.ec2_count}"
availability_zone = "${var.availability_zone}"
kms_key_id = "xxxx"
encrypted = "true"
size = "${var.vol_size_details_xvdf}"
type = "${var.vol_type_details}"
tags {
Name = "d-drive"
Owner = "${var.ebs_vol_owner}"
Managed_By = "Terraform"
}
}
resource "aws_instance" "my-ec2" {
depends_on = ["aws_ebs_volume.agent-xvdf"]
lifecycle {
ignore_changes = ["tags"]
create_before_destroy = true
}
count = "${var.ec2_count}"
ami = "${data.aws_ami.ami_id.id}"
iam_instance_profile = "yyyy"
instance_type = "${var.instance_type_details}"
tags {
Owner = "${var.instance_owner}"
ServerRole = "${var.server_details} ${var.ec2_os_flavour}"
Creator = "${var.creator_initials}"
Created = "TF Creation Time = ${timestamp()}"
}
vpc_security_group_ids =
["${data.aws_security_group.vpc_security_group_details.id}"]
#This is a template provider which exposes chef-cookbook roles during
bootstrapping process to manage instances or to install software
#In the below code snippet we have used "teamcity.chef.json" file to
mention Chef cookbook recipes to httpd and TeamCity.
user_data = "${file("..\\common\\${var.env_subfolder}\\teamcity.agent.chef.${var.app_instance}.json")}"
availability_zone = "${var.availability_zone}"
subnet_id = "${data.aws_subnet.subnet_id_details.id}"
# This parameter automatically deletes root-volume attached to the instance
when the instance is terminated.
root_block_device {
delete_on_termination = "true"
volume_size = "${var.vol_size_details_sda1}"
volume_type = "${var.vol_type_details}"
}
}
# Below resource will attach/detach "agent-xvdf" volume from AWS Instance i.e. {aws_instance.my-ec2}
resource "aws_volume_attachment" "agent-xvdf" {
depends_on = ["aws_ebs_volume.agent-xvdf"]
count = "${var.ec2_count}"
device_name = "xvdf"
volume_id = "${element(aws_ebs_volume.agent-xvdf.*.id,
count.index)}"
instance_id = "${element(aws_instance.my-ec2.*.id, count.index)}"
force_detach = "true"
skip_destroy = "false"
}
使用目前的设置,terraform -pan、-apply 和 -destroy 工作正常,分别创建和删除 3 个资源。
但是,当我通过 terraform 应用此计划,然后尝试通过 AWS 控制台终止实例时,阻止 EBS 卷,即 xvdf 不会自动删除。
我们如何将此 ebs 音量设置为terminate on instance delete
?
解决方案
您可以使用资源中的ebs_block_device
块aws_instance
。默认情况下,这将在实例终止时删除 ebs 卷。
https://www.terraform.io/docs/providers/aws/r/instance.html#block-devices
您必须使用上述内容而不是aws_volume_attachment
资源。
推荐阅读
- openapi - 如何在openapi-generator中获取不同组中的参数
- python - 将字符串列表转换为 2 元组整数列表
- linux - 在 ubuntu 上运行 cron 作业
- python - XLSXWriter:向图像添加超链接?
- apache-kafka - Kafka Connect S3 - JSON 到 Parquet
- javascript - 让材料表单字段适合 Flex Box 容器?
- javascript - 通过快递中间商时图像格式发生变化
- typescript - TSLint 将 body-parser 标记为已弃用
- android - Retrofit Post 请求不起作用,我收到 500 错误代码(内部服务器错误)
- regex - 删除vim中每一行的第i个字符?