[Terraform docs : AWS] 04. Change Infrastructure

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

서론

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

참고


배경과 목표

이전 튜토리얼에서 Terraform을 사용하여 AWS의 단일 EC2 인스턴스인 첫 번째 인프라를 생성했었음. 이번에는 해당 리소스를 수정하고 Terraform 프로젝트에 변경 사항을 적용하는 방법을 알아보자.

인프라는 지속적으로 변경되는 특징이 있으며 Terraform은 이러한 변화를 관리하는 데 도움이 됨. Terraform conf를 변경하면 Terraform은 desired state에 도달하는 데 필요한 항목만 수정하는 execution plan을 작성함.

프로덕션에서 Terraform을 사용하는 경우, 버전 제어 시스템을 사용하여 구성 파일을 관리하고 Terraform Cloud 또는 Terraform Enterprise와 같은 원격 백엔드에 상태를 저장하는 것이 좋음.

전제

  • 이전 튜토리얼에 이어서 진행한다는 것을 전제함.
  • 아니라면, 아래 항목들을 수행하자.
    • terraform cli v1.2.0+ 설치
    • aws cli 최신버전 설치 및 테스트를 수행할 account에 대한 credential 설정
    • learn-terraform-aws-instance 폴더 생성 및 main.tf 생성
    • main.tf
      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-0c76973fbe0ee100c"
        instance_type = "t2.micro"
      
        tags = {
          Name = "ExampleAppServerInstance"
        }
      }
      • learning-terraform이라는 aws profile을 생성해뒀었음.
      • terraform init하고 terraform apply하기.

Configuration

기존 terraform으로 배포한 인프라 ec2 인스턴스 aws_instance.app_server에 대해 ami를 바꿔보자.

  • ami-035233c9da2fabf52로 바꾸자.

main.tf

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"
  }
}
  • ami 값은 region에 따라 다르다는 것을 주의하자.
  • 여기서 ami가 바꼈으므로 기존 ec2는 지우고 새로운 ec2를 배포하게 됨.

Apply changes

이제 terraform apply로 인프라를 바꿔주자.

$ terraform apply
aws_instance.app_server: Refreshing state... [id=i-0efc99a1991a2ee55]

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
following symbols:
-/+ destroy and then create replacement

Terraform will perform the following actions:

  # aws_instance.app_server must be replaced
-/+ resource "aws_instance" "app_server" {
      ~ ami                                  = "ami-0c76973fbe0ee100c" -> "ami-035233c9da2fabf52" # forces replacement
...
          ~ volume_size           = 8 -> (known after apply)
          ~ volume_type           = "gp2" -> (known after apply)
        }
    }

Plan: 1 to add, 0 to change, 1 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: Destroying... [id=i-0efc99a1991a2ee55]
aws_instance.app_server: Still destroying... [id=i-0efc99a1991a2ee55, 10s elapsed]
aws_instance.app_server: Still destroying... [id=i-0efc99a1991a2ee55, 20s elapsed]
aws_instance.app_server: Still destroying... [id=i-0efc99a1991a2ee55, 30s elapsed]
aws_instance.app_server: Destruction complete after 39s
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-07ff472fe3fed27d9]

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

접두사 -/+는 Terraform이 리소스를 제자리에서 업데이트하는 대신 리소스를 삭제하고 다시 생성함을 의미함. Terraform은 일부 속성을 내부에서 업데이트할 수 있지만(~ 접두사로 표시됨) EC2 인스턴스에 대한 AMI를 변경하려면 다시 생성해야 함. Terraform은 이러한 세부 정보를 처리하고 execution plan은 Terraform이 수행할 작업을 표시함.

또한 execution plan은 AMI 변경으로 인해 Terraform이 인스턴스를 대체하도록 강제하는 것임을 보여줌. 이 정보를 사용하여 필요한 경우 파괴적인 업데이트를 방지하도록 변경 사항을 조정할 수 있음.

다시 한 번 Terraform은 진행하기 전에 실행 계획의 승인을 요청하고 yes라고 대답하여 계획된 단계를 실행하자.

execution plan에서 알 수 있듯이 Terraform은 먼저 기존 인스턴스를 삭제한 다음 그 자리에 새 인스턴스를 생성했음. terraform show를 다시 사용하여 Terraform이 이 인스턴스와 연결된 새 값을 출력하도록 할 수 있음.

$ terraform show
# aws_instance.app_server:
resource "aws_instance" "app_server" {
    ami                                  = "ami-035233c9da2fabf52"
...
        volume_size           = 8
        volume_type           = "gp2"
    }
}

결과 확인

profile
기록하는 엔지니어 되기 💪

0개의 댓글