3 minute read

IaC

코드 형태로 인프라를 작성, 정의, 배포, 업데이트하는 것을 의미

종류

  1. 에드 훅 스크립트
  2. 구성 관리 도구
  3. 서버 템플릿 도구
  4. 서버 프로비전 도구 : Terraform, CloudFormation

CloudFormation

image
image

  • ec2.yml파일 생성
    EC2Instance:
      Type: AWS::EC2::Instance
      Properties:
          ImageId: ami-068a0feb96796b48d  # 내가 생성할 이미지 아이디
          KeyName: cloudcamp  # 내 AWS 키(cloudcamp.rsa)
          InstanceType: t2.micro  # 인스턴스 유형
          SecurityGroups: # 보안 그룹
          - default
          BlockDeviceMappings:
          -
            DeviceName: /dev/sda1
            Ebs:
              VolumeSize: 8   # 크기
    

    image
    나머지는 다 기본설정으로

  • 생성 확인
    image
    image

Terraform

설치

  • 다운로드
    https://www.terraform.io/downloads

  • 환경변수 설정
    테라폼 파일을 C드라이브 밑에 terraform 디렉토리 생성 후 안에 집어 넣는다.
    image

  • 확인
    image
    CMD 명령어에 terraform을 입력해서 명령어들이 출력되면 성공이다.

AWS CLI

설치

  • 다운로드
    https://docs.aws.amazon.com/ko_kr/cli/latest/userguide/getting-started-install.html
    image

  • 설치
    기본설정으로 설치

  • 확인
    image

  • 보안키 받기
    image

  • CLI설정하기 CMD에서

    aws configure
    

    image
    보안키ID
    보안키PW
    지역명

Terraform으로 EC2 생성

  • VsCode 설정
    image

  • tf파일 생성 후 코드 작성
    image
    main.tf ```tf terraform { required_providers { aws = { source = “hashicorp/aws” version = “~> 4.16” } }

    required_version = “>= 1.2.0” }

provider “aws” { region = “ap-northeast-2” }

resource “aws_instance” “app_server” { ami = “ami-068a0feb96796b48d” instance_type = “t2.micro”

tags = { Name = “ExampleAppServerInstance” } }

- 테라폼 초기화<br/>
```shell
terraform init  # main.tf가 있는 디렉토리로 가서
  • 확인
    image

  • 적용
    terraform apply
    

    image
    yes를 입력하면 내 AWS EX2 인스턴스가 생성된다.
    image

  • ec2에 보안그룹 추가하기
    https://registry.terraform.io/providers/hashicorp/aws/latest/docs 을 활용해서
    main.tf ```shell terraform { required_providers { aws = { source = “hashicorp/aws” version = “~> 4.16” } }

    required_version = “>= 1.2.0” }

provider “aws” { region = “ap-northeast-2” }

resource “aws_security_group” “ec2_allow_rule” { ingress { description = “SSH” 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”] }

}

resource “aws_instance” “app_server” { ami = “ami-068a0feb96796b48d” instance_type = “t2.micro” vpc_security_group_ids = [aws_security_group.ec2_allow_rule.id] tags = { Name = “ExampleAppServerInstance” } }

```shell
terraform plan  # 생성가능한지 확인
terraform apply # terraform plan에서 이상이 없으면 실행해준다.
  • 확인
    image
    업데이트된 ec2에 보안그룹이 추가됐다.

변수활용해서 EC2 만들기

같은 디렉토리 안에 변수를 담을 tf파일 생성해준다.
variables.tf

variable "app_server_ami" {
  type = string
  default = "ami-068a0feb96796b48d"
  
}


variable "app_server_type" {
  type = string
  default = "t2.micro"  
}

# 원래 main 안에 있던 변수는 제거해준다.

terraform.tfvars

app_server_ami = "ami-012b9d1d0d2e2c900"
# app_server_type = "t2.micro"
  • 확인
    terraform plan  # 생성가능한지 확인
    terraform apply # terraform plan에서 이상이 없으면 실행해준다.
    

    image

  • 퍼블릭 IP 생성하기
    main.tf
    ## 마지막에 추가 후 apply
    output "app_server_public_ip" {
    description = "aws instance public_ip"
    value = aws_instance.app_server.public_ip
    }
    
  • 확인
    image

VPC

`main.tf’

provider "aws" {
  region  = "ap-northeast-2"
}

resource "aws_vpc" "my-vpc2" {
  cidr_block       = "200.200.0.0/16"
  instance_tenancy = "default"
  enable_dns_hostnames = true #DNS 호스트 네임 활성화
  tags = {
    Name = "my-vpc2"
  }
}
  • 확인
    image

서브넷 생성하기

main.tf 에 추가

resource "aws_subnet" "my2-subnet-1" {
  vpc_id     = aws_vpc.my-vpc2.id
  cidr_block = "200.200.10.0/24"
  availability_zone = "ap-northeast-2a"
  tags = {
    Name = "my2-subnet-1"
  }
}

# 필요한 만큼 추가
  • 확인
    image

게이트웨이 추가

main.tf 에 추가

resource "aws_internet_gateway" "my-gw2" {
  vpc_id = aws_vpc.my-vpc2.id

  tags = {
    Name = "my-gw2"
  }
}
  • 확인
    image

라우팅테이블

## route
resource "aws_default_route_table" "my2-route-table" {
  default_route_table_id = aws_vpc.my-vpc2.default_route_table_id

  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.my-gw2.id # 게이트웨이와 연결
  }

  tags = {
    Name = "my2-route-table"
  }
}

보안그룹

resource "aws_security_group" "ec2_allow_rule2" {
    vpc_id      = aws_vpc.my-vpc2.id
  ingress {
    description = "SSH"
    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"]
  }
  
}

ec2

  • 변수 생성
    variables.tf ```tf variable “app_server_ami” { type = string default = “ami-068a0feb96796b48d”
    }

variable “app_server_type” { type = string default = “t2.micro”
}

variable “my_ec2_keyname” { type = string default = “cloudkey” }

`terraform.tfvars`
```tfvars
app_server_ami = "ami-068a0feb96796b48d"
app_server_type = "t2.micro"
resource "aws_instance" "app_server2" {
  associate_public_ip_address = true  # 퍼블릭 ip
  ami           = var.app_server_ami
  instance_type = var.app_server_type
  vpc_security_group_ids = [aws_security_group.ec2_allow_rule2.id]
  subnet_id = aws_subnet.my2-subnet-1.id  # 서브넷 연결
  key_name = vae.my_ec2_keyname  # key 추가
  tags = {
    Name = "ExampleAppServerInstance"
  }
}

output "app_server_public_ip" {
  description = "aws instance public_ip"
  value = aws_instance.app_server2.public_ip
}
  • 만든 EC2 제거
    terraform destroy
    

모듈

모듈을 사용할 디렉토리를 하나 만들고 그 안에 위에서 만든 Terraform 프로젝트 디렉토리를 집어 넣는다.
image

main.tf

module "module_ec2_1" {
   source = "./vpc" 
   app_server_ami = "ami-09cf633fe86e51bf0"
   app_server_type = "t2.micro"
}