프로젝트/컴파일 설치로 AWS 3-Tier 구축하기(+테라폼)

[Terraform AWS 3Tier 2] Bastion Server 생성

su-mmer 2023. 10. 8. 16:24
728x90

테라폼으로 Bastion Server를 생성하겠습니다.

서버 생성 자체는 어렵지 않았으나 모듈화 할 때 생각할 것이 많아보입니다.

윈도우와 맥을 모두 사용해서 로컬호스트의 이름이 섞여있을 수 있습니다.

 

서버 접속을 위한 키 생성

hh@DESKTOP-4UIU15G:~$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/hh/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/hh/.ssh/id_rsa
Your public key has been saved in /home/hh/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:******** hh@DESKTOP-4UIU15G
The key's randomart image is:
+---[RSA 3072]----+
|                 |
|   o =           |
|    = +  .o      |

키 생성 명령으로 키를 생성합니다.

/home/hh/.ssh.id_rsa 위치에 키가 생성될 것이라고 알려줍니다.

 

hee@MacBookAir terraform-aws-3tier % ls -al ~/.ssh/
total 32
drwxr-xr-x   6 hee  staff   192  9 12 15:50 .
drwxr-x---+ 30 hee  staff   960 10  8 15:30 ..
-rw-------   1 hee  staff  2622  9 12 15:47 id_rsa
-rw-r--r--   1 hee  staff   585  9 12 15:47 id_rsa.pub
-rw-------@  1 hee  staff   828  9 12 15:50 known_hosts
-rw-r--r--@  1 hee  staff    92  9 12 15:50 known_hosts.old

~/.ssh 디렉토리 내에 id_rsa와 id_rsa.pub 키가 생성되었습니다.

id_rsa키가 개인키, id_rsa.pub키가 공개키입니다.

퍼블릭키를 사용하여 AWS에 키를 생성하고, 서버에 접속할 때는 개인키를 사용하여 인증합니다.

 

hee@MacBookAir terraform-aws-3tier % cat ~/.ssh/id_rsa.pub > ssh-key.pub      
hee@MacBookAir terraform-aws-3tier % cat ~/.ssh/id_rsa > ssh-key.pem

키를 좀 더 편리하게 사용하기 위해 키를 사용할 디렉토리 내부로 복사했습니다.

여기서 중요한 점은, 키가 github에 공개되지 않도록 키 이름을 gitignore에 추가해주어야 합니다.

 

이런 구조가 되었습니다.

코드 작성

AWS에서 생성될 이름을 매번 수동 작성하였더니 이름들이 뒤죽박죽이어서 변수를 작성했습니다.

variable "name" {
  type        = string
  default     = "terraform-frog"
  description = "All resources name incloud this value"
}

 

보안그룹 생성

# 보안 그룹
resource "aws_security_group" "sg_bastion" {
  vpc_id = aws_vpc.main.id
  description = "allow 22 port for bastion"
  ingress {  // 인바운드
    from_port = 22
    to_port = 22
    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"]
  }
  tags = {
    Name = "${var.name}-bastion"
  }
}

bastion server를 위한 보안그룹을 생성합니다.

ingress에서 모든 대역에서 22번 포트로의 접근만 허용합니다.

cidr를 모든 대역에서 허용하기보다는 사용할 대역만 지정하는 것이 제일 좋습니다.

egress에서 모든 대역으로 나가는 통신을 허용합니다.

보안그룹의 이름은 변수 설정을 해두었기 때문에 terraform-frog-bastion이 됩니다.

 

# instance
data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-20230918"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }
}

사용할 ami 를 찾아 필터링합니다.

https://cloud-images.ubuntu.com/locator/ec2/

 

Ubuntu Amazon EC2 AMI Finder

Amazon EC2 AMI Locator As Ubuntu cloud images are uploaded and registered on the Amazon EC2 cloud, they are referred to as AMI (Amazon Machine Images). Each AMI is a machine template from which you can instantiate new servers. Each AMI has its own unique I

cloud-images.ubuntu.com

위 사이트로 검색하면 조금 편리합니다.

 

resource "aws_key_pair" "main_key" {
  key_name = "${var.name}-key"
  public_key = file("./ssh-key.pub")
}

resource "aws_eip" "bastion_eip" {
  instance = aws_instance.bastion.id
  tags = {
    Name = "${var.name}-bastion"
  }
}

resource "aws_instance" "bastion" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"
  subnet_id = aws_subnet.public-2c.id
  vpc_security_group_ids = [ aws_security_group.sg_bastion.id ]
  key_name = "${var.name}-key"

  tags = {
    Name = "${var.name}-bastion"
  }
}

서버 접속을 위한 키페어를 생성합니다.

베스천 서버는 외부 접속이 가능해야하므로 EIP도 생성하여 할당합니다.

 

terraform apply 명령으로 리소스 생성 후에 접속을 시도해봅니다.

 

접속이 잘 되었습니다.

728x90