Outsider's Dev Story

Stay Hungry. Stay Foolish. Don't Be Satisfied.
RetroTech 팟캐스트 44BITS 팟캐스트

Terraform 0.12로 테라폼 코드 업그레이드하기

지난 5월 Terraform 0.12가 공개됐다. Terraform 0.12는 HCL 문법이 개선되고 많은 부분이 개선되어서 나오기 전부터 많이 기다리고 있던 버전이다. 가장 크게는 값에 변수를 사용할 때 "${var.example}"처럼 String Interpolation 쓰듯이 써줘야 하는 부분이 그냥 var.example로 쓸 수 있게 되었다. "${var.example}"으로 쓰던게 익숙해 져서 지금은 괜찮은데 처음 Terraform 쓸 때는 왜 문법이 이런가 생각했던 기억이 난다. 0.12의 새 기능은 테라폼 0.12 베타 1 출시 및 개선된 HCL 문법 살펴보기에 잘 정리되어 있다.

리소스가 많진 않지만, 개인적으로 사용하는 AWS 인프라도 Terraform으로 관리하고 있는데 0.11을 계속 쓰고 있었다가 이번에 0.12로 업그레이드 하는 작업을 진행했다. 리소스가 많지 않아서 회사 프로젝트에 비할 바는 아니지만, 코드와 상태 간에 어긋난 부분이 없다면 업그레이드는 어렵지 않게 할 수 있을 것으로 보인다.

Terraform 0.12 업그레이드 사전 점검

Upgrading to Terraform v0.12 문서에 업그레이드 방법이 잘 나와 있다. 업그레이드가 가능한지 점검해 보고 업그레이드를 진행하려면 Terraform 0.11.14+와 Terraform 0.12.x가 모두 필요하다. 나 같은 경우는 Terraform CLI를 최신 버전인 0.12.x로 올리고 terraform 명령어로 사용할 수 있게 해두고 0.11.14+ 버전은 terraform11 명령어로 사용할 수 있게 설치해 두었다.(이 글에서도 terraform11라고 된 부분은 0.11.14+ 버전을 의미한다.)

Terraform 0.11.14부터 terraform 0.12checklist라는 명령어가 추가되었다. 이 명령어를 사용하면 현재 프로젝트를 Terraform의 업그레이드 명령어로 업그레이드 할 수 있는지가 나온다.

$ terraform11 0.12checklist
Looks good! We did not detect any problems that ought to be
addressed before upgrading to Terraform v0.12.

This tool is not perfect though, so please check the v0.12 upgrade
guide for additional guidance, and for next steps:
    https://www.terraform.io/upgrade-guides/0-12.html

업그레이드 전에 작업이 필요한 경우에는 아래와 같이 안내가 나온다.

$ terraform11 0.12checklist
After analyzing this configuration and working directory, we have identified some necessary steps that we recommend you take before upgrading to Terraform v0.12:

- [ ] Upgrade provider "aws" to version 2.27.0 or newer.

  No currently-installed version is compatible with Terraform 0.12. To upgrade, set the version constraint for this provider as follows and then run `terraform init`:

      version = "~> 2.27.0"

Taking these steps before upgrading to Terraform v0.12 will simplify the upgrade process by avoiding syntax errors and other compatibility problems.

이는 사용 중인 AWS 프로바이더가 버전이 맞지 않으니 0.12를 지원하는 버전을 지정한 다음 terraform init을 실행하라는 의미이다. 안내대로 진행한 다음에 다시 실행하면 업그레이드가 가능하다고 나온다.

Terraform 0.12 업그레이드

Terraform 0.12에는 0.12upgrade라는 명령어가 있어서 이를 사용하면 코드를 0.12에 맞게 바꾸어준다. 한꺼번에 변환해주기 때문에 버전을 올릴 때 노가다 작업을 줄이고 쉽게 올릴 수 있다.

$ terraform 0.12upgrade

This command will rewrite the configuration files in the given directory so
that they use the new syntax features from Terraform v0.12, and will identify
any constructs that may need to be adjusted for correct operation with
Terraform v0.12.

We recommend using this command in a clean version control work tree, so that
you can easily see the proposed changes as a diff against the latest commit.
If you have uncommited changes already present, we recommend aborting this
command and dealing with them before running this command again.

