terraform 创建 pem 文件

terraform create pem file

我是 terraform 的新手。

我尝试用 aws 制作简单的 terraform 代码。

效果很好。我可以看到 ec2 和安全组 eip。

我想访问实例,但我没有 .pem 文件。

所以我很难连接 ec2。

如何获取.pem文件?

有人可以告诉我吗?

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
}

您可以使用“tls_private_key”创建密钥对,在上传到 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
  }
}