다음을 통해 공유


빠른 시작: Terraform을 사용하여 공용 IP 주소로 Azure Container Instance 만들기

Azure Container Instances를 사용하여 Azure에서 서버리스 Docker 컨테이너를 간단하고 빠르게 실행합니다. Azure Kubernetes Service와 같은 풀 컨테이너 오케스트레이션 플랫폼이 필요하지 않을 경우 애플리케이션을 요청 시 컨테이너 인스턴스에 배포합니다. 이 문서에서는 Terraform 을 사용하여 격리된 Docker 컨테이너를 배포하고 공용 IP 주소에서 해당 웹 애플리케이션을 사용할 수 있도록 합니다.

Terraform 을 사용하면 클라우드 인프라의 정의, 미리 보기 및 배포가 가능합니다. Terraform을 사용하여 HCL 구문을 사용하여 구성 파일을 만듭니다. HCL 구문을 사용하면 클라우드 공급자(예: Azure)와 클라우드 인프라를 구성하는 요소를 지정할 수 있습니다. 구성 파일을 만든 후에는 인프라 변경 내용을 배포하기 전에 미리 볼 수 있는 실행 계획을 만듭니다. 변경 내용을 확인하면 실행 계획을 적용하여 인프라를 배포합니다.

이 문서에서는 다음 방법을 알아봅니다.

필수 조건

Terraform 코드 구현

  1. 샘플 Terraform 코드를 테스트하고 실행할 디렉터리를 생성한 후, 그것을 현재 디렉터리로 만드세요.

  2. main.tf라는 파일을 만들고 다음 코드를 삽입합니다.

    resource "random_pet" "rg_name" {
      prefix = var.resource_group_name_prefix
    }
    
    resource "azurerm_resource_group" "rg" {
      name     = random_pet.rg_name.id
      ___location = var.resource_group_location
    }
    
    resource "random_string" "container_name" {
      length  = 25
      lower   = true
      upper   = false
      special = false
    }
    
    resource "azurerm_container_group" "container" {
      name                = "${var.container_group_name_prefix}-${random_string.container_name.result}"
      ___location            = azurerm_resource_group.rg.___location
      resource_group_name = azurerm_resource_group.rg.name
      ip_address_type     = "Public"
      os_type             = "Linux"
      restart_policy      = var.restart_policy
      zones               = var.zone != "" ? [ var.zone ] : null
    
      container {
        name   = "${var.container_name_prefix}-${random_string.container_name.result}"
        image  = var.image
        cpu    = var.cpu_cores
        memory = var.memory_in_gb
    
        ports {
          port     = var.port
          protocol = "TCP"
        }
      }
    }
    
  3. outputs.tf라는 파일을 만들고 다음 코드를 삽입합니다.

    output "container_ipv4_address" {
      value = azurerm_container_group.container.ip_address
    }
    
  4. providers.tf라는 파일을 만들고 다음 코드를 삽입합니다.

    terraform {
      required_version = ">=1.0"
      required_providers {
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~>3.0"
        }
        random = {
          source  = "hashicorp/random"
          version = "~>3.0"
        }
      }
    }
    provider "azurerm" {
      features {}
    }
    
  5. variables.tf라는 파일을 만들고 다음 코드를 삽입합니다.

    variable "resource_group_location" {
      type        = string
      default     = "eastus"
      description = "Location for all resources."
    }
    
    variable "resource_group_name_prefix" {
      type        = string
      default     = "rg"
      description = "Prefix of the resource group name that's combined with a random value so name is unique in your Azure subscription."
    }
    
    variable "container_group_name_prefix" {
      type        = string
      description = "Prefix of the container group name that's combined with a random value so name is unique in your Azure subscription."
      default     = "acigroup"
    }
    
    variable "container_name_prefix" {
      type        = string
      description = "Prefix of the container name that's combined with a random value so name is unique in your Azure subscription."
      default     = "aci"
    }
    
    variable "image" {
      type        = string
      description = "Container image to deploy. Should be of the form repoName/imagename:tag for images stored in public Docker Hub, or a fully qualified URI for other registries. Images from private registries require additional registry credentials."
      default     = "mcr.microsoft.com/azuredocs/aci-helloworld"
    }
    
    variable "port" {
      type        = number
      description = "Port to open on the container and the public IP address."
      default     = 80
    }
    
    variable "cpu_cores" {
      type        = number
      description = "The number of CPU cores to allocate to the container."
      default     = 1
    }
    
    variable "memory_in_gb" {
      type        = number
      description = "The amount of memory to allocate to the container in gigabytes."
      default     = 2
    }
    
    variable "restart_policy" {
      type        = string
      description = "The behavior of Azure runtime if container has stopped."
      default     = "Always"
      validation {
        condition     = contains(["Always", "Never", "OnFailure"], var.restart_policy)
        error_message = "The restart_policy must be one of the following: Always, Never, OnFailure."
      }
    }
    
    variable "zone" {
        type        = string
        description = "The availability zone to deploy the container group into. If not specified, the container group is nonzonal and might be deployed into any zone."
        default     = ""
    }
    
  6. 컨테이너 그룹 영역을 만들려면 변수 값을 zone 배포하려는 논리 가용성 영역으로 설정합니다.

    중요합니다

    영역 컨테이너 그룹은 가용성 영역을 지원하는 지역에서만 사용할 수 있습니다. 지역에서 가용성 영역을 지원하는지 확인하려면 Azure 지역 목록을 참조하세요.

