-
Terraform State
IaC/Terraform 기초 2023. 9. 3. 09:12테라폼의 명령어를 설명하면서 제가 계속해서 강조하는 것이 있는데요.
바로 state 파일!!!
테라폼을 처음 시작하거나 아직 초보단계에서 가장 많이 착각을 하는 것이 이 부분이라 계속해서 강조를 드렸습니다.
테라폼은 실제 클라우드에 어떤 리소스가 있는지는 모른다.
테라폼은 오로지 state 파일로 판단한다.테라폼에서 이 부분을 항상 숙지하고 있으셔야 합니다. 그래서 뭐 이게 어떻다는 거죠? 라고 되물으실 수 있습니다.
바로 이런 특징 때문에 테라폼에서는 duplicate resource 문제가 발생할 수 있습니다.
state 파일이 꼬여서 많은 사람들이 duplicate resource에게 고통받는 중 duplicate resource는 테라폼에서 일반적으로 발생하는 에러 중에 한 유형인데요.
같은 이름을 가진 리소스를 중복해서 만들려고 할 때 발생하는 문제입니다.
테라폼은 state 파일만 바라보는 바보(?)이기 때문에 어떤 리소스를 만든 후에
그 리소스를 만들었다는 state 파일 자체를 삭제하거나 terraform state rm 명령어로 그 기록을 지워버리면
state 파일을 읽은 후에
"그 리소스는 없어! 그러니까 새로 만들어야 해!"
라고 판단하고 같은 이름으로 또 리소스를 만들려고 합니다.
그러면 AWS같은 클라우드는
"그 리소스는 이미 있으니까 만들 수 없어! 이름이 겹친다구!"
라고 친절하게 리소스 생성을 거절합니다.
(가끔씩 불친절한 부분도 있긴 합니다.)여기서 저는 테라폼으로 aws iam role과 policy를 생성한 다음에 의도적으로
terraform state rm aws_iam_policy.cloud_man_lambda_tagging_policy
명령어로 state에서 관리되고 있던 policy를 지워보았습니다.
그리고 다시 terraform apply를 해서 아래와 같은 에러를 발생시켰습니다.
Error: creating IAM Policy (lambda-tagging-sample-policy): EntityAlreadyExists: A policy called lambda-tagging-sample-policy already exists. Duplicate names are not allowed. │ status code: 409, request id: 7e83980f-51f8-4515-be4b-25cf4e3ae4c9 │ │ with aws_iam_policy.cloud_man_lambda_tagging_policy, │ on iam.tf line 1, in resource "aws_iam_policy" "cloud_man_lambda_tagging_policy": │ 1: resource "aws_iam_policy" "cloud_man_lambda_tagging_policy" {
에러 메시지는
"이미 lambda-tagging-sample-policy라는 이름의 policy가 있으니까 중복된 이름으로는 만들수 없어!"
라는 의미입니다.
그럼 이제 terraform state 명령어에 어떤 명령어가 있는지 알아볼까요?
terraform state --help 라고 치면 다음처럼 terraform state 와 관련된 명령어들을 확인할 수 있습니다.
Usage: terraform [global options] state <subcommand> [options] [args] This command has subcommands for advanced state management. These subcommands can be used to slice and dice the Terraform state. This is sometimes necessary in advanced cases. For your safety, all state management commands that modify the state create a timestamped backup of the state prior to making modifications. The structure and output of the commands is specifically tailored to work well with the common Unix utilities such as grep, awk, etc. We recommend using those tools to perform more advanced state tasks. Subcommands: list List resources in the state mv Move an item in the state pull Pull current state and output to stdout push Update remote state from a local state file replace-provider Replace provider in the state rm Remove instances from the state show Show a resource in the state
주요 명령어 위주로 빠르게 살펴보겠습니다.
terraform state list
현재 테라폼 state 파일에서 관리되고 있는 리소스들의 리스트를 보여줍니다.
terraform state pull
현재 적용되고 있는 테라폼 state 파일을 가져와 출력해서 보여줍니다.
terraform state push
만약 로컬에 있는 state파일을 이용해서 여러가지 리소스를 생성/삭제 하다가 현재 상태를 클라우드 storage backend에 저장하고 싶은 경우, 현재 로컬의 state 파일을 backend.tf 로 설정된 클라우드 backend에 저장합니다. github를 아시는 분이라면 git push와 유사한 기능으로 이해하시면 좋을 것 같습니다.
terraform state rm <state에서 지우고 싶은 리소스>
state에서 해당 리소스에 대한 기록을 지웁니다. 단순히 state 파일에서 지워지는 것이고 실제 클라우드에서는 아무런 변화가 없습니다. 그럼 이런 기능은 언제 쓸까요? 더 이상 해당 리소스를 테라폼으로 관리하지 않거나 혹은 이미 클라우드에서 지워진 리소스인데 state에는 남아있는 경우 이 명령어를 활용하여 state에서 삭제하는 것이 가능합니다.terraform state 명령어는 테라폼을 실행하여 state 파일을 수정하는 것이 아닌
직접 state 파일을 수정하는 명령어이기 때문에 매우 신중하게 사용되어야 합니다.
물론 state파일의 backup 파일이 생성되기는 하지만, state 파일이 잘 관리되지 못하면
테라폼을 실행할 때 실제 클라우드의 상태와 state 파일의 차이로 생각지 못한 에러들이 발생할 수 있기 때문입니다.
오늘은 terraform state 파일의 특징과 명령어로 state 파일을 직접 관리하는 방법까지 알아보았습니다.
다음에는 테라폼으로 만들지는 않았지만 이미 클라우드에 있었던 리소스들을
state 파일로 가져오는 terraform import 명령어에 대해서 알아보겠습니다.
'IaC > Terraform 기초' 카테고리의 다른 글
Terraform Provider (0) 2023.09.12 Terraform Apply (0) 2023.09.05 Terraform Plan (0) 2023.09.03 Terraform Init (0) 2023.08.31 Terraform Install (0) 2023.08.31