궁금한게 많은 개발자 노트

[ IaC ] Terraform init -reconfigure vs -migrate-state 본문

DevOps

[ IaC ] Terraform init -reconfigure vs -migrate-state

궁금한게 많은 개발자 2024. 1. 9. 19:40

terraform init: 명령어는 Terraform 구성을 초기화하는 데 사용됩니다. 이 단계에서 Terraform이 작성한 Configuration을 이해하고, provider(aws, gcp, azure, local, etc)들이 필요한 플러그인과 모듈을 registry로 부터 다운로드합니다.또한, .terraform 디렉토리를 생성하여 이전에 다운로드한 리소스를 캐시합니다

https://developer.hashicorp.com/terraform/language/settings/backends/configuration

 

Backend Configuration - Configuration Language | Terraform | HashiCorp Developer

Use the `backend` block to control where Terraform stores state. Learn about the available state backends, the backend block, initializing backends, partial backend configuration, changing backend configuration, and unconfiguring a backend.

developer.hashicorp.com

 

terraform을 사용하여 infrastructure를 provisioning하는 과정에서 중요한 것은 AWS(CSP)상의 실제 인프라와 Backend에 저장된 staste(tfstate)가 100% 일치하도록 만드는 것입니다. 그래서 현재 생성한 configuration상태를 저장하는 .tfstate를 .terraform디렉토리에 저장하게 됩니다. (local 또는 원격) 이를 통해 여러 개발자가 작업한 것의 sync를 맞출 수 있습니다.

 

 

이 때, 보안의 목적이나 여러 작업자가 .tfstate를 원활하게 공유하기 위해서 AWS S3 bucket에 .tfstate를 저장하고 공유하기도 합니다. 이럴 때에 local에 있는 .tfstate를 원격 저장소로 옮기고, 앞으로의 상태 저장은 해당 원격 저장소에서 관리한다는 것을 명시해주는 것이 필요할 것입니다.

또, 실제 생성된 인프라 구성과 tfstate의 싱크가 맞지 않는 경우 실제 인프라를 기반으로 tfstate를 변경하거나 tfstate를 기반으로 인프라를 변경하고 싶을 수가 있습니다.

이럴 때 사용하는 것이 terraform import도 있을 수 있지만 terraform init의 옵션인 -reconfigure와 -migrate-state입니다.

 

Backend Initialization
During init, the root configuration directory is consulted for backend configuration and the chosen backend is initialized using the given configuration settings.
Re-running init with an already-initialized backend will update the working directory to use the new backend settings. Either -reconfigure or -migrate-state must be supplied to update the backend configuration.

 

https://developer.hashicorp.com/terraform/cli/commands/init

 

Command: init | Terraform | HashiCorp Developer

The terraform init command initializes a working directory containing configuration files and installs plugins for required providers.

developer.hashicorp.com

 

 

-reconfigure 옵션은 현재 존재하는 working directory의 configuration을 완전히 무시하고, backend-block에 명시된 설정으로 re-initalize하는 것을 의미합니다. 이것은 .terraform sub-directory를 제거하고, 다시 terraform init을 진행하는 것과 동일할 수 있습니다. 하지만, 차이점은 .terraform sub-directory를 제거하게 된다면 기존 working directory information을 모두 버리게 되는 것입니다. 주로, local로 설정된 backend를 앞으로는 원격에서 관리하겠다라고 선언할 때 -reconfigure -backend-conf=dev.conf등의 옵션을 통해 사용합니다.

 

반대로 -migrate-state는 새로운 backend를 현재 configuration으로 reconfiguration하는 것을 의미합니다. backend를 현재 존재하는 state로 업데이트 하기를 시도하며, 이 과정에서 생기는 변화들로 인해 interactive prompt가 migration을 할 것인지 물을 수 있습니다. -force-copy옵션을 함께 사용한다면 모든 질문에 대한 대답을 'yes'로 처리할 수 있습니다.

 

Terraform을 사용하면서 현재 state를 유지 해야 할 때도, 또 새로운 상태로 업데이트 해야할 때도 잧은 것 같습니다. 이럴 대 위 옵션들을 적절히 사용한다면 인프라를 구축하는 것에 도움이 될 것 같습니다.

Comments