Terraform Console 사용 (with YAML)

신동수·2024년 3월 6일
0

Terraform

목록 보기
4/10

개요

  • Terraform 에서 환경별로 yaml 파일을 만들어 사용하고 있으며, plan 이나 apply 를 사용하지 않고 console 명령을 통해 값을 확인 할 수 있어 본 포스팅을 작성 하였다.

구조

# Terraform tree 구조
.
├── _variables_
│   ├── common-dev.yaml
│   ├── common-prod.yaml
│   ├── common-staging.yaml
│   └── common-test.yaml
├── main.tf
├── output.tf
├── provider.tf
├── s3
│   ├── s3.tf
│   └── variables.tf
├── variables.tf
├── variables.tf
└── vpc
    ├── igw.tf
    ├── nat.tf
    ├── output.tf
    ├── route.tf
    ├── subnet.tf
    ├── varialbes.tf
    └── vpc.tf

기본적인 구조는 위와 같으며 각 서비스를 모듈별로 나누고 main.tf 에서 각 모듈을 호출하여 사용하는 방식으로 사용 예정이다.
yamlencode
위 공식 문서에서 더 자세한 예시를 확인할 수 있고, json 에 대한 예시도 확인할 수 있다.

# _variables_/common-test.yaml
---
env: test
service_name: service
role_arn: arn:aws:iam::Account:role/Role
account: 'Account'
tf_state_s3: s3
tf_state_dynamo: dynamoDB
common_tags:
	Service: service
	Environment: test
	Project: IaC-Terraform

위 yaml 은 테스트를 위한 yaml 이고, 위 구조는 정해진 것이 없기에 사용자의 상황에 맞춰서 수정하며 사용해주면 좋을거 같다.

# ./variables.tf
variable "env" {
	description = "Environment"
	type = string
}

variable "region" {
	description = "region name"
	type = string
	default = "ap-northeast-2"
}

locals {
	# environment 별로 다른 파일 바라보도록 설정
	common_info = yamldecode(file("${path.module}/_variables_/common-${var.env}.yaml"))
	common_tags = local.common_info.common_tags
}

variables.tf 파일의 내용이며, locals 에 대한 내용을 확인하면 common_info, common_tags 값이 있는데 common_info 는 yaml 에 대한 모든 내용, common_tags 는 yaml 에서 common_tags 항목에 대한 값이 있다.

# CLI 에서 값 확인
% terraform console -var="env=test"

-var 의 옵션을 준 이유는 variable 에서 env 의 값을 변수로 받고 __variables__ 폴더에서 각 환경에 맞는 yaml 값을 가져오기 위함이다.

결과

# 결과 확인
% terraform console -var="env=test"
> local.common_info
{
  "account" = "Account"
  "common_tags" = {
    "Environment" = "test"
    "Project" = "IaC-Terraform"
    "Service" = "service"
  }
  "env" = "test"
  "role_arn" = "arn:aws:iam::Account:role/Role"
  "service_name" = "service"
  "tf_state_dynamo" = "dynamoDB"
  "tf_state_s3" = "s3"
}
> local.common_info.common_tags
{
  "Environment" = "test"
  "Project" = "IaC-Terraform"
  "Service" = "service"
}

위 예시처럼 값이 나올 것이다.


다양한 변수 처리를 하는 것은 좋다고 생각한다.
코드의 재사용성이 높아지기에 시간도 단축되고 점점 고도화하며 사용하고 싶다.

profile
조금씩 성장하는 DevOps 엔지니어가 되겠습니다. 😄

0개의 댓글

관련 채용 정보