Cloud Computing & MSA

Linux Terraform 설치

sstdio.h·2019년 10월 21일·조회 8,775

1. 개요

Terraform을 설치하고 AWS Provider를 설정한 뒤, 간단한 VPC와 Subnet, Internet Gateway를 생성해 보는 기록이다. 예제는 Terraform v0.12.12 기준으로 작성되었으며, 당시 실행 결과를 그대로 남긴다.

실습을 따라 할 경우 AWS 리소스가 실제로 생성될 수 있으므로 비용과 권한을 확인하고, 테스트가 끝나면 마지막의 terraform destroy로 정리하는 것이 좋다.


2. 설치 준비

테라폼 설치 파일 및 현재 버전은 https://www.terraform.io/downloads.html 에서 확인한다.

나는 https://releases.hashicorp.com/terraform/0.12.12/terraform_0.12.12_linux_amd64.zip 을 받았다.


3. 설치

$ wget https://releases.hashicorp.com/terraform/0.12.12/terraform_0.12.12_linux_amd64.zip
--2019-10-21 23:27:23--  https://releases.hashicorp.com/terraform/0.12.12/terraform_0.12.12_linux_amd64.zip
Resolving releases.hashicorp.com (releases.hashicorp.com)... 151.101.109.183, 2a04:4e42:15::439
Connecting to releases.hashicorp.com (releases.hashicorp.com)|151.101.109.183|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 16403395 (16M) [application/zip]
Saving to: ‘terraform_0.12.12_linux_amd64.zip’

terraform_0.12.12_linux_amd64.zip                   100%[==================================================================================================================>]  15.64M  58.5MB/s    in 0.3s

2019-10-21 23:27:23 (58.5 MB/s) - ‘terraform_0.12.12_linux_amd64.zip’ saved [16403395/16403395]

$ unzip terraform_0.12.12_linux_amd64.zip
Archive:  terraform_0.12.12_linux_amd64.zip
  inflating: terraform
$ ls -l
total 65620
-rwxr-xr-x 1 ubuntu ubuntu 50789440 Oct 18 18:43 terraform
-rw-rw-r-- 1 ubuntu ubuntu 16403395 Oct 18 18:44 terraform_0.12.12_linux_amd64.zip

압축을 풀면 terraform 실행 파일이 생긴다. 어느 경로에서나 실행하려면 이 파일을 PATH에 포함된 디렉토리로 옮기거나, 현재 디렉토리를 기준으로 실행하면 된다.


4. 버전 확인

$ terraform -v
Terraform v0.12.12

5. AWS 연결

5.1. 작업 디렉토리 생성

이 예제에서는 tf-exam이라는 디렉토리를 생성한다.

$ mkdir tf-exam
$ cd tf-exam

5.2. AWS Provider 설정 파일

tf-exam/aws-provider.tf 파일을 생성한다.

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

예제에서는 구조를 보여 주기 위해 access_key, secret_key 항목을 비워 두었다. 실제 키를 파일에 직접 적어 커밋하면 보안 사고로 이어질 수 있으므로, 실습 환경에서는 키 관리 방식에 주의해야 한다.

5.3. init

작업 디렉토리에서 terraform init을 실행하면 Provider 플러그인과 필요한 초기 파일이 준비된다.

$ terraform init

Initializing the backend...

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "aws" (hashicorp/aws) 2.33.0...

The following providers do not have any version constraints in configuration,
so the latest version was installed.

To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.

* provider.aws: version = "~> 2.33"

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

출력에 나온 것처럼 Provider 버전 제약이 없으면 실행 시점의 최신 호환 버전이 설치될 수 있다. 재현성을 높이려면 프로젝트에서 사용할 Provider 버전을 명시하는 것이 좋다.

5.4. 구조 확인

terraform init이 끝나면 다음과 같은 디렉토리/파일들이 생성된다.

$ ls -la
total 16
drwxrwxr-x  3 ubuntu ubuntu 4096 Oct 21 23:42 .
drwxr-xr-x 10 ubuntu ubuntu 4096 Oct 21 23:41 ..
drwxr-xr-x  3 ubuntu ubuntu 4096 Oct 21 23:42 .terraform
-rw-rw-r--  1 ubuntu ubuntu  147 Oct 21 23:41 aws-provider.tf
$ ls -la .terraform
total 12
drwxr-xr-x 3 ubuntu ubuntu 4096 Oct 21 23:42 .
drwxrwxr-x 3 ubuntu ubuntu 4096 Oct 21 23:42 ..
drwxr-xr-x 3 ubuntu ubuntu 4096 Oct 21 23:42 plugins
$

5.5. Terraform으로 VPC 생성

이제 VPC를 만들어보자.

다음과 같은 vpc.tf 파일을 만들었다.

$ cat vpc.tf
resource "aws_vpc" "stdio-vpc" {
  cidr_block = "10.10.10.0/24"
  tags = {
    Name = "stdio-vpc"
  }
}

resource "aws_subnet" "stdio-subnet-c" {
  vpc_id = "${aws_vpc.stdio-vpc.id}"
  cidr_block = "10.10.10.128/25"
  availability_zone = "ap-northeast-2c"
}

실행 전에 검사를 해보자. terraform plan은 실제 리소스를 만들기 전에 어떤 변경이 일어날지 보여 준다.

