blahblah
blahblah

Reputation: 209

Terraform create pem file

I'm new to Terraform and I'm trying to create a simple AWS Terraform code.

It works well but I can see ec2 and security group, eip.

I want to access instance but I don't have .pem file.

So it's hard to connect to the ec2 instance.

How to get the .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
}

Upvotes: 1

Views: 3254

Answers (1)

Leo
Leo

Reputation: 538

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
  }
}

Upvotes: 3

Related Questions