简体   繁体   中英

AWS, terraform) How to connect to new instance from another instance which created new instance?

I cannot connect to instance2 from instance1 , which creates instance2 by terraform, because instance1 has no key_name.pem, except key_name.pub.

How can I download key_name.pem to the instance1?

Here is what I did:

  1. I created AWS instance 1

  2. generate ssh key

ssh-keygen -t rsa -b 4096 -C "roy" -f "$HOME/.ssh/test_key" -N ""
  1. terraform apply(key resource)
# main.tf
provider "aws"{
    region = "ap-northeast-2"
}

resource "aws_key_pair" "test_key" {
key_name = "test_key"
public_key = "${file("~/.ssh/test_key.pub")}"
}
  1. terraform apply(create instance)
provider "aws"{
    region = "ap-northeast-2"
}
resource "aws_instance" "ec2" {
ami = "ami-06e7b9c5e0c4dd014"
instance_type = "t2.nano"
key_name = "test_key"
tags {
Name = "ec2_instance"
}

You can use user_data when creating instance1 . This can be a regular bash script, in which you create the id_rsa ( key_name.pem ) file for the user ubuntu (if you are using an Ubuntu AMI).

#!/bin/bash

#create id_rsa

echo "[KEY_DATA]" > /home/ubuntu/.ssh/id_rsa
chmod 0600 /home/ubuntu/.ssh/id_rsa

But why do you even need a private key on the instance? Terraform does not need the private key...

Just in case you are using instance1 as SSH bastion: You should use SSH forwarding instead of copying your private key to an instance: Run ssh -A instance1_ip and then ssh instance2_ip from instance one. This way you don't need a private key on instance1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM