使用Terraform的count功能为多个实例分配EBS
假设subnet.main和aws_security_group已经另行设置好。
#--------------------------------------------------------------
# Ec2 Instances
#--------------------------------------------------------------
resource "aws_instance" "elasticsearch" {
instance_type = "${var.elasticsearch_instance_type}"
ami = "${var.default_ami}"
subnet_id = "${element(aws_subnet.main.*.id, count.index%length(aws_subnet.main.*.id))}"
vpc_security_group_ids = [ "${aws_security_group.output_all.id}", "${aws_security_group.elasticsearch.id}" ]
key_name = "${aws_key_pair.developer.id}"
iam_instance_profile = "${aws_iam_instance_profile.elasticsearch.id}"
tags {
Name = "${format("%s-elasticsearch%02d", var.environment, count.index+1)}"
role = "elasticsearch"
environment = "${var.environment}"
}
count = "${var.elasticsearch_server_count}"
}
#--------------------------------------------------------------
# EBS
#--------------------------------------------------------------
resource "aws_ebs_volume" "elasticsearch-data" {
availability_zone = "${element(aws_subnet.main.*.availability_zone, count.index)}"
size = "${var.elasticsearch_volume_size}"
type = "gp2"
tags {
Name = "${format("elasticsearch%02d-data", count.index+1)}"
environment = "${var.environment}"
}
count = "${var.elasticsearch_ebs_count}"
}
#--------------------------------------------------------------
# EBS attachment
#--------------------------------------------------------------
resource "aws_volume_attachment" "attach_elasticsearch-data" {
device_name = "/dev/sdb"
volume_id = "${element(aws_ebs_volume.elasticsearch-data.*.id, count.index)}"
instance_id = "${element(aws_instance.elasticsearch.*.id, count.index)}"
count = "${var.elasticsearch_server_count}"
}
只需要一个选项:
当elasticsearch_server_count的数量达到并启动服务器后,EBS将被附加。
更进一步。
terraform destory -target 'aws_instance.elasticsearch'
如果删除实例,EBS仍然保留,因此下次启动实例时将分配相同的EBS。
当EBS已经挂载时,在执行 terraform destroy时会产生错误,因此在卸载时需要一个工具来执行卸载操作。目前,provisioner只在创建时执行,所以terraform并不能完成这个工作。