Module
지난 [Terraform 기초 2 - Terraform/Provider] 글에서 그냥 실습으로 vpc, subnet, igw, route, sg, ec2를 생성해보았다.
(https://writestudy.tistory.com/67)
그냥 냅다 resource에 스태틱한 값을 집어 넣어서 이건 재활용이 불가하다.
분리수거도 안된다.
그래서 앞서 학습했던 variable, module 등을 활용해보려고 한다.
├─ main.tf
├─ outputs.tf └─ child ├─ main.tf ├─ outputs.tf └─ variables.tf |
[child module]
- variables.tf
variable "vpc_cidr_block" {
description = "vpc_cidr_block"
type = string
}
variable "pub_sub_cidr" {
description = "pub_sub_cidr_block"
type = string
}
variable "pub_sub_bool" {
description = "pub ip allocate : true/false"
type = bool
}
variable "ec2_ami_name" {
description = "ubuntu/aws_linux"
type = string
}
variable "ec2_ami" {
type = map(string)
default = {
"ubuntu" = "ami-0e9bfdb247cc8de84"
"aws_linux" = "ami-0eddbd81024d3fbdd"
}
}
variable "ec2_ami_type" {
description = "ami type"
type = string
}
variable "server_port" {
description = "http_port"
}
|
- main.tf
# vpc
resource "aws_vpc" "tf_vpc" {
cidr_block = var.vpc_cidr_block
}
# Subnet
resource "aws_subnet" "tf_pub_subnet" {
vpc_id = aws_vpc.tf_vpc.id
cidr_block = var.pub_sub_cidr
map_public_ip_on_launch = var.pub_sub_bool
}
# internet gateway
resource "aws_internet_gateway" "tf_int_gw" {
vpc_id = aws_vpc.tf_vpc.id
}
# route table
resource "aws_route_table" "tf_route" {
vpc_id = aws_vpc.tf_vpc.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.tf_int_gw.id
}
}
# route table 연결
resource "aws_route_table_association" "route_table_association" {
subnet_id = aws_subnet.tf_pub_subnet.id
route_table_id = aws_route_table.tf_route.id
}
# SG
resource "aws_security_group" "tf_sg" {
vpc_id = aws_vpc.tf_vpc.id
name = "tf_sg"
ingress {
from_port = var.server_port
to_port = var.server_port
protocol = "TCP"
cidr_blocks = ["0.0.0.0/0"]
}
}
# Ec2 instance
resource "aws_instance" "tf_web_svr01" {
ami = "$lookup(var.ec2_ami, var.ec2_ami_name)"
instance_type = var.ec2_ami_type
subnet_id = aws_subnet.tf_pub_subnet.id
vpc_security_group_ids = ["${aws_security_group.tf_sg.id}"]
user_data = <<-EOF
#!/bin/bash
echo "Hello, World" > index.html
nohup busybox httpd -f -p "${var.server_port}" &
EOF
}
|
- outputs.tf
output "public_ip" {
value = aws_instance.tf_web_svr01.public_ip
}
|
[root module]
- variables.tf
provider "aws" {
region = "ap-northeast-2"
}
module "child" {
source = "./child"
vpc_cidr_block = "10.0.0.0/16"
pub_sub_cidr = "10.0.1.0/24"
pub_sub_bool = "true"
ec2_ami_name = "ubuntu"
ec2_ami_type = "t2.micro"
server_port = "80"
}
|
- outputs.tf
output "public_ip" {
value = module.child.public_ip
}
|
[결과]
- ec2에 apache 설정을 해놨으므로 정상인지 확인해보자
'네트워크 & 클라우드 > 자동화' 카테고리의 다른 글
Terraform 기초 9.1 - Module (0) | 2022.12.02 |
---|---|
Terraform 기초 8 - Local (0) | 2022.12.02 |
Terraform 기초 7 - Output (0) | 2022.12.01 |
Terraform 기초 6 - Variables (0) | 2022.12.01 |
Terraform 기초 5 - Data Block (0) | 2022.12.01 |