문제
- Ubuntu에 apache(httpd)를 설치하고, index.html 생성(닉네임 출력)하는 userdata를 작성해서 설정 배포 후 웹 접속 - 해당 테라폼 코드(파일)를 작성
- (옵션) userdata 부분은 별도의 파일을 참조할 수 있게 data 블록을 활용할 것 → 아래 링크를 참고해 보자
https://developer.hashicorp.com/terraform/tutorials/provision/cloud-init
Provision infrastructure with Cloud-Init | Terraform | HashiCorp Developer
Deploy preconfigured infrastructure with Terraform using the Cloud-Init tool.
developer.hashicorp.com
이번에는 테라폼을 통해서 간단한 웹 서버를 만들어보겠습니다.
파일은 다음과 같이 구성하였습니다.
main.tf는 다음과 같습니다.
1. main.tf
resource "aws_security_group" "web_sg" {
name_prefix = "web-sg-"
vpc_id = var.vpc_id
ingress {
from_port = 80
to_port = 80
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 = "web-sg"
}
}
resource "aws_instance" "web_server" {
ami = var.ami
instance_type = var.instance_type
key_name = var.key_name
subnet_id = var.subnet_id
vpc_security_group_ids = [aws_security_group.web_sg.id]
user_data = file("${path.module}/userdata.sh")
associate_public_ip_address = true
tags = {
Name = "web-server"
}
depends_on = [aws_security_group.web_sg]
}
aws_instance에 depends_on 옵션을 걸어서 인스턴스가 보안그룹 이후에 만들어지도록 설정하였고,
보안그룹은 단순 80 포트 오픈해 주는 역할을 합니다.
2. output.tf
output "instance_public_ip" {
value = aws_instance.web_server.public_ip
}
출력변수로 받을 public_ip 값입니다.
3. variables.tf
provider "aws" {
region = var.region
}
variable "region" {
default = "ap-northeast-2"
}
variable "instance_type" {
default = "t2.micro"
}
variable "ami" {
description = "Ubuntu AMI ID"
default = "ami-0f0646a5f59758444"
}
variable "key_name" {
description = "Key pair name"
default = "kp-chiyoung4"
}
variable "subnet_id" {
description = "Subnet ID"
default = "subnet-00xxxxxxxxc1cdba6"
}
variable "vpc_id" {
description = "VPC ID"
default = "vpc-xxxxxxxxb1e4414c7"
}
variables.tf에 설정한 값들입니다.
ami는 ubuntu ami이고, 키 이름, 서브넷 id, vpc id 등을 받습니다.
4. userdata.sh
#!/bin/bash
sudo apt-get update
sudo apt-get install -y apache2
echo "Hello, Chi young!" > /var/www/html/index.html
sudo systemctl restart apache2
위의 내용은 userdata.sh 설정을 통해서 호출 시 Hello, Chi young! 을 받는 아파치 웹서버입니다.
리소스를 생성해 줍니다.
리소스가 생성되면, 웹 브라우저를 통해서 접근이 가능합니다!
다음과 같이 확인하실 수 있습니다.
'DevOps > Terraform' 카테고리의 다른 글
[Terraform] 테라폼을 이용한 vpc 배포 (0) | 2024.06.23 |
---|---|
[Terraform] 테라폼으로 서브넷 생성하기 (0) | 2024.06.23 |
[Terraform] 테라폼 lifecycle의 precondition (0) | 2024.06.16 |
[Terraform] 테라폼으로 ec2 배포하기 (0) | 2024.06.16 |
[Terraform] 테라폼이란 (2) | 2024.06.16 |