📚 IaC/Terraform

[Terraform] 테라폼 변수와 출력

heywantodo 2023. 6. 20. 09:57
728x90
반응형

[Terraform] 테라폼 변수와 출력

테라폼은 코드 내에서 값들을 저장하고 재사용할 수 있는 매개변수를 사용할 수 있다.

예를 들어, 특정 네트워크 서브넷 또는 인스턴스 유형을 Terraform 모듈의 변수로 정의할 수 있다.

 

이런식으로 변수를 사용하면, 모듈을 사용하는 프로젝트나 환경마다 변수 값을 다르게 지정할 수 있다.

이를 통해 코드의 유연성과 가독성을 높일 수 있다. 

 

Variables

입력 변수 (Input)

모듈의 매개 변수 역할을 한다

사용자는 소스를 편집하지 않고도 동작을 사용자 정의할 수 있음 

함수의 입력 파라미터(인자 값)와 비슷한 개념

 

Input Variables - Configuration Language | Terraform | HashiCorp Developer

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

developer.hashicorp.com

 

출력 값 (Output)

모듈의 반환 값과 같음

함수의 리턴 값과 비슷한 개념

 

Output Values - Configuration Language | Terraform | HashiCorp Developer

Output values are the return values of a Terraform module.

developer.hashicorp.com

 

로컬 값 (Local)

식에 짧은 이름을 할당하기 위한 편리한 기능

함수의 임시 지역 변수와 비슷한 개념

 

Local Values - Configuration Language | Terraform | HashiCorp Developer

Local values assign a name to an expression that can be used multiple times within a Terraform module.

developer.hashicorp.com

 

입력 변수(input) 의 정의 및 활용 

DRY 원칙에 따라 코드가 중복되지 않도록 구성하기에 편리함

variable "NAME" {
  [CONFIG ..]
}
  • description : 입력 변수의 사용 방법을 설명
  • default : 변수의 기본 값, 없으면 테라폼이 대화식으로 물어봄
  • type : 변수의 타입을 지정 (string, number, boolist, map, set, object, tuple)

변수 사용

variable "server_port" {
  description = "The Port the server will use for HTTP requests"
  type = number
}

variable "security_group_name" {
  description = "The Name of the security group"
  type = string
  default = "allow_http"
}

리소스 구성을 변수로 변경 

resource "aws_instance" "web" {
  ami           ="ami-0c9c942bd7bf113a2" #ubuntu 22.04
  instance_type = "t2.micro"
  vpc_security_group_ids = [aws_security_group.web.id]
    
    user_data = <<-EOF
      #!/bin/bash
      sudo apt-get update -y && sudo apt-get install nginx -y
      sudo systemctl enable nginx --now
      echo '<html><h1>hello Terraform</h1></html>' > /usr/share/nginx/html/index.html
      EOF

  tags = {
    Name = "tf-ec2"
  }
}

resource "aws_security_group" "web" {
  name = var.security_group_name
  description = "Allow HTTP inbound traffics"
  
  ingress {
    description = "HTTP from VPC"
    from_port = var.server_port
    to_port = var.server_port
    protocol = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  egress {
    from_port = 0
    to_port = 0
    protocol = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

terraform plan 명령어를 실행하면 server_port를 입력하라는 창이 나타남

SG의 name은 default값을 설정했기 때문에, default 값으로 지정이 된 모습을 볼 수 있음 

SG의 name을 다른 값으로 설정해주고 싶을 땐, apply(plan) 명령어에서 -var 옵션을 사용하면 됨 

terraform apply -var 'security_group_name=[사용 할 이름]'

 

✔ Userdata에서도 변수를 사용 할 수 있다

아래는 Userdata에서 변수를 사용해서 포트를 변경하는 예시

resource "aws_instance" "web" {
  ami           ="ami-0c9c942bd7bf113a2" #ubuntu 22.04
  instance_type = "t2.micro"
  vpc_security_group_ids = [aws_security_group.web.id]
    
    user_data = <<-EOF
      #!/bin/bash
      sudo apt-get update -y && sudo apt-get install nginx -y
      sudo systemctl enable nginx --now
      sudo sed -i "s/listen 80 default_server;/listen ${var.server_port} default_server;/" /etc/nginx/sites-enabled/default
      sudo sed -i "s/listen \[::\]:80 default_server;/listen \[::\]:${var.server_port} default_server;/" /etc/nginx/sites-enabled/default
      sudo systemctl restart nginx 
      echo '<html><h1>hello Terraform Port is ${var.server_port}</h1></html>' | sudo tee /var/www/html/index.nginx-debian.html >/dev/null
      EOF

  tags = {
    Name = "tf-ec2"
  }
}

Good~

 

출력 값(Output) 의 정의 및 활용

NAME은 출력 변수의 이름, Value는 출력하려는 테라폼의 표현식

  • description : 출력 변수에 어떤 유형의 데이터가 포함되어있는지를 알려줌
  • sensitive : 출력을 기록하지 않도록 지시할 수 있음
output "<NAME>" {
  value = <VALUE>
  [CONFIG ...]
}

콘솔에 접속하지 않고도 인스턴스의 IP를 확인할 수 있게 출력해보자

output "public-ip" {
  description = "The Public IP address of the web server"
  value       = aws_instance.web.public_ip
}

output "Private-ip" {
  description = "The Private IP address of the web server"
  value       = aws_instance.web.private_ip
}

instance resource의 식별자로 IP를 가져옴

콘솔에서 IP를 확인 할 필요가 없어서 매우 편함

 

728x90
반응형