GCP

Terraform Variables

김모우 2023. 3. 14. 22:13
728x90
반응형

variables.tf


Terraform의 변수는 variables.tf를 통해 선언하고 사용한다. 변수 형태는 여러 가지 종류가 있으므로 변수 선언 방식에 대해서 알아보자

## 기본 변수
variable "project" {
  type = string
}

## 배열 형태 변수
variable "region" {
  type    = list(string)
  default = ["asia-northeast1", "asia-northeast2", "asia-northeast3"]
}

## Object 형태 변수
variable "vpc" {
  type = object({
    vpc_name    = string
    ip_cidr_ragne = string
    network = string
  })
}

## Object 형태 변수 - 배열
variable "docker_port" {
  type = list(object({
    internal = number
    external = number
    protocol = string
  }))
  default = [
    {
      internal = 8300
      external = 8300
      protocol = "tcp"
    }
  ]
}

terra-01-vpc.tfvars


  • terraform apply 시 사용할 변수를 미리 파일에 지정하고 해당 파일을 불러와서 main.tf에 실행 시킨다.
  • 실행 방법: terraform apply -var-file="terra-01-vpc.tfvars"
## 기본 변수
project = "mgmt-poc-tf-vpc"

## 배열 형태 변수
region = ["asia-northeast1", "asia-northeast2", "asia-northeast3"]

## Object 형태 변수
vpc = {
  "vpc_name": "terra-01-vpc"
  "ip_cidr_range": "10.100.0.0/24"
  "network": "test-mgmt-poc-tf-vm-01"
}

## Object 형태 변수 - 배열
docker_port = [{
  "internal": "8080"
  "external": "8080"
  "protocol": "tcp"
}]

 

Console 실행

## 기본 변수
terraform apply -var="project=mgmt-poc-tf-vpc"

## 배열 형태 변수
terraform apply -var='region=["asia-northeast1", "asia-northeast2", "asia-northeast3"]'

## Object 형태 변수
terraform apply -var='vpc={"vpc_name":"terra-01-vpc","ip_cidr_range":"10.100.0.0/24","network":"test-mgmt-poc-tf-vm-01"}'

Main.tf

## Provider 선언
provider "google" {
  project = "var.project"
  region = "var.region"
  credentials = "${file("terra-access.json")}"
}

## VPC 생성 예시
resource "google_compute_subnetwork" "terra-vpc-01" {
  name          = var.vpc.vpc_name
  ip_cidr_range = var.vpc.ip_cidr_range
  region        = var.region
  network       = var.vpc.network
}
728x90
반응형

'GCP' 카테고리의 다른 글

Terraform 시작하기  (0) 2023.02.12
GCP Cloud Run  (0) 2023.02.06
Google Cloud Platform for AWS Professionals Labs  (0) 2021.04.15