fullmoon's bright IT blog

[T103] 2주차 - 기본 사용 2/3 (1) 데이터소스 ( data) 본문

Cloud/AWS

[T103] 2주차 - 기본 사용 2/3 (1) 데이터소스 ( data)

휘영청 2023. 9. 8. 11:22
728x90

테라폼으로 시작하는 IaC의 도서를 기반으로 작성하였습니다.
 


 
테라폼을 작성하면 보통 main, variable, output으로 크게 작성하는데 나는 테라폼을 배웠어도 늘 어려웠던 부분이 데이터를 따로 뺀다거나 리소스를 따로 뺀다는 부분이 설명이 없어서  너무 아쉬웠다.

나처럼 개념이 하나도 없는 상태로 테라폼을 하면 나중에 데이터를 따로 빼고싶어도 
어떻게 해야할지 모르는 상황이 발생한다.

오늘은 
데이터 소스(1) , 입력변수(2) , 지역값을 알아보려고 한다.
 


1) Data - 데이터소스

데이터 소스는 테라폼으로 정의되지 않은 외부 리소스 또는 저장된 정보를 테라폼 내에서 참조 할 때 사용한다.
데이터 소스 블록은 data로 시작된다. 이후 ‘데이터 소스 유형’을 정의한다. Resource 블록 정의와 유사하다.

 

1-1) 데이터 소스 구성

일단 책에 있는 내용으로 확인해보자

data "local_file" "abc" {
  filename = "${path.module}/abc.txt"
}
  • 데이터 소스 유형은 첫 번째 _를 기준으로 앞은 프로바이더 이름
  • 뒤는 프로바이더에서 제공하는 리소스 유형을 의미한다.
  • 데이터 소스 유형을 선언한 뒤에는 고유한 이름을 붙인다.
  • 리소스의 이름과 마찬가지로 이름은 동일한 유형에 대한 식별자 역할을 하므로 중복될 수 없다.
  • 이름 뒤에는 데이터 소스 유형에 대한 구성 인수들은 { } 안에 선언한다. 인수가 필요하지 않은 유형도 있다
  • 그때에도 { } 는 입력한다.

    [데이터 소스를 정의할 때 사용하는 메타인수]
• depends_on :종속성을 선언하며. 선언된 구성요소와의 생성 시점에 대해 정의
• count:선언된 개수에 따라 여러 데이터 소스를선언
• for_each :m ap 또는 set 타입의 데이터 배열의 값을 기준으로 여러 리소스를 생성
• provider:동일한프로바이더가 다수 정의되어 있는 경우 지정
• life cycle:데이터 소스의 수명주기 관리

 
이것을 알아보기 쉽게, 그리고 데이터 소스를 참조하기 위해서 가져온다면 어떻게 작성해야할지 보여주겠다.

 
[코드 예시]

데이터 소스를 활용해 AWS 가용영역 인수를 정의  하고
리전 내에서 사용 가능한 가용영역 목록 가져와서 사용하기

예제에 있는 aws_availability_zones의 문서를 확인해보자

데이터소스로 가져오기 위한 조건인수 = Arguments /   데이터 소스의 내용 = Attributes
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/availability_zones
 

[도전과제1]

위 리전 내에서 사용 가능한 가용영역 목록 가져오기를 사용하여

VPC 리소스 생성 실습 진행하기 혹은

관련된 데이터 소스를 사용한 실습한 내용을 글로 작성하기

#데이터 소스를 활용하고
data "aws_availability_zones" "available" {
  state = "available"
  region = "ap-northeast-2"
}

#VPC 생성하기
resource "aws_vpc" "example" {
  cidr_block = "10.0.0.0/16" 
  enable_dns_support = true
  enable_dns_hostnames = true

  tags = {
    Name = "hwi-vpc"
  }
}

오프라인 테스트하기

#main.tf
mkdir 3.5 && cd 3.5

테스트를 위해 먼저 만들어준다.

data "local_file" "abc" {
  filename = "${path.module}/abc.txt"
}

데이터 소스 정의 해준다

# 실습 확인을 위해서 abc.txt 파일 생성
echo "t101 study - 2week" > abc.txt

