본문 바로가기
프로그래밍/환경구축

[Terraform] ec2를 만들어보자(+ 여러 명령어 실행)

by laoching 2025. 4. 1.
728x90
반응형

테라폼을 이용해 aws에 ec2를 만들고 안에 각종 명령어를 실행할 수 있다.

 

이번에 작성한 코드는 아래의 기능들을 가지고 있다.

1. ec2 생성

 - 리전: ap-northeast-2

 - os: ubuntu 24.04

 - name: test_instance

2. keypair 생성

 - name: test_key_pair

3. security group 생성

 - inbound allow : 22/tcp, 8080/tcp 

4. 안에서 여러 명령어 실행

 

그리고 생성한 ec2에 접속하기 위해서는 terraform output을 이용하여 위에 생성한 key를 사용한다.

 - terraform output 명령어 사용

 

provider "aws" {
  region = "ap-northeast-2"  # 원하는 AWS 리전
}

# 키 페어 생성
resource "tls_private_key" "test_key" {
  algorithm = "RSA"
  rsa_bits  = 2048
}

resource "aws_key_pair" "test_key_pair" {
  key_name   = "test_key_pair"
  public_key = tls_private_key.test_key.public_key_openssh
}

# make security group for ssh connect
resource "aws_security_group" "allow_ssh_http" {
  name	= "allow_ssh_http"
  description = "created by terraform, allow ssh and http(8080)"
  vpc_id	= "vpc-02bbd76648ff780eb"

  ingress {
    from_port = 22
    to_port = 22
    protocol = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  ingress {
    from_port = 8080
    to_port = 8080
    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"]
  }
}



# EC2 인스턴스 생성
resource "aws_instance" "test_instance" {
  ami           = "ami-024ea438ab0376a47"  # ubuntu24.04 lts
  instance_type = "t2.micro"  # 원하는 인스턴스 타입을 설정하세요.

  # 생성된 키 페어를 사용
  key_name = aws_key_pair.test_key_pair.key_name

  # select security group
  vpc_security_group_ids = [aws_security_group.allow_ssh_http.id]

  # 사용자 데이터를 통해 Docker 설치
  # 아래 부분에 ec2에서 실행할 명령어를 명시해준다.
  user_data = <<-EOF
    #!/bin/bash
    # 업데이트 및 Docker 설치
    apt-get update -y
    apt-get install -y ca-certificates curl
    install -m 0755 -d /etc/apt/keyrings
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
    chmod a+r /etc/apt/keyrings/docker.asc

  EOF

  tags = {
    Name = "test_terra_instance"
  }
}

# 키 페어의 비공개 키를 출력
output "private_key_pem" {
  value     = tls_private_keytest_key.private_key_pem
  sensitive = true
}

output "instance_id" {
  value = aws_instance.test_instance.id
}

output "public_ip" {
  value = aws_instance.test_instance.public_ip
}

 

 

728x90
반응형

댓글