$ 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_subnet.stdio-subnet-c will be created
  + resource "aws_subnet" "stdio-subnet-c" {
      + arn                             = (known after apply)
      + assign_ipv6_address_on_creation = false
      + availability_zone               = "ap-northeast-2c"
      + availability_zone_id            = (known after apply)
      + cidr_block                      = "10.10.10.128/25"
      + id                              = (known after apply)
      + ipv6_cidr_block                 = (known after apply)
      + ipv6_cidr_block_association_id  = (known after apply)
      + map_public_ip_on_launch         = false
      + owner_id                        = (known after apply)
      + vpc_id                          = (known after apply)
    }

  # aws_vpc.stdio-vpc will be created
  + resource "aws_vpc" "stdio-vpc" {
      + arn                              = (known after apply)
      + assign_generated_ipv6_cidr_block = false
      + cidr_block                       = "10.10.10.0/24"
      + default_network_acl_id           = (known after apply)
      + default_route_table_id           = (known after apply)
      + default_security_group_id        = (known after apply)
      + dhcp_options_id                  = (known after apply)
      + enable_classiclink               = (known after apply)
      + enable_classiclink_dns_support   = (known after apply)
      + enable_dns_hostnames             = (known after apply)
      + enable_dns_support               = true
      + id                               = (known after apply)
      + instance_tenancy                 = "default"
      + ipv6_association_id              = (known after apply)
      + ipv6_cidr_block                  = (known after apply)
      + main_route_table_id              = (known after apply)
      + owner_id                         = (known after apply)
      + tags                             = {
          + "Name" = "stdio-vpc"
        }
    }

Plan: 2 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를 하면 실행된다.

이제 진짜 생성한다.

$ 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_subnet.stdio-subnet-c will be created
  + resource "aws_subnet" "stdio-subnet-c" {
      + arn                             = (known after apply)
      + assign_ipv6_address_on_creation = false
      + availability_zone               = "ap-northeast-2c"
      + availability_zone_id            = (known after apply)
      + cidr_block                      = "10.10.10.128/25"
      + id                              = (known after apply)
      + ipv6_cidr_block                 = (known after apply)
      + ipv6_cidr_block_association_id  = (known after apply)
      + map_public_ip_on_launch         = false
      + owner_id                        = (known after apply)
      + vpc_id                          = (known after apply)
    }

  # aws_vpc.stdio-vpc will be created
  + resource "aws_vpc" "stdio-vpc" {
      + arn                              = (known after apply)
      + assign_generated_ipv6_cidr_block = false
      + cidr_block                       = "10.10.10.0/24"
      + default_network_acl_id           = (known after apply)
      + default_route_table_id           = (known after apply)
      + default_security_group_id        = (known after apply)
      + dhcp_options_id                  = (known after apply)
      + enable_classiclink               = (known after apply)
      + enable_classiclink_dns_support   = (known after apply)
      + enable_dns_hostnames             = (known after apply)
      + enable_dns_support               = true
      + id                               = (known after apply)
      + instance_tenancy                 = "default"
      + ipv6_association_id              = (known after apply)
      + ipv6_cidr_block                  = (known after apply)
      + main_route_table_id              = (known after apply)
      + owner_id                         = (known after apply)
      + tags                             = {
          + "Name" = "stdio-vpc"
        }
    }

Plan: 2 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.

  Enter a value: yes

aws_vpc.stdio-vpc: Creating...
aws_vpc.stdio-vpc: Creation complete after 2s [id=vpc-097de0b441b01ae64]
aws_subnet.stdio-subnet-c: Creating...
aws_subnet.stdio-subnet-c: Creation complete after 1s [id=subnet-08d8b4839d6c6aa1b]

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

귀차니즘으로 AWS 콘솔 화면 캡처는 하지 않았으나 잘 생성되었다.

한편 권한 문제로 Error: Error creating VPC: UnauthorizedOperation: You are not authorized to perform this operation., Error: error adding tags: error tagging resource (vpc-xxx): UnauthorizedOperation: You are not authorized to perform this operation. Encoded authorization failure message: 같은 에러들이 날 수도 있다. 이 경우에는 현재 사용 중인 AWS 자격 증명에 VPC 생성, Subnet 생성, 태그 추가 권한이 있는지 확인해야 한다.

5.6. Internet Gateway 추가

이번에는 IGW를 추가한다. vpc.tf와 동일 레벨로 아래 내용의 igw.tf를 만들었다.

resource "aws_internet_gateway" "stdio-gateway" {
  vpc_id = "${aws_vpc.stdio-vpc.id}"
  tags = {
    Name = "stdio-gateway"
  }
}

다시 terraform apply를 한다.

$ terraform apply
aws_vpc.stdio-vpc: Refreshing state... [id=vpc-097de0b441b01ae64]
aws_subnet.stdio-subnet-c: Refreshing state... [id=subnet-08d8b4839d6c6aa1b]

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_internet_gateway.stdio-gateway will be created
  + resource "aws_internet_gateway" "stdio-gateway" {
      + id       = (known after apply)
      + owner_id = (known after apply)
      + tags     = {
          + "Name" = "stdio-gateway"
        }
      + vpc_id   = "vpc-097de0b441b01ae64"
    }

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.

  Enter a value: yes

aws_internet_gateway.stdio-gateway: Creating...
aws_internet_gateway.stdio-gateway: Creation complete after 1s [id=igw-0665265de7b6ca3a7]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

5.7. 배포된 자원 삭제

terraform destroy로 삭제할 수 있다. apply와 마찬가지로 삭제될 리소스 목록을 보여 주고, 확인 입력을 받은 뒤 실제 삭제를 진행한다.

$ terraform destroy

실습 후 남아 있는 리소스가 없는지 AWS 콘솔에서도 한 번 확인해 두는 것이 좋다.

댓글 0

로그인 후 댓글을 남길 수 있습니다.

아직 댓글이 없습니다.