안녕하세요!
AWS같은 public 클라우드를 작업하다보면 늘 새로운 VPC를 만들어야하고 Subnet을 설정하고, 라우팅테이블로 연결해주고 등등 여러가지 설정작업들이 많은데요, 늘 반복되는 작접을 좀 편하고 빠르고 간단하게 할 수 없을까 생각을 종종 해왔습니다. 
 
바로 이것이 코드로 인프라를 관리한다! IaaC (Infrastructure as a Code)입니다.
 
생성할 인프라구성들을 미리 코드로 만들어놓으면 여러번 콘솔에서 작업할 필요없이 변화되는 수만 조금 수정하여 다시 코드를 실행해 주면 되기 때문에 한결 공수를 줄일 수 있는 혁기적인 방법이죠.
 
이미 이러한 코드들을 위한 다양한 도구들이 존재하는데요
오늘은 이중에서 Terraform 에 대하여 알아보도록 하겠습니다!
 
Terraform(테라폼)이란?
한마디로 정의하자면, HashiCorp에서 제공하는 클라우드 인프라 배포 툴 입니다.
 
보통 배포툴 이라고하면 Ansible이나 Chef를 생각하시는 분들도 많으실텐데요, Ansible이 동일한 환경 배포를 도와준다고 하면 테라폼은 좀더 클라우드 환경에 초첨이 맞춰져 있습니다.
 
대표되는 퍼블릭 클라우드인 AWS, Azure, GCP 뿐만아니라 Kubernetes, Helm등 다양한 플랫폼을 지원해 주고 있습니다.
지원되는 플랫폼 -  https://www.terraform.io/docs/providers/
 
 
Terraform 설치
설치는 
해당링크를 통해 다운로드 받은 후 압축을 풀어주면 됩니다.
간단간단
 
설치 후 cmd창을 통해 확인이 가능합니다.
C:\Users\kyoun>terraform -version
Terraform v0.11.13
 
 
Your version of Terraform is out of date! The latest version
is 0.12.24. You can update by downloading from www.terraform.io/downloads.html
 
 
 
 
 
 
Terraform을 이용하여 AWS인프라 환경을 구축해보자  시리즈 1탄이 VPC를 구성하는 법을 알아보도록 하겠습니다.
 
환경
# local - windows 10
#Terraform version
 
PS C:\terraform> terraform -version
Terraform v0.11.13
 
#1 - AWS IAM 설정
 저희가 사용해야 할 terraform에서 aws에 접근을 하기 위하여 Key 정보가 필요한데요 
Terraform이라는 IAM을 별도로 만들고 Key를 저장해줍니다.
IAM생성은 제가 작성한 AWS 블로그 글을 참고하시면 됩니다
 
  • AWS IAM 메뉴 접속 후 사용할 Terraform User 클릭
 
 
  • 사용할 IAM 이름 선택 후 Security credentials 항목에서 Createa access key를 클릭해줍니다.
 
 
  • access_key와 secret_key 코드를 따로 저장하거나 .csv파일을 저장해줍니다.
나중에 이 키가 쓰이므로 꼭 저장해주세염!
 
 
#2 - Terraform provider
ㅈ ㅏ! 이제 key를 저장했으니 terraform 으로 가볼까요/
지난 시간에 Terraform이 무엇인지 알아보았는데요
저는 AWS위에 인프라환경을 구축할 예정이여서 Terraform이란 친구에게 AWS에서 구축을 원한다라는 정보를 알려주는게 제일 첫번째 순서가 되겠죠?
 
이를 Terraform에서는 provider라고 칭하는데요 다음과 같은 코드로 작성이 됩니다.
# provider default example
# 00.aws.tf
 
provider "aws" {
  access_key = "<AWS Access Key>"
  secret_key = "<AWS Secret Key>"
  region     = "<AWS Region>"
}
 
이를 실질적으로 적용해보면 다음과 같은 형태로 구성이 되어 집니다.
provider "aws" {
  access_key = "**********QJMA5GP***"                     <------- AWS IAM생성시 부여된 access_key
  secret_key = "**************bUZnJjDbRnbiICmY******"     <------- AWS IAM생성시 부여된 secret_key
  region     = "ap-northeast-2"                           <------- 사용할 리전
}
주의할점은 git hub같은 SCM에 업로드하실때 액세스,시크릿 키가 노출될 수 있으니 주의 하셔야 합니다.
저는 테스트 용으로 provider안에 임시로 키 설정을 해 주었지만 실제 키는 외부에 저장하는것을 추천합니다.
이러한 키 설정은 다음편에 계속!
 
 
#3 - VPC 구성
terraform과 aws를 연동해줬으니 이제 기본이 되는 VPC를 만들어봅시다.
# vpc example code
 
 resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"}
다음과 같은 형태의 sample로 코드화가 되는데요 
사용하고자 하는 vpc의 CIDR range를 지정해줍니다.
 
# VPC 구성
# 01.vpc.tf
 
resource "aws_vpc" "test" {
  cidr_block       = "10.100.0.0/16"
 
 
  tags = {
    Name = "kbseo_tf_vpc"
  }
}
tag를 이용하여서 vpc의 이름을 지정해 줄 수 있습니다.
resource같은경우 실제 구성하고자 하는 aws의 resource 타입 (여기서는 aws_vpc가 되겠죠) 뒤에오는 test는 제가 임의로 지정한 이름입니다.
다른 resource같은경우 Hashicorp 문서를 참고 바랍니다~  https://www.hashicorp.com/resources/
 
