Hi Experts,
I would like to create two Instance with different ami’s(Redhat, Ubuntu) and create two volumes and attach to two Instance.
"/dev/sdb" parameter is not supported for Ubuntu when I tried to attach, So in this code, I have created a separate “aws_volume_attachment” resource to attach.
How to use single resource “aws_volume_attachment” using condition if it is redhat use “/dev/sdb” parameter, if it is ubuntu use “/dev/sdg” parameter. Kindly advise
Variable file:
variable "EC2tag" {
default = ["redhat", "ubuntu"]
}
variable "ebstag" {
default = ["redhat", "ubuntu"]
}
variable "Algorithm" {
default = "RSA"
}
variable "redhatdevice" {
default = "/dev/sdb"
}
variable "ubuntudevice" {
default = "/dev/sdg"
}
variable "availability_zone" {
default = "us-east-1e"
}
variable "keyname" {
default = "test"
}
variable "input" {
default = {
ami = ["ami-0b0af3577fe5e3532", "ami-09e67e426f25ce0d7"]
instance_type = ["t2.micro", "t2.small"]
}
}
Main file:
#Creating ec2 resource
resource "aws_instance" "ec2" {
count = length(var.ebstag)
ami = element(var.input["ami"], count.index)
instance_type = element(var.input["instance_type"], count.index)
availability_zone = var.availability_zone
key_name = aws_key_pair.keys.key_name
tags = {
Name = element(var.EC2tag, count.index)
}
}
resource "aws_ebs_volume" "ebs" {
count = length(var.ebstag)
availability_zone = var.availability_zone
size = 10
tags = {
Name = element(var.ebstag, count.index)
}
}
resource "aws_volume_attachment" "redhat" {
device_name = var.redhatdevice
volume_id = element(aws_ebs_volume.ebs.*.id, 0)
instance_id = element(aws_instance.ec2.*.id, 0)
}
resource "aws_volume_attachment" "ubuntu" {
device_name = var.ubuntudevice
volume_id = element(aws_ebs_volume.ebs.*.id, 1)
instance_id = element(aws_instance.ec2.*.id, 1)
}
#Generate key
resource "tls_private_key" "key" {
algorithm = var.Algorithm
}
#Attach key
resource "aws_key_pair" "keys" {
key_name = var.keyname
public_key = tls_private_key.key.public_key_openssh
tags = {
Name = var.keyname
}
provisioner "local-exec" {
command = "echo '${tls_private_key.key.private_key_pem}' > ./myKey.pem"
}
}