12
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

terraformでcountを使った複数インスタンスにEBSを割り当てる

Posted at

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がattachされます。

さらに

terraform destory -target 'aws_instance.elasticsearch'

とした場合、インスタンスだけ消えてEBSは残るので、次回インスタンスを立ち上げたときには同じEBSが割り当てられます。

問題はterraform destoryしたときにEBSがマウント済みだと当然エラーになるので落とすときはumountをする何かが必要になります。
いまのところ作成時にのみprovisionerが実行されるだけなのでterraformでは完結しません。

12
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?