Reputation: 1087
I want to create a AWS instance and according to a variable, create an additional disk or not. This would allow me keeping the same .tf file and just specify via command line variables when I need the disk.
...
variable "create-extra-disk" {
default=false
}
...
resource "aws_instance" "my_instance" {
count = "${var.instance_count}"
ami = "${var.image_id}"
instance_type = "${var.type}"
key_name = "${aws_key_pair.my-keypair.key_name}"
security_groups = ["${aws_security_group.basic_sg.name}"]
ebs_block_device {
# enable = "${var.create-extra-disk}" # I'd like something like this
device_name = "/dev/sdb"
volume_size = 100
volume_type = "gp2"
delete_on_termination = true
}
...
Upvotes: 0
Views: 915
Reputation: 1785
You can use separated resources for ec2, ebs, and ebs attachment for configurability, https://www.terraform.io/docs/providers/aws/r/ebs_volume.html https://www.terraform.io/docs/providers/aws/r/volume_attachment.html
Above code seems to be terraform 0.11 or under,
variable "create-extra-disk" {
default = true
}
resource "aws_instance" "my_instance" {
count = "${var.instance_count}"
...
}
resource "aws_ebs_volume" "additional" {
count = "${var.create-extra-disk == true ? var.instance_count : 0}"
availability_zone = "${var.region}"
size = 100
type = "gp2"
}
resource "aws_volume_attachment" "ebs_att" {
count = "${var.create-extra-disk == true ? var.instance_count : 0}"
device_name = "/dev/sdb"
volume_id = "${element(aws_ebs_volume.additional.*.id, count.index)}"
instance_id = "${element(aws_instance.my_instance.*.id, count.index)}"
}
Upvotes: 1
Reputation: 5763
You need to create two resources and use of count with a variable to include the condition to run the extra disk part, all this would be in the single file.
...
variable "create-extra-disk" {
default=false
}
...
resource "aws_instance" "my_instance" {
count = "${var.instance_count && var.create-extra-disk == true ? 1 : 0}"
ami = "${var.image_id}"
instance_type = "${var.type}"
key_name = "${aws_key_pair.my-keypair.key_name}"
security_groups = ["${aws_security_group.basic_sg.name}"]
}
resource "aws_instance" "my_instance_with_ebs" {
count = "${var.instance_count && var.create-extra-disk == true ? 1 : 0 }"
ami = "${var.image_id}"
instance_type = "${var.type}"
key_name = "${aws_key_pair.my-keypair.key_name}"
security_groups = ["${aws_security_group.basic_sg.name}"]
ebs_block_device {
device_name = "/dev/sdb"
volume_size = 100
volume_type = "gp2"
delete_on_termination = true
}
Upvotes: 0