본문 바로가기

Infrastructure/Terraform

[Terraform] 원격 상태 저장

Terraform Remote State

이전 장에서는 "Terraform"이 무엇인지 알아보고 기본적인 사용법에 대해서 알아보았다.
이번 장에서는 "원격 상태 저장"에 대해서 알아보도록 한다.
모든 소스 코드는 리포지토리에 올려두었다.


Intro

  • 지금까지 우리가 살펴본 방법은 테스트 및 개발 환경에서 사용하기에는 적합하지만 운영 환경에서 사용하기에는 다소 무리가 있다.
  • 운영 환경에서는 팀 동료가 액세스하여 인프라에서 협업할 수 있도록 상태를 보안 및 암호화로 유지해야 한다.
  • 이러한 환경을 구축하기 위해 사용되는 가장 좋은 방법은 상태에 대한 공유 액세스가 있는 원격 환경에서 "Terraform"을 실행하는 것이다.
  • "Terraform Cloud"를 사용하면 팀이 인프라 변경 사항을 쉽게 버전 확인, 감사 및 협업할 수 있는 방법을 제공한다.
  • "API 토큰" 및 "액세스 키"를 비롯한 변수를 안전하게 저장하고 장기간 실행되는 "Terraform" 프로세스를 위한 안전하고 안정적인 환경을 제공한다.
  • 이번 장에서는 "상태(State)"를 "Terraform Cloud"로 마이그레이션하는 방법에 대해서 살펴본다.

전제 조건(Prerequisites)

  • 이번에는 "이전 장"에서 사용한 코드를 베이스로 "Terraform Cloud"로 마이그레이션해야 하기 때문에 "이전 장"에서 사용한 코드가 필요하다.
  • terraform.init, terraform apply 명령을 입력하여 정상적으로 "Terraform"이 초기화되고 적용되는지 확인해본다.
$ terraform init
Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 4.16"...
- Installing hashicorp/aws v4.27.0...
- Installed hashicorp/aws v4.27.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

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.

$ terraform apply
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
following symbols:
  + create

Terraform will perform the following actions:
#...
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
#...
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
  • 위의 출력처럼 정상적으로 리소스가 생성되었다면 "Terraform"은 AWS EC2 인스턴스를 프로비저닝하고 리소스에 대한 데이터를 "로컬 상태 파일"에 저장하게 된다.

Terraform 클라우드 설정

  • "HashiCorp Cloud Platform" 또는 "Terraform Cloud" 계정이 있는 경우 기존 자격 증명을 사용하여 로그인한다.
  • 만약 계정이 없는 경우 새로운 계정을 생성하여 조직을 만들어야 한다.
  • main.tf 파일의 "Terraform" 구성 블록에 cloud, organization-name을 추가한다.

main.tf

terraform {
  cloud {
    organization = "my-organization-name"
    workspaces {
      name = "my-terraform-cloud-aws-workspace"
    }
  }

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }
}

Terraform 클라우드에 로그인

  • terraform login 명령을 입력하여 "Terraform Cloud"에 로그인한다.
  • 로그인할 때 "Terraform Cloud" 계정을 생성할 때 생성한 API 키를 사용해야 한다.
$ terraform login
Terraform will request an API token for app.terraform.io using your browser.

If login is successful, Terraform will store the token in plain text in
the following file for use by subsequent commands:
    /Users/<USER>/.terraform.d/credentials.tfrc.json

Do you want to proceed?
  Only 'yes' will be accepted to confirm.

  Enter a value:

Terraform 초기화

  • terraform init 명령어를 사용하여 "Terraform"을 초기화하면 구성을 다시 초기화하고 상태 파일을 "Terraform Cloud"로 마이그레이션한다.
$ terraform init

Initializing Terraform Cloud...
Do you wish to proceed?
  As part of migrating to Terraform Cloud, Terraform can optionally copy your
  current workspace state to the configured Terraform Cloud workspace.

  Answer "yes" to copy the latest state snapshot to the configured
  Terraform Cloud workspace.

  Answer "no" to ignore the existing state and just activate the configured
  Terraform Cloud workspace with its existing state, if any.

  Should Terraform migrate your existing state?

  Enter a value: yes


Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v4.17.0

Terraform Cloud has been successfully initialized!

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

If you ever set or change modules or Terraform Settings, run "terraform init"
again to reinitialize your working directory.
  • "Terraform"의 상태 파일이 더 이상 로컬에 저장되지 않으므로 기존에 생성된 로컬의 상태 파일을 삭제한다.
$ rm terraform.tfstate
  • CLI 기반의 워크플로와 함께 "Terraform Cloud"를 사용하는 경우 "Terraform"을 원격으로 실행하거나 로컬 시스템에서 실행하도록 선택할 수 있다.
  • 로컬 시스템에서 실행하는 경우 "Terraform Cloud"는 로컬 시스템에서 "Terraform"을 실행하고, 원격으로 "Terraform Cloud"에 상태 파일을 저장한다.

작업 공간 변수 설정(Set workspace variables)

  • 우리는 terraform init 단계에서 my-terraform-cloud-aws-workspace라는 작업 공간(workspace)를 "Terraform Cloud" 조직에 생성하였다.
  • AWS 공급자를 인증하려면 AWS 자격 증명으로 작업 공간을 구성해야 한다.
  • "Terraform Cloud"에서 my-terraform-cloud-aws-workspace 작업 공간의 변수 페이지의 Workspace VariablesAWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY를 추가하고 SENSITIVE로 설정한다.


구성 적용

  • "Terraform Cloud" 연동이 완료되었으니 terraform apply 명령어를 사용하여 Terraform Cloud에서 실행을 트리거해본다.
$ terraform apply

# ...
No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration
and found no differences, so no changes are needed.
  • 리소스 자체는 변경 사항이 없으므로 변경될 부분이 없다는 문구가 출력된다.
  • 지금까지 "Terraform Cloud"와의 연동으로 "상태값"을 원격에 저장하게 되었다.
  • 이렇게 원격 상태 스토리지를 사용하면 협업이 쉬워지고 상태 및 비밀 정보가 로컬 디스크에 저장되지 않으며, 원격 상태는 사용될 때만 메모리에 로드된다.

참고 자료

'Infrastructure > Terraform' 카테고리의 다른 글

[Terraform] String Functions  (0) 2023.03.15
[Terraform] Numeric Functions  (0) 2023.03.15
[Terraform] 표준 모듈 구조  (0) 2023.01.25
[Terraform] 공급자(Provider) 버전 관리  (0) 2023.01.25
[Terraform] 기본 개념  (0) 2023.01.25