MONG 기술블로그

테라폼 고도화 - 2 ( Variable ) 본문

Terraform

테라폼 고도화 - 2 ( Variable )

MJHmong 2022. 3. 21. 23:06

Terraform은 HCL 문법을 가진 언어이다. 따라서 언어적 특성을 가지고있으므로 변수를 정의하여 사용할 수 있다.

이때 사용하는 변수를 Terraform Variable이라고 한다.

 

오늘은 테라폼에서 사용하는 언어의 Variable이 어떤것이 있는지 알아보고 이중 string 변수타입의 사용법에 대해 알아보자.

 

변수 타입

- string

- number

- bool

 

자료구조

- list()

- set()

- map()

- object({ = , ...})

- tuple([, ...])

  

금번 실습에서는 string 타입에 대한 Variable만을 사용한다.

이외에 다양한 타입들이 존재하니 더욱 더 자세한 부분은 아래 URL을 참고하여 학습하자.

 

https://www.terraform.io/language/values/variables

 

Input Variables - Configuration Language | Terraform by HashiCorp

Input variables allow you to customize modules without altering their source code. Learn how to declare, define, and reference variables in configurations.

www.terraform.io

 

 

1. 변수를 정의해보자 - variables.tf

변수는 일반적으로 variables.tf 파일에 정의한다.

 

variables.tf

variable access_key {
  type        = string
  description = "description"
}

variable secret_key {
  type        = string
  description = "description"
}


variable s3_name {
  type        = string
  description = "description"
}

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

위 예제에서는 다음의 variables를 정의했다.

 

- acess_key & secret_key : AWS acess_key & secret_key 정보

- s3_name : S3예제에서 사용한 버킷명

- region : 구축할 리전정보

 

 

2.변수에 값을 주입해보자 - terraform.tfvars

정의한 변수에 대한 값은 .tfvars 확장자를 가진 파일을 생성하여 대입한다.

 

terraform.tfvars

s3_name = "mjh-test-s3-bucket"
access_key = "your access key"
secret_key = "your secret key"

 

 

3.변수값을 사용해보자 - var.

각각의 Variable이 사용되는 파일에 var.(dot) 을 이용하여 접근할 수 있다.

 

provider.tf

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.0"
    }
  }
}

# Configure the AWS Provider
provider "aws" {
  region	= var.region
  access_key = var.access_key
  secret_key = var.secret_key
}

 

s3.tf

resource "aws_s3_bucket" "test-s3-bucket" {
  bucket = var.s3_name

  tags = {
    Name        = var.s3_name
  }
}

 

 

'Terraform' 카테고리의 다른 글

테라폼 고도화 - 1 ( Backend )  (0) 2022.03.21
테라폼 기본 명령어 실습  (0) 2022.03.16
테라폼 설치 및 기본 개념  (0) 2022.03.14
Comments