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
반응형
'프로그래밍 > 환경구축' 카테고리의 다른 글
젯브레인스(pycharm, injellij 등) 학생 라이센스 받기 - 메일로 안될 경우 (0) | 2024.02.25 |
---|---|
mongodb 설치 (0) | 2023.10.03 |
파이썬 라이브러리 모음집 anaconda 설치 (0) | 2023.08.23 |
WSL로 윈도우에서 리눅스 사용하기 (0) | 2023.08.15 |
ubuntu 20.04에 git 설치하고 push하기(git personal access token 발급받기) (0) | 2022.03.01 |
댓글