📚 IaC/Terraform

[Terraform] Key-Pair 생성 후 EC2 인스턴스 SSH 접속

heywantodo 2023. 7. 3. 14:51
728x90
반응형

[Terraform] Key-Pair 생성 후 EC2 인스턴스 SSH 접속

앞서 테라폼으로 생성했던 EC2 인스턴스들은, Key가 없기때문에 SSH 접속을 할 수가 없었다.

Terraform에는 Key를 사용하거나 Key를 생성하는 방법을 사용하여 SSH 접속을 할 수가 있다. 

 

1. 기존에 있는 Key 사용하기

resource에 key_name을 추가해주면 된다.

나는 기존에 사용하고 있던 key 이름이 test 였기때문에, test로 두었다.

resource "aws_instance" "web" {
  ami                    = "ami-0c9c942bd7bf113a2" #ubuntu 22.04
  instance_type          = "t2.micro"
  vpc_security_group_ids = [aws_security_group.web.id]
  subnet_id              = aws_subnet.subnet_a.id
  key_name               = "test"
    
    user_data = templatefile("userdata.tftpl", {
      server_port = var.server_port
    })

  tags = {
    Name = "tf-ec2"
  }
}

 

Key name은 EC2 콘솔에서 확인할 수 있다.

 

⚠보안그룹에 22번 Port를 열어주는 것도 까먹지 말자

resource "aws_security_group" "web" {
  vpc_id = aws_vpc.vpc.id
  name = var.security_group_name
  description = "Allow HTTP inbound traffics"
  
  ingress {
    description = "SSH from VPC"
    from_port = "22"
    to_port = var.server_port
    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"]
  }
}

 

생성 후 기존 Key로 접속이 잘 되는 모습을 확인할 수 있다. 

 

2. Key 생성해서 사용하기

먼저 bash 명령어로 ssh key를 생성해준다.

$ ssh-keygen -m PEM -f tf-key -N ""

생성을 하고 나면 key가 생긴다.

새로 생성된 Key를 사용하기 위해선 resource를 생성해줘야 한다.

resource "aws_key_pair" "tf-key" {
  key_name   = "tf-key"
  public_key = file("tf-key.pub")
}

resource를 생성한 후 인스턴스 resource에도 식별자를 이용하여 넣어준다.

resource "aws_instance" "web" {
  ami                    = "ami-0c9c942bd7bf113a2" #ubuntu 22.04
  instance_type          = "t2.micro"
  vpc_security_group_ids = [aws_security_group.web.id]
  subnet_id              = aws_subnet.subnet_a.id
  key_name               = aws_key_pair.tf-key.key_name
    
    user_data = templatefile("userdata.tftpl", {
      server_port = var.server_port
    })

  tags = {
    Name = "tf-ec2"
  }
}

생성 후 SSH 접속을 위해선 key에 권한을 줘야한다.

sudo chmod 600 tf-key
ssh -i ./tf-key ubuntu@54.180.151.250

접속 성공 🍀

 

앞으로 SSH 접속이 가능해져 Terraform으로 생성된 인스턴스를 터미널로 관리 할 수 있다. 

 

728x90
반응형