【입문】 Terraform 프로젝트 설정

AWS 콘솔에서 포치포치가 아니라 코드로 인프라를 관리하는 방법을 배우고 싶었고 학습을 시작했습니다.
이번에는 실제로 Terraform 프로젝트 작성, 공식 튜토리얼에 있는 EC2 인스턴스 작성까지 정리합니다.

준비


  • 공식 페이지
  • AWS, GCP 등 제공업체별로 자습서를 제공합니다.



  • Terraform 실행 환경
  • homebrew 등으로 넣을 수 있습니다.
  • 공식 Docker 컨테이너가 있으므로 이번에는 여기를 사용합니다.



  • 프로젝트 만들기



    일단 간단하게 시험하기 위해, 이하의 구성으로 만듭니다.
    work_dir/
     ├ .env
     ├ docker-compose.yml
     └ src/
       └ main.tf
    

    파일은 각각 아래와 같습니다.
    // AWS credential info
    AWS_ACCESS_KEY_ID =
    AWS_SECRET_ACCESS_KEY =
    

    docker-compose.yml
    version: "3.8"
    services:
      terraform:
        env_file:
          - .env
        image: hashicorp/terraform:light
        volumes:
          - ./src:/app/terraform
        working_dir: /app/terraform
    

    src/main.tf
    terraform {
      required_providers {
        aws = {
          source  = "hashicorp/aws"
          version = "~> 3.44.0"
        }
      }
    }
    
    provider "aws" {
      profile = "default"
      region  = "ap-northeast-1"
    }
    
    resource "aws_instance" "example" {
      ami           = "ami-830c94e3"
      instance_type = "t3.micro"
    
      tags = {
        Name = "ExampleInstance"
      }
    }
    
    src/main.tf 리전, 인스턴스 유형 등을 선호합니다.
    이번에는 ami-830c94e3를 t3.micro 크기의 인스턴스로 도쿄 리전에서 시작하도록 썼습니다.

    명령 실행



    프로젝트를 만든 다음 tf 파일을 만든 후 init 한 번 실행하십시오.
    docker-compose run --rm terraform init
    Creating network "mochimochi-terraform_default" with the default driver
    Creating mochimochi-terraform_terraform_run ... done
    
    Initializing the backend...
    
    Initializing provider plugins...
    
    Terraform has been successfully initialized!
    
    You may now begin working with Terraform. Try running "terraform plan" to see
    any changes that are required for your infrastructure. All Terraform commands
    should now work.
    
    If you ever set or change modules or backend configuration for Terraform,
    rerun this command to reinitialize your working directory. If you forget, other
    commands will detect it and remind you to do so if necessary.
    
    plan 를 실행하여 정의한 내용을 확인할 수 있습니다.
    $ docker-compose run --rm terraform plan
    Creating mochimochi-terraform_terraform_run ... done
    
    An execution plan has been generated and is shown below.
    Resource actions are indicated with the following symbols:
      + create
    
    Terraform will perform the following actions:
    
      # aws_instance.example will be created
      + resource "aws_instance" "example" {
          + ami                          = "ami-830c94e3"
          + arn                          = (known after apply)
          + associate_public_ip_address  = (known after apply)
          + availability_zone            = (known after apply)
          + cpu_core_count               = (known after apply)
          + cpu_threads_per_core         = (known after apply)
          + get_password_data            = false
          + host_id                      = (known after apply)
          + id                           = (known after apply)
          + instance_state               = (known after apply)
          + instance_type                = "t3.micro"
          + ipv6_address_count           = (known after apply)
          + ipv6_addresses               = (known after apply)
          + key_name                     = (known after apply)
          + outpost_arn                  = (known after apply)
          + password_data                = (known after apply)
          + placement_group              = (known after apply)
          + primary_network_interface_id = (known after apply)
          + private_dns                  = (known after apply)
          + private_ip                   = (known after apply)
          + public_dns                   = (known after apply)
          + public_ip                    = (known after apply)
          + secondary_private_ips        = (known after apply)
          + security_groups              = (known after apply)
          + source_dest_check            = true
          + subnet_id                    = (known after apply)
          + tags                         = {
              + "Name" = "ExampleInstance"
            }
          + tenancy                      = (known after apply)
          + vpc_security_group_ids       = (known after apply)
    
          + ebs_block_device {
              + delete_on_termination = (known after apply)
              + device_name           = (known after apply)
              + encrypted             = (known after apply)
              + iops                  = (known after apply)
              + kms_key_id            = (known after apply)
              + snapshot_id           = (known after apply)
              + tags                  = (known after apply)
              + throughput            = (known after apply)
              + volume_id             = (known after apply)
              + volume_size           = (known after apply)
              + volume_type           = (known after apply)
            }
    
          + enclave_options {
              + enabled = (known after apply)
            }
    
          + ephemeral_block_device {
              + device_name  = (known after apply)
              + no_device    = (known after apply)
              + virtual_name = (known after apply)
            }
    
          + metadata_options {
              + http_endpoint               = (known after apply)
              + http_put_response_hop_limit = (known after apply)
              + http_tokens                 = (known after apply)
            }
    
          + network_interface {
              + delete_on_termination = (known after apply)
              + device_index          = (known after apply)
              + network_interface_id  = (known after apply)
            }
    
          + root_block_device {
              + delete_on_termination = (known after apply)
              + device_name           = (known after apply)
              + encrypted             = (known after apply)
              + iops                  = (known after apply)
              + kms_key_id            = (known after apply)
              + tags                  = (known after apply)
              + throughput            = (known after apply)
              + 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.
    
    ------------------------------------------------------------------------
    
    Note: You didn't specify an "-out" parameter to save this plan, so Terraform
    can't guarantee that exactly these actions will be performed if
    "terraform apply" is subsequently run.
    
    apply 를 실행하면 정의한 내용이 적용됩니다.
    $ docker-compose run --rm terraform apply
    
    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.example: Creating...
    aws_instance.example: Still creating... [10s elapsed]
    aws_instance.example: Creation complete after 13s [id=i-056f8b4b8de00beda]
    
    Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
    

    complete라고 표시되었지만 실제로 AWS 콘솔을 보러 가면 인스턴스가 생성되었다고 생각합니다.



    Terraform을 사용하여 AMI에서 안전한 인스턴스를 만들 수있었습니다.
    다른 AWS 리소스의 경우 어떻게 하는지, 또 배우고 게시해 가려고 합니다.

    좋은 웹페이지 즐겨찾기