Skip to content

Instantly share code, notes, and snippets.

@iamtheindian
Created June 13, 2020 10:15
Show Gist options
  • Save iamtheindian/86124ccb721b07c4b8737abd5158091d to your computer and use it in GitHub Desktop.
Save iamtheindian/86124ccb721b07c4b8737abd5158091d to your computer and use it in GitHub Desktop.
#creating instance
#instance ami id
variable "ami_id" {
#IMAGE NAME = Amazon Linux 2 AMI (HVM), SSD Volume Type
default = "ami-0447a12f28fddb066"
}
#creating key pair and deleting when destroy command executed
resource "null_resource" "exec" {
provisioner "local-exec" {
command = "aws ec2 create-key-pair --key-name MyKeyPair --query 'KeyMaterial' --output text > /root/HybridCloud/Terraform/MyKeyPair.pem --profile rbterra"
}
provisioner "local-exec" {
when = "destroy"
command = "aws ec2 delete-key-pair --key-name MyKeyPair --profile rbterra && rm -f MyKeyPair"
on_failure = "continue"
}
}
#reading data of key pair file
data "local_file" "key_file" {
depends_on =[null_resource.exec]
filename = "/root/HybridCloud/Terraform/MyKeyPair.pem"
}
#launching instance
resource "aws_instance" "webos" {
ami = var.ami_id
instance_type = "t2.micro"
depends_on = [null_resource.exec,aws_security_group.allow_tls,aws_security_group_rule.http,aws_security_group_rule.https]
connection {
type = "ssh"
user = "ec2-user"
private_key = data.local_file.key_file.content
host = aws_instance.webos.public_ip
}
provisioner "remote-exec" {
inline = [
"sudo yum install httpd git php -y",
"sudo systemctl start httpd",
"sudo systemctl enable httpd",
]
}
key_name = "MyKeyPair"
vpc_security_group_ids = [aws_security_group.allow_tls.id]
tags = {
Name = "TRedHat"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment