Define providers
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "5.17.0"
}
tls = {
source = "hashicorp/tls"
version = "4.0.4"
}
}
}
provider "aws" {
# Configuration options
region = "us-east-1"
access_key = "AKIATWPFCVR7VUV5PQOZ"
secret_key = "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"
}
provider "tls" {
# Configuration options
}
Resource to Create TLS Key
resource "tls_private_key" "razzaq_key" {
algorithm = "RSA"
rsa_bits = 4096
}
Key Pair Variable
variable "key_pair_name" {
type = string
default = "razzaqkeypair"
}
Resource to Create Generated Key Pair to AWS and Saved Private Key in Local Host
resource "aws_key_pair" "generated_razzaq_key" {
key_name = var.key_pair_name
public_key = tls_private_key.razzaq_key.public_key_openssh
provisioner "local-exec"{
command = "echo '${tls_private_key.razzaq_key.private_key_pem}' > ./'${var.key_pair_name}.pem'"
}
}
Creating SG and Allowed HTTP + SSH
resource "aws_security_group" "razzaq-sg" {
name = "sec-grp-razzaq"
description = "Allow HTTP and SSH traffic via Terraform"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "sec-grp-razzaq"
}
}
Creating EC2 Instance to Patch, Install and Start Apache2 + Display Private Key
resource "aws_instance" "web" {
ami = "ami-053b0d53c279acc90"
instance_type = "t2.micro"
key_name = aws_key_pair.generated_razzaq_key.key_name
tags = {
Name = "assignment1-razzaq"
}
provisioner "local-exec" {
command = "chmod 400 ./${var.key_pair_name}.pem"
}
provisioner "local-exec" {
command = "cat ./${var.key_pair_name}.pem"
}
connection {
type = "ssh"
user = "ubuntu"
private_key = file("${var.key_pair_name}.pem")
host = self.public_ip
}
provisioner "remote-exec" {
inline = [
"sudo apt-get update",
"sudo apt-get install apache2 -y",
"sudo systemctl start apache2"
]
}
}
To Ouput Private Key with Command as Raw Output
output "razzaq_private_key" {
value = tls_private_key.razzaq_key.private_key_pem
sensitive = true
}
Top comments (0)