다음과 같이 vpc를 구성 해 준 뒤 대망의 terraform을 돌려돌려돌려볼까요?
 
 
#4 - terraform init
terraform init이란 선언된 프로바이더를 보고 필요한 플러그인등을 가져옵니다
 
 
PS C:\terraform> terraform init
 
Initializing provider plugins...
- Checking for available provider plugins on https://releases.hashicorp.com...
- Downloading plugin for provider "aws" (2.59.0)...
 
알맞은 플러그인들은 가져온것 같네요!
init후 terraform 버전을 확인해 보면 프로바이더 버젼도 함께 출력되는것을 보실 수 있습니다.
PS C:\terraform> terraform -version
Terraform v0.11.13
+ provider.aws v2.59.0
 
프로바이더의 플러그인을 잘 가져왔으니 이제 terraform을 실행해봅니다.
 
 
#5 - terraform plan / terraform apply
terraform plan같은경우 현재 저희가 뚝딱뚝딱 코드로 만들어 놓은 리소스들을 실제로 프로바이더(aws)에 적용했을 시 테라폼이 어떠한 작업을 수행할 지 보여줍니다.
apply하기 전에 미리 확인하면 좋겠죠 ^.~
 
$ terraform plan
PS C:\terraform> terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.
 
 
 
 
------------------------------------------------------------------------
 
 
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create
 
 
Terraform will perform the following actions:
 
 
  + aws_vpc.test
      id:                               <computed>
      arn:                              <computed>
      assign_generated_ipv6_cidr_block: "false"
      cidr_block:                       "10.100.0.0/16"
      default_route_table_id:           <computed>
      default_security_group_id:        <computed>
      dhcp_options_id:                  <computed>
      enable_classiclink:               <computed>
      enable_classiclink_dns_support:   <computed>
      enable_dns_hostnames:             <computed>
      enable_dns_support:               "true"
      ipv6_association_id:              <computed>
      ipv6_cidr_block:                  <computed>
      main_route_table_id:              <computed>
      owner_id:                         <computed>
      tags.%:                           "1"
      tags.Name:                        "kbseo_tf_vpc"
 
 
 
 
Plan: 1 to add, 0 to change, 0 to destroy.
 
 
------------------------------------------------------------------------
 
 
Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.
실제 테라폼을 구동했을 시 적용되는것을 잘 보여줍니다!
 
자 그럼 이제 적용해볼차례
 
 
$ terraform apply
PS C:\terraform> terraform apply
 
 
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create
 
 
Terraform will perform the following actions:
 
 
  + aws_vpc.main
      id:                               <computed>
      arn:                              <computed>
      assign_generated_ipv6_cidr_block: "false"
      cidr_block:                       "10.100.0.0/16"
      default_network_acl_id:           <computed>
      default_route_table_id:           <computed>
      default_security_group_id:        <computed>
      dhcp_options_id:                  <computed>
      enable_classiclink:               <computed>
      enable_classiclink_dns_support:   <computed>
      enable_dns_hostnames:             <computed>
      enable_dns_support:               "true"
      instance_tenancy:                 "dedicated"
      ipv6_association_id:              <computed>
      ipv6_cidr_block:                  <computed>
      main_route_table_id:              <computed>
      owner_id:                         <computed>
      tags.%:                           "1"
      tags.Name:                        "kbseo_tf_vpc"
 
 
 
 
Plan: 1 to add, 0 to change, 0 to destroy.
 
 
Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.
 
 
aws_vpc.main: Creating...
  arn:                              "" => "<computed>"
  assign_generated_ipv6_cidr_block: "" => "false"
  cidr_block:                       "" => "10.100.0.0/16"
  default_network_acl_id:           "" => "<computed>"
  default_route_table_id:           "" => "<computed>"
  default_security_group_id:        "" => "<computed>"
  dhcp_options_id:                  "" => "<computed>"
  enable_classiclink:               "" => "<computed>"
  enable_classiclink_dns_support:   "" => "<computed>"
  enable_dns_hostnames:             "" => "<computed>"
  enable_dns_support:               "" => "true"
  instance_tenancy:                 "" => "dedicated"
  ipv6_association_id:              "" => "<computed>"
  ipv6_cidr_block:                  "" => "<computed>"
  main_route_table_id:              "" => "<computed>"
  owner_id:                         "" => "<computed>"
  tags.%:                           "" => "1"
  tags.Name:                        "" => "kbseo_tf_vpc"
aws_vpc.main: Creation complete after 2s (ID: vpc-0366a37927f68d179)
 
 
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
 
잘 생성된 것 같아보입니다!
콘솔로 확인해볼까요?
 
 
잘 만들어졌습니다!
 
오늘은 간단하게 terraform 을 이용하여 aws상 vpc를 구성하는것을 살펴보았는데요
사실상 aws상에서 네트워크를 구성하려면 vpc뿐만아니라 subnet, routing table등등 설정해줘야할 사항이 많은데요..
매번 IP대역들을 각각의 tf파일에 적어주면 여러번 구성할때마다 헷갈리실거예요..
(저만 헷갈리시는거 아니죠ㅜㅜ?)
 
그렇기에 이렇게 ip 대역들 같이 매번 변하는 수들을 따로 모아서 tf파일로 관리하는데요
다음시간에는 좀 더 효율적으로 테라폼을 관리하는 법에 대해 알아보겠습니다!
 
 
 

+ Recent posts