Terraform

[ Terraform101 Study - 2w ] 반복문(1)

su''@ 2024. 6. 23. 06:32
Terrafrom T101 4기 실습 스터디 게시글입니다.
"테라폼으로 시작하는 IaC" 도서를 참고하여 정리했습니다. 

 

list 형태의 값 목록이나 Key-Value 형태의 문자열 집합인 데이터가 있는 경우 동일한 내용에 대해 테라폼 구성 정의를 반복적으로 하지 않고 관리할 수 있다.

  • count : 반복문, 정수 값만큼 리소스나 모듈을 생성
    • 3.9 디렉터리를 신규 생성 후 열기 → main.tf 파일 생성
    mkdir 3.9 && cd 3.9
    touch main.tf
    
    • 리소스 또는 모듈 블록에 count 값이 정수인 인수가 포함된 경우 선언된 정수 값만큼 리소스나 모듈을 생성하게 된다.
    • count에서 생성되는 참조값은 count.index이며, 반복하는 경우 0부터 1씩 증가해 인덱스가 부여된다.
    • main.tf 파일
    resource "local_file" "abc" {
      count    = 5
      content  = "abc"
      filename = "${path.module}/abc.txt"
    }
    
    output "filecontent" {
      value = local_file.abc.*.content
    }
    
    output "fileid" {
      value = local_file.abc.*.id
    }
    
    output "filename" {
      value = local_file.abc.*.filename
    }
    • 실행 후 확인 : 5개의 파일이 생성되어야 하지만 파일명이 동일하여 결과적으로 하나의 파일만 존재 ← count 사용 시 주의

    #
    terraform init && terraform apply -auto-approve
    terraform state list
    echo "local_file.abc" | terraform console
    echo "local_file.abc[0]" | terraform console
    echo "local_file.abc[4]" | terraform console
    terraform state show 'local_file.abc[0]'
    terraform state show 'local_file.abc[4]'
    ls *.txt
    
    # 
    terraform output
    terraform output filename
    terraform output fileid
    terraform output filecontent
    • main.tf 파일 수정 : count.index 값 추가
    resource "local_file" "abc" {
      count    = 5
      content  = "This is filename abc${count.index}.txt"
      filename = "${path.module}/abc${count.index}.txt"
    }
    
    output "fileid" {
      value = local_file.abc.*.id
    }
    
    output "filename" {
      value = local_file.abc.*.filename
    }
    
    output "filecontent" {
      value = local_file.abc.*.content
    }
    • 실행 후 확인
    #
    terraform apply -auto-approve
    terraform state list
    ls *.txt
    
    echo "local_file.abc" | terraform console
    echo "local_file.abc[0].content" | terraform console
    echo "local_file.abc[4].content" | terraform console
    terraform state show 'local_file.abc[0]'
    terraform state show 'local_file.abc[4]'
    
    # 
    terraform output
    terraform output filename
    terraform output fileid
    terraform output filecontent
    
    # graph 확인 > graph.dot 파일 선택 후 오른쪽 상단 DOT 클릭
    terraform graph > graph.dot

    • 때때로 여러 리소스나 모듈의 count로 지정되는 수량이 동일해야 하는 상황이 있다. 이 경우 count에 부여되는 정수 값을 외부 변수에 식별되도록 구성할 수 있다.
    • main.tf 파일 수정 : list 형태의 배열을 활용한 반복문 동작 구성
    variable "names" {
      type    = list(string)
      default = ["a", "b", "c"]
    }
    
    resource "local_file" "abc" {
      count   = length(var.names)
      content = "abc"
      # 변수 인덱스에 직접 접근
      filename = "${path.module}/abc-${var.names[count.index]}.txt"
    }
    
    resource "local_file" "def" {
      count   = length(var.names)
      content = local_file.abc[count.index].content
      # element function 활용
      filename = "${path.module}/def-${element(var.names, count.index)}.txt"
    }
    • 실행 후 확인 : local_file.abc와 local_file.def는 var.name에 선언되는 값에 영향을 받아 동일한 갯수만큼 생성하게 된다.
      • local_file.def의 경우 local_file.abc와 개수가 같아야 content에 선언되는 인수 값에 오류가 없을 것이므로 서로 참조되는 리소스와 모듈의 반복정의에 대한 공통의 영향을 주는 변수로 관리할 수 있다.
    #
    terraform apply -auto-approve
    terraform state list
    ls *.txt
    diff abc-a.txt abc-b.txt
    diff abc-a.txt def-c.txt
    cat abc-a.txt abc-b.txt abc-c.txt
    cat def-a.txt def-b.txt def-c.txt
    
    echo "local_file.abc" | terraform console
    echo "local_file.abc[0].content" | terraform console
    echo "local_file.abc[2].content" | terraform console
    terraform state show 'local_file.abc[0]'
    terraform state show 'local_file.abc[2]'
    
    # graph 확인 > graph.dot 파일 선택 후 오른쪽 상단 DOT 클릭
    terraform graph > graph.dot
    • count로 생성되는 리소스의 경우 <리소스 타입>.<이름>[<인덱스 번호>], 모듈의 경우 module.<모듈 이름>[<인덱스 번호>]로 해당 리소스의 값을 참조한다.
    • 단, 모듈 내에 count 적용이 불가능한 선언이 있으므로 주의해야 한다.
      • 예를 들어 provider 블록 선언부가 포함되어 있는 경우에는 count 적용이 불가능하다 → provider 분리
      • 또한 외부 변수가 list 타입인 경우 중간에 값이 삭제되면 인덱스가 줄어들어 의도했던 중간 값에 대한 리소스만 삭제되는 것이 아니라 이후의 정의된 리소스들도 삭제되고 재생성된다.