<1> 테라폼 블록 테라폼 버전이나 프로바이더 버전과 같은 값들은 자동으로 설정되지만, 함께 작업할 때는 버전을 명시적으로 선언하고 필요한 조건을 입력하여 실행 오류를 최소화 mkdir 03 cd 03 # 현재 버전 정보 확인 terraform version Terraform v1.5.2 // 1.0 이하로 설정 해보자. 지금 버전은 1.5.2 이다. vi main.tf terraform { required_version = "< 1.0.0" } resource "local_file" "abc" { content = "abc!" filename = "${path.module}/abc.txt" } # 실행 결과는? terraform init ... 에러. 나는 1.5라 에러남. [root@myeks2-bastion-EC2 03]# terraform init Initializing the backend... ╷ │ Error: Unsupported Terraform Core version │ │ on main.tf line 3, in terraform: │ 3: required_version = "< 1.0.0" │ │ This configuration does not support Terraform version 1.5.2. To proceed, either choose another supported Terraform version │ or update this version constraint. Version constraints are normally set for good reason, so updating the constraint may │ lead to other errors or unexpected behavior. ╵ 2 수정 1.0 이상 terraform { required_version = ">= 1.0.0" } resource "local_file" "abc" { content = "abc!" filename = "${path.module}/abc.txt" } # 실행 결과는? terraform init 성공 [root@myeks2-bastion-EC2 03]# terraform init Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/local... - Installing hashicorp/local v2.4.0... - Installed hashicorp/local v2.4.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! <2> 프로바이더 버전 블럭 1 https://registry.terraform.io/browse/providers 사용하고자 하는 프로바이더 클릭 예) HashiCorp 오른쪽위 use provider 클릭하여 설정법 보면 된다. 버전도 확인하자. 2.4.0 2 프로바이더 버전을 100으로 지정 에러 난다. terraform { required_version = ">= 1.0.0" required_providers { local = { source = "hashicorp/local" version = ">=100.0.0" } } } resource "local_file" "abc" { content = "123!" filename = "${path.module}/abc.txt" } # 실행 결과는? terraform init -upgrade 에러 Initializing the backend... Initializing provider plugins... - Finding hashicorp/local versions matching ">= 100.0.0"... ╷ │ Error: Failed to query available provider packages │ │ Could not retrieve the list of available versions for provider hashicorp/local: no available releases match the given │ constraints >= 100.0.0 3 2.0 이상으로 변경 terraform { required_version = ">= 1.0.0" required_providers { local = { source = "hashicorp/local" version = ">= 2.0.0" } } } resource "local_file" "abc" { content = "123!" filename = "${path.module}/abc.txt" } # 실행 결과는? terraform init -upgrade 잘됨. <3> 백엔드 블럭 <4> 리소스 블럭 1 mkdir 03-re cd 03-re 2 resource 로 시작한다. resource "<리소스 유형>" "<이름>" { <인수> = <값> } resource "local_file" "abc" { content = "123" filename = "${path.module}/abc.txt" } 3 vi main.tf resource "local_file" "abc" { content = "123" filename = "${path.module}/abc.txt" } resource "aws_instance" "web" { ami = "ami-a1b2c3d4" instance_type = "t2.micro" } // aws언더바로 시작 = aws의 인스턴스이다. // 이름은 테라폼이 구분하는 이름이다. web // { 중괄호 } = 인수의 값 내용 4 # init 시 프로바이더 선언 없이도 리소스 추가로 자동 인식된 프로바이더 요구사항과 초기화 terraform init tree .terraform 프로바이더 지정을 안하더라도. 리소스 다음에 프로바이더가 나온다. 그래서 관련 라이블러리가 다운 로드 된다. 5 로컬로 다 바꿈. resource "local_file" "abc" { content = "123!" filename = "${path.module}/abc.txt" } resource "local_file" "def" { content = "456!" filename = "${path.module}/def.txt" } // 동일한 유형이지만 이름을 구분한다. // abc , def 이름으로 구분한다. 6 (VS Code 확장 graphviz 설치) 7 배포 terraform apply -auto-approve 8 확인 ls *.txt abc.txt def.txt terraform state list local_file.abc local_file.def 9 (선택) VS Code 사용시 terraform graph terraform graph > graph-2.dot 10 제거 terraform destroy -auto-approve terraform apply -auto-approve 11 리소스 참조값을 설정해 두 개의 리소스 간 암시적 종속성 부여 resource "local_file" "abc" { content = "123!" filename = "${path.module}/abc.txt" } resource "local_file" "def" { content = local_file.abc.content filename = "${path.module}/def.txt" } terraform apply -auto-approve 생성 순서가 달라진다. 순차적으로 생성된다. abc에 의존된게 def 이다. def만들때 abc 참고한다. 확인 ls *.txt terraform state list [root@myeks2-bastion-EC2 03-re]# ls *.txt abc.txt def.txt [root@myeks2-bastion-EC2 03-re]# terraform state list local_file.abc local_file.def 12 리소스 자체를 depends_on 지정 가능하다. def는 abc만들고 만들어라. resource "local_file" "abc" { content = "123!" filename = "${path.module}/abc.txt" } resource "local_file" "def" { depends_on = [ local_file.abc ] content = "456!" filename = "${path.module}/def.txt" } 13 terraform destroy -auto-approve terraform apply -auto-approve <5> create_before_destroy (bool) = 생성후 삭제 리소스 수정 시 신규 리소스를 우선 생성하고, 기존 리소스를 삭제 1 테라폼은 삭제후 새로 생성한다. (기본) 이뮤터블 이다. 2 mkdir life cd life 3 resource "local_file" "abc" { content = "lifecycle - step 1" filename = "${path.module}/abc.txt" lifecycle { create_before_destroy = false } } 4 # terraform init && terraform plan && terraform apply -auto-approve terraform state list # 파일 내용 확인 cat abc.txt lifecycle - step 1[ 5 컨텐트 내용 수정 resource "local_file" "abc" { content = "lifecycle - step 1111111111111111" filename = "${path.module}/abc.txt" lifecycle { create_before_destroy = false } } 제거후 새로 만든다. 6 # terraform plan && terraform apply -auto-approve ... -/+ destroy and then create replacement Terraform will perform the following actions: # local_file.abc must be replaced -/+ resource "local_file" "abc" { ~ content = "lifecycle - step 1" -> "lifecycle - step 1111111111111111" # forces replacement ... # 파일 내용 확인 cat abc.txt lifecycle - step 11111111111111 7 내용 수정 저장 resource "local_file" "abc" { content = "lifecycle - step 2" filename = "${path.module}/abc.txt" lifecycle { create_before_destroy = true } } true로 변경하고 생성. 만들고 삭제 파일이 삭제 되어 버린다!!! 만든거도 삭제된다. (장애 상태) terraform plan && terraform apply -auto-approve terraform destroy -auto-approve <6> prevent_destroy (bool): 삭제 방지 해당 리소스를 삭제 Destroy 하려 할 때 명시적으로 거부 1 resource "local_file" "abc" { content = "lifecycle - step 3" filename = "${path.module}/abc.txt" lifecycle { prevent_destroy = true } } 2 # terraform plan terraform apply -auto-approve ... │ Error: Instance cannot be destroyed │ │ on main.tf line 1: │ 1: resource "local_file" "abc" { ... 3 cat abc.txt lifecycle - step 3 <7> ignore_changes (list): 리소스 요소에 선언된 인수의 변경 사항을 테라폼 실행 시 무시 ignore_changes 리소스 요소의 인수를 지정해 수정 계획에 변경 사항이 반영되지 않도록 하는 것 1 resource "local_file" "abc" { content = "lifecycle - step 4" filename = "${path.module}/abc.txt" lifecycle { ignore_changes = [] } } 2 terraform apply -auto-approve cat abc.txt lifecycle - step 4 3 resource "local_file" "abc" { content = "lifecycle - step 5" filename = "${path.module}/abc.txt" lifecycle { ignore_changes = [ content ] } } 4 # terraform apply -auto-approve cat abc.txt lifecycle - step 4 변경되지 않음!!! <8> precondition: 리소스 요소에 선언해 인수의 조건을 검증 리소스 생성 이전에 입력된 인수 값을 검증하는 데 사용해 프로비저닝 이전에 미리 약속된 값 이외의 값 또는 필수로 명시해야 하는 인수 값을 검증 1 variable "file_name" { default = "step0.txt" } resource "local_file" "abc" { content = "lifecycle - step 6" filename = "${path.module}/${var.file_name}" lifecycle { precondition { condition = var.file_name == "step6.txt" error_message = "file name is not \"step6.txt\"" } } } 2 # terraform plan local_file.abc: Refreshing state... [id=63cd1a0c571d59f5b4337364e612786cc63c1bb8] Planning failed. Terraform encountered an error while generating this plan. ╷ │ Error: Resource precondition failed │ │ on main.tf line 22, in resource "local_file" "abc": │ 22: condition = var.file_name == "step6.txt" │ ├──────────────── │ │ var.file_name is "step0.txt" │ │ file name is not "step6.txt" ╵ 3 클라우드 인프라의 VM을 생성할 때 내부적으로 검증된 이미지 아이디를 사용하는지 등과 같은 구성을 미리 확인하고 사전에 잘못된 프로비저닝을 실행할 수 없도록 구성할 수 있다. <9> postcondition: Plan과 Apply 이후의 결과를 속성 값으로 검증 프로비저닝 변경 이후 결과를 검증함과 동시에 의존성을 갖는 다른 구성의 변경을 맞는 효과 1 resource "local_file" "abc" { content = "" filename = "${path.module}/step7.txt" lifecycle { postcondition { condition = self.content != "" error_message = "content cannot empty" } } } output "step7_content" { value = local_file.abc.id } 2 # postcondition 조건에 맞지 않아 에러 발생 terraform apply -auto-approve terraform state list cat step7.txt 3 resource "local_file" "abc" { content = "step7 file ok" filename = "${path.module}/step7.txt" lifecycle { postcondition { condition = self.content != "" error_message = "content cannot empty" } } } output "step7_content" { value = local_file.abc.id } 4 terraform apply -auto-approve terraform state list cat step7.txt