Would you like to upgrade the module in the current directory?
  Only 'yes' will be accepted to confirm.

  Enter a value: yes

-----------------------------------------------------------------------------

Upgrade complete!

The configuration files were upgraded successfully. Use your version control
system to review the proposed changes, make any necessary adjustments, and
then commit.

yes를 입력하면 코드 변경이 진행된다. Git 등으로 형상 관리를 하고 있다면 여기서는 코드만 변경한 것이므로 변경이 잘못되었다고 생각하면 코드를 되돌리면 될 일이다. 이상이 없으면 terraform plan을 실행해서 문제가 없는지 확인하면 되고 AWS 프로바이더의 버전이 올라가면서 일부 속성의 기본값이 바뀌거나 하는 부분만 확인해보고 필요하다면 terraform apply하면 된다. 업그레이드를 진행하면 versions.tf 파일이 자동으로 생기며 terraform 블록에서 필수 버전을 0.12 이상으로 지정된다. 어차피 0.11에서는 아예 0.12의 tf 파일을 제대로 읽지 못하므로 버전 강제를 추가하는 것으로 보인다. 나 같은 경우는 필요 없게 느껴져서(혼자 사용하니까) 형상 관리에 추가하진 않았다.

업그레이드는 대부분 이상 없이 되었는데 모듈 쪽에서는 문제를 약간 겪었다. Terraform 모듈이 정의된 디렉터리에서는 실제 인프라와 연결되지 않기 때문에 프로바이더 정보 같은 것이 없고 실제 인프라와의 연결은 해당 모듈을 가져다 사용하는 쪽이다. 처음에는 이를 모르고 모듈 쪽 디렉터리에서 업그레이드를 시도했더니 다음과 같은 오류가 났다.

$ terraform 0.12upgrade

...

Would you like to upgrade the module in the current directory?
  Only 'yes' will be accepted to confirm.

  Enter a value: yes

-----------------------------------------------------------------------------

Error: error resolving providers:

- provider.aws: no suitable version installed
  version requirements: "(any version)"
  versions installed: none

이는 모듈을 가져다 쓰는 곳에서, 즉 프로바이더가 정의된 곳에서 해당 모듈의 경로를 지정해서 업그레이드를 진행하면 된다.

$ terraform 0.12upgrade ../modules/vpc

...

Would you like to upgrade the module in ../modules/vpc?
  Only 'yes' will be accepted to confirm.

  Enter a value: yes

-----------------------------------------------------------------------------

Upgrade complete!

The configuration files were upgraded successfully. Use your version control
system to review the proposed changes, make any necessary adjustments, and
then commit.


변경된 코드

개인 인프라의 소소한 리소스에서 0.12로 업그레이드 하면서 고친 부분을 정리했다.

  • 퍼스트 클래스 표현식이 도입되어 표현식에서 "${}"부분이 제거되었다.

    • "${var.priority}" -> var.priority
  • 원격 상태 참조에서 출력값에 outputs 속성이 추가되어 값을 가져올 때 outputs 부분을 추가했다.
  • "${data.terraform_remote_state.global.logs}" -> data.terraform_remote_state.global.outputs.logs
  • 이전 버전까지는 맵 속성(map attribute) 즉, 리소스에서 key = {}로 정의하는 형태와 중첩 블록 즉, 리소스 내에서 다른 리소스를 정의하는 key {}형태를 상호 교환해서 쓸 수도 있어서 구분이 모호했지만 0.12에서는 둘의 구분이 명확해졌다. 본문에서 키를 사용자가 임의로 쓸 수 있으면 =를 써야 하는 맵 속성이고 키가 미리 정해져 있으면 =없이 써야하는 중첩 블록이다. 이 부분을 규칙에 맞게 고쳐준다.

    • config { } -> config = { }
    • tags { } -> tags = { }
  • 리스트 변수도 []로 감싸줘야 하던 부분이 개선되어 문법에 맞게 리스트를 고쳐야 한다.(아마 이 부분은 0.12upgrade 명령어가 자동으로 고쳐주지 못하고(안의 값이 뭔지 모르므로...) 오류가 나서 직접 고쳤던 것 같다.)
    ["${module.side_effect_vpc.availability_zones}"] -> module.side_effect_vpc.availability_zones
2019/09/18 03:53 2019/09/18 03:53