[Terraform docs : AWS] 06. Define Input Variable

박종배·2023년 1월 21일
0
post-thumbnail

서론

아래에 글은 공식문서를 공부하며 정리한 내용입니다.

참고


배경과 목표

이제 유용한 구성을 생성할 수 있는 충분한 Terraform 지식이 있지만 지금까지의 예시에서는 하드 코딩된 값을 사용했었음. Terraform 구성에는 구성을 보다 동적이고 유연하게 만드는 변수가 포함될 수 있으므로 이를 알아보자.

전제

이 문서의 이전 단계 수행.

인스턴스 이름을 변수로 설정하기

현재 구성에는 여러 하드 코딩된 값이 포함되어 있음. Terraform 변수를 사용하면 유연하고 재사용하기 쉬운 구성을 작성할 수 있음.

EC2 인스턴스 이름을 정의하는 변수를 추가하자.

instance_name 변수를 정의하는 variable 블록이 있는 variables.tf라는 새 파일을 만들자.

variables.tf

variable "instance_name" {
    description = "Value of the Name tag for the EC2 instance"
    type = string
    default = "ExampleAppServerInstance"
}
  • Terraform은 .tf로 끝나는 현재 디렉터리의 모든 파일을 로드하므로 원하는 대로 구성 파일의 이름을 지정할 수 있음.

main.tf에서 새 변수를 사용하도록 aws_instance 리소스 블록을 업데이트하자. 다른 값을 선언하지 않는 한 instance_name 변수 블록은 기본값("ExampleAppServerInstance")으로 기본 설정됨.

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

  required_version = ">= 1.2.0"
}

provider "aws" {
  region  = "ap-northeast-2"
  profile = "learning-terraform"
}

resource "aws_instance" "app_server" {
  ami           = "ami-035233c9da2fabf52"
  instance_type = "t2.micro"

  tags = {
    **# Name = "ExampleAppServerInstance"
    Name = var.instance_name**
  }
}
  • 변수의 접근은 var로 시작함.

작성한 conf를 apply 하기

$ terraform apply

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
following symbols:
  + create

Terraform will perform the following actions:

  # aws_instance.app_server will be created
  + resource "aws_instance" "app_server" {
      + ami                                  = "ami-035233c9da2fabf52"
...
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_instance.app_server: Creating...
aws_instance.app_server: Still creating... [10s elapsed]
aws_instance.app_server: Still creating... [20s elapsed]
aws_instance.app_server: Still creating... [30s elapsed]
aws_instance.app_server: Creation complete after 32s [id=i-0258ef94469904c3a]

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

이제 구성을 다시 apply하자. 이번에는 -var 플래그를 사용하여 변수를 전달하여 기본 인스턴스 이름을 재정의하자. Terraform은 인스턴스의 이름 태그를 새 이름으로 업데이트하게 됨. 프롬프트에 yes로 응답하자.

$ terraform apply -var "instance_name=YetAnotherName"
aws_instance.app_server: Refreshing state... [id=i-0258ef94469904c3a]

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
following symbols:
  ~ update in-place

Terraform will perform the following actions:

  # aws_instance.app_server will be updated in-place
  ~ resource "aws_instance" "app_server" {
        id                                   = "i-0258ef94469904c3a"
      ~ tags                                 = {
          ~ "Name" = "ExampleAppServerInstance" -> "YetAnotherName"
        }
      ~ tags_all                             = {
          ~ "Name" = "ExampleAppServerInstance" -> "YetAnotherName"
        }
        # (29 unchanged attributes hidden)

        # (7 unchanged blocks hidden)
    }

Plan: 0 to add, 1 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_instance.app_server: Modifying... [id=i-0258ef94469904c3a]
aws_instance.app_server: Modifications complete after 1s [id=i-0258ef94469904c3a]

Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
  • 명령줄을 통해 변수를 설정하면 해당 값이 저장되지 않음. Terraform은 변수를 사용하고 설정하는 다양한 방법을 지원하므로 명령을 실행할 때 변수를 반복적으로 입력하지 않아도 됨. 자세히 내용은 여기를 참고하자.

확인

이제 삭제하자.

$ terraform destroy
profile
기록하는 엔지니어 되기 💪

0개의 댓글