Issue
i'm new to terraform.
i try to make simple terraform code with aws.
it works well. i can see ec2 and security group, eip.
i want to access instance but i don't have .pem file.
so it make me hard to connect ec2.
how to get .pem file?
can anyone let me know please?
resource "aws_key_pair" "alone_ec2" {
key_name = "alone_ec2"
public_key = file("~/.ssh/id_rsa.pub")
}
resource "aws_security_group" "alone_web" {
name = "Alone EC2 Security Group"
description = "Alone EC2 Security Group"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["${chomp(data.http.myip.body)}/32"]
}
ingress {
from_port = 8080
to_port = 8080
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
# EC2
resource "aws_instance" "web" {
ami = "ami-02de72c5dc79358c9"
instance_type = "t2.micro"
key_name = aws_key_pair.alone_ec2.key_name
vpc_security_group_ids = [
aws_security_group.alone_web.id
]
tags = {
Name = "example-webservice"
}
root_block_device {
volume_size = 30
}
}
# EIP
resource "aws_eip" "elasticip" {
instance = aws_instance.web.id
}
output "EIP" {
value = aws_eip.elasticip.public_ip
}
Solution
You can use "tls_private_key" to create the key pair, save it to your machine using a provisioner when uploading it to aws.
resource "tls_private_key" "this" {
algorithm = "RSA"
rsa_bits = 4096
}
resource "aws_key_pair" "this" {
key_name = "my-key"
public_key = tls_private_key.this.public_key_openssh
provisioner "local-exec" {
command = <<-EOT
echo "${tls_private_key.this.private_key_pem}" > my-key.pem
EOT
}
}
Answered By - Leo Answer Checked By - Willingham (WPSolving Volunteer)