Terraform 초기화

terraform init를 실행하여 Terraform 배포를 초기화합니다. 이 명령은 Azure 리소스를 관리하는 데 필요한 Azure 공급자를 다운로드합니다.

terraform init -upgrade

핵심 사항:

  • -upgrade 매개 변수는 필요한 공급자 플러그 인을 구성의 버전 제약 조건을 준수하는 최신 버전으로 업그레이드합니다.

Terraform 실행 계획 만들기

terraform 계획을 실행하여 실행 계획을 만듭니다.

terraform plan -out main.tfplan

핵심 사항:

  • terraform plan 명령은 실행 계획을 만들지만 실행하지는 않습니다. 대신 구성 파일에 지정된 구성을 만드는 데 필요한 작업을 결정합니다. 이 패턴을 사용하면 실제 리소스를 변경하기 전에 실행 계획이 예상과 일치하는지 확인할 수 있습니다.
  • 선택 사항인 -out 매개 변수를 사용하여 계획의 출력 파일을 지정할 수 있습니다. -out 매개 변수를 사용하면 검토한 계획이 정확하게 적용됩니다.

Terraform 실행 계획 적용

terraform 적용을 실행하여 클라우드 인프라에 실행 계획을 적용합니다.

terraform apply main.tfplan

핵심 사항:

  • 예시 terraform apply 명령은 이전에 terraform plan -out main.tfplan를 실행했다고 가정합니다.
  • -out 매개 변수에 다른 파일 이름을 지정한 경우 terraform apply에 대한 호출에서 동일한 파일 이름을 사용합니다.
  • -out 매개 변수를 사용하지 않은 경우 매개 변수 없이 terraform apply를 호출합니다.

결과 확인

  1. 실행 계획을 적용하면 Terraform이 공용 IP 주소를 출력합니다. IP 주소를 다시 표시하려면 terraform 출력을 실행합니다.

    terraform output -raw container_ipv4_address
    
  2. 브라우저의 주소 표시줄에 샘플의 공용 IP 주소를 입력합니다.

    Azure Container Instances 샘플 페이지의 스크린샷

리소스 정리

Terraform을 통해 만든 리소스가 더 이상 필요하지 않은 경우 다음 단계를 수행합니다.

  1. terraform 계획을 실행하고 플래그를 지정합니다destroy.

    terraform plan -destroy -out main.destroy.tfplan
    

    핵심 사항:

    • terraform plan 명령은 실행 계획을 만들지만 실행하지는 않습니다. 대신 구성 파일에 지정된 구성을 만드는 데 필요한 작업을 결정합니다. 이 패턴을 사용하면 실제 리소스를 변경하기 전에 실행 계획이 예상과 일치하는지 확인할 수 있습니다.
    • 선택 사항인 -out 매개 변수를 사용하여 계획의 출력 파일을 지정할 수 있습니다. -out 매개 변수를 사용하면 검토한 계획이 정확하게 적용됩니다.
  2. terraform을 실행하여 실행 계획을 적용합니다.

    terraform apply main.destroy.tfplan
    

Azure에서 Terraform 문제 해결

Azure에서 Terraform을 사용할 때 발생하는 일반적인 문제 해결

다음 단계