# 
terraform init && terraform plan && terraform apply -auto-approve
terraform state list

# 테라폼 콘솔 : 데이터 소스 참조 확인
echo "data.local_file.abc" | terraform console

파일을 수정해본다.
 
데이터 소스 동작 확인을 위해 main.tf 수정한다

resource "local_file" "abc" {
  content  = "123!"
  filename = "${path.module}/abc.txt"
}

data "local_file" "abc" {
  filename = local_file.abc.filename
}

resource "local_file" "def" {
  content  = data.local_file.abc.content
  filename = "${path.module}/def.txt"
}



[만들어지는 중..]

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create
 <= read (data resources)

Terraform will perform the following actions:

  # data.local_file.abc will be read during apply
  # (depends on a resource or a module with changes pending)
 <= data "local_file" "abc" {
      + content              = (known after apply)
      + content_base64       = (known after apply)
      + content_base64sha256 = (known after apply)
      + content_base64sha512 = (known after apply)
      + content_md5          = (known after apply)
      + content_sha1         = (known after apply)
      + content_sha256       = (known after apply)
      + content_sha512       = (known after apply)
      + filename             = "./abc.txt"
      + id                   = (known after apply)
    }

  # local_file.abc will be created
  + resource "local_file" "abc" {
      + content              = "123!"
      + content_base64sha256 = (known after apply)
      + content_base64sha512 = (known after apply)
      + content_md5          = (known after apply)
      + content_sha1         = (known after apply)
      + content_sha256       = (known after apply)
      + content_sha512       = (known after apply)
      + directory_permission = "0777"
      + file_permission      = "0777"
      + filename             = "./abc.txt"
      + id                   = (known after apply)
    }

  # local_file.def will be created
  + resource "local_file" "def" {
      + content              = (known after apply)
      + content_base64sha256 = (known after apply)
      + content_base64sha512 = (known after apply)
      + content_md5          = (known after apply)
      + content_sha1         = (known after apply)
      + content_sha256       = (known after apply)
      + content_sha512       = (known after apply)
      + directory_permission = "0777"
      + file_permission      = "0777"
      + filename             = "./def.txt"
      + id                   = (known after apply)
    }

Plan: 2 to add, 0 to change, 0 to destroy.
local_file.abc: Creating...
local_file.abc: Creation complete after 0s [id=5f30576af23a25b7f44fa7f5fdf70325ee389155]
data.local_file.abc: Reading...
data.local_file.abc: Read complete after 0s [id=5f30576af23a25b7f44fa7f5fdf70325ee389155]
local_file.def: Creating...
local_file.def: Creation complete after 0s [id=5f30576af23a25b7f44fa7f5fdf70325ee389155]

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

 
terraform state list 로 확인해보고 나서 파일도 확인해보자.
local _ file.def로 생성된 리소스의 def.t x t 파일 내용이 abc .txt의 내용과 같은지 확인

data.local_file.abc
local_file.abc
local_file.def
C:\terraform\03.start\3.5>dir *.txt

Directory of C:\terraform\03.start\3.5

2023-09-08  오후 01:19                 4 abc.txt
2023-09-08  오후 01:19                 4 def.txt
               2 File(s)              8 bytes
# graph 확인
terraform graph > graph.dot

# 테라폼 콘솔 : 데이터 소스 참조 확인
C:\terraform\03.start\3.5> terraform console
> data.local_file.abc.content
"123!"
> exit

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

Command: graph | Terraform | HashiCorp Developer

The terraform graph command generates a visual representation of a configuration or execution plan that you can use to generate charts.

developer.hashicorp.com

terraform graph -draw-cycles | graph.dot -Tsvg > graph.svg

난 그래프 보고싶은데 왜 안나오냐... ㅎㅎㅎ 윈도우 커맨드 열받네!
해결했음 진짜 바보같음 
윈도우 바이너리에 있는 dot 실행파일 

이거 실행해야함...ㅋㅎㅋ

 

C:\terraform\03.start\3.5>"C:\Program Files\Graphviz\bin\dot.exe" -Tsvg graph.dot

짜잔!~

728x90