Terraform을 사용하여 스토리지 버킷 만들기 및 객체 업로드

이 빠른 시작 가이드에서는 스토리지 버킷을 프로비저닝하고 버킷에 sample_file.txt 객체를 업로드하는 Terraform 구성 파일을 만듭니다. 이 빠른 시작을 완료하려면 Cloud Shell 편집기, Cloud Shell 터미널, Cloud Shell에 사전 설치된 Terraform CLI를 사용합니다.

시작하기 전에

이 빠른 시작을 위해 프로젝트를 설정하려면 다음 단계를 완료하세요.

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. Cloud Storage API 사용 설정

    API 사용 설정

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  7. Cloud Storage API 사용 설정

    API 사용 설정

폴더 구조 및 Terraform 구성 파일 만들기

Terraform 구성 파일과 Cloud Storage에 객체로 업로드할 파일을 만들려면 다음 단계를 수행하세요.

  1. Google Cloud 콘솔에서 Cloud Shell을 활성화합니다.

    Cloud Shell 활성화

    Google Cloud 콘솔 하단에서 Cloud Shell 세션이 시작되고 명령줄 프롬프트가 표시됩니다. Cloud Shell은 Google Cloud CLI가 사전 설치된 셸 환경으로, 현재 프로젝트의 값이 이미 설정되어 있습니다. 세션이 초기화되는 데 몇 초 정도 걸릴 수 있습니다.

  1. Terraform 구성을 적용할 기본 Google Cloud 프로젝트를 설정합니다.
    export GOOGLE_CLOUD_PROJECT=PROJECT_ID
  2. Cloud Shell 터미널에서 홈 디렉터리를 활성 디렉터리로 설정합니다.
    cd
  3. terraform라는 새 폴더를 만듭니다.
    mkdir terraform
  4. Cloud Shell 창의 툴바에서 편집기 열기를 클릭하여 Cloud Shell 편집기를 시작합니다.
  5. 탐색기 창에서 terraform 폴더를 마우스 오른쪽 버튼으로 클릭한 후 새 파일을 클릭합니다.
  6. 파일 이름으로 main.tf를 입력한 다음 확인을 클릭합니다.
  7. 탐색기 창에서 terraform 폴더를 마우스 오른쪽 버튼으로 클릭한 후 새 파일을 클릭합니다.
  8. 파일 이름으로 sample_file.txt를 입력한 다음 확인을 클릭합니다.

Terraform 구성 파일에서 인프라 정의

Terraform 구성 파일에서 프로비저닝할 인프라를 정의하려면 다음 단계를 수행하세요.

  1. Cloud Shell 편집기에서 main.tf 파일을 엽니다.

  2. 다음 샘플을 main.tf 파일에 복사합니다.

    # Create new storage bucket in the US
    # location with Standard Storage
    
    resource "google_storage_bucket" "static" {
     name          = "BUCKET_NAME"
     location      = "US"
     storage_class = "STANDARD"
    
     uniform_bucket_level_access = true
    }
    
    # Upload a text file as an object
    # to the storage bucket
    
    resource "google_storage_bucket_object" "default" {
     name         = "OBJECT_NAME"
     source       = "OBJECT_PATH"
     content_type = "text/plain"
     bucket       = google_storage_bucket.static.id
    }

    다음과 같이 바꿉니다.

    • BUCKET_NAME을 만들려는 버킷의 이름으로 바꿉니다. 예를 들면 my-bucket입니다.

    • OBJECT_NAME을 업로드할 객체의 이름으로 바꿉니다. 이 빠른 시작에서는 sample_file.txt 이름을 입력합니다.

    • OBJECT_PATH를 업로드할 객체의 경로로 바꿉니다. 이 빠른 시작에서는 ~/terraform/sample_file.txt 경로를 입력합니다.

  3. main.tf 파일을 저장합니다.

Terraform 구성 파일이 포함된 작업 디렉터리 초기화

Terraform과 Terraform 구성 파일이 포함된 디렉터리를 초기화하려면 다음 단계를 수행하세요.

  1. Cloud Shell 터미널을 열기 위해 Cloud Shell 편집기의 툴바에서 터미널 열기를 클릭합니다.

  2. Cloud Shell 터미널에서 terraform 폴더를 현재 작업 디렉터리로 설정합니다.

    cd ~/terraform
    
  3. Terraform을 초기화합니다.

    terraform init
    
  4. Cloud Shell을 승인하라는 메시지가 표시되면 승인을 클릭합니다.

    Terraform이 작업 디렉터리를 초기화합니다. 작업 디렉터리가 성공적으로 초기화되면 Terraform에서 다음과 비슷한 출력을 반환합니다.

    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.
    

실행 계획 미리보기

Terraform 실행 계획은 Terraform 구성을 기반으로 하며 Terraform이 Cloud Storage 인프라와 서비스에 적용할 변경사항을 나타냅니다.

Terraform 실행 계획 보기:

terraform plan

출력 예시:

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:

  # google_storage_bucket.static will be created
  + resource "google_storage_bucket" "static" {
      + force_destroy               = false
      + id                          = (known after apply)
      + location                    = "US"
      + name                        = "my-bucket"
      + project                     = "my-project"
      + public_access_prevention    = (known after apply)
      + self_link                   = (known after apply)
      + storage_class               = "STANDARD"
      + uniform_bucket_level_access = true
      + url                         = (known after apply)

      + versioning {
          + enabled = (known after apply)
        }

      + website {
          + main_page_suffix = (known after apply)
          + not_found_page   = (known after apply)
        }
    }

  # google_storage_bucket_object.default will be created
  + resource "google_storage_bucket_object" "default" {
      + bucket         = (known after apply)
      + content_type   = "text/plain"
      + crc32c         = (known after apply)
      + detect_md5hash = "different hash"
      + id             = (known after apply)
      + kms_key_name   = (known after apply)
      + md5hash        = (known after apply)
      + media_link     = (known after apply)
      + name           = "sample_file.txt"
      + output_name    = (known after apply)
      + self_link      = (known after apply)
      + source         = "sample_file.txt"
      + storage_class  = (known after apply)
    }

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

실행 계획에 제안된 변경사항 적용

Terraform 구성 파일의 변경사항을 적용하려면 다음 단계를 수행하세요.

  1. 다음 명령어를 사용하여 실행 계획의 변경사항을 Cloud Storage 인프라에 적용합니다. 변경사항을 적용하면 Terraform이 스토리지 버킷을 만들고 sample_file.txt를 버킷에 업로드합니다.

    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:
    
      # google_storage_bucket.static will be created
      + resource "google_storage_bucket" "static" {
          + force_destroy               = false
          + id                          = (known after apply)
          + location                    = "US"
          + name                        = "my-bucket"
          + project                     = "my-project"
          + public_access_prevention    = (known after apply)
          + self_link                   = (known after apply)
          + storage_class               = "STANDARD"
          + uniform_bucket_level_access = true
          + url                         = (known after apply)
    
          + versioning {
              + enabled = (known after apply)
            }
    
          + website {
              + main_page_suffix = (known after apply)
              + not_found_page   = (known after apply)
            }
        }
    
      # google_storage_bucket_object.default will be created
      + resource "google_storage_bucket_object" "default" {
          + bucket         = (known after apply)
          + content_type   = "text/plain"
          + crc32c         = (known after apply)
          + detect_md5hash = "different hash"
          + id             = (known after apply)
          + kms_key_name   = (known after apply)
          + md5hash        = (known after apply)
          + media_link     = (known after apply)
          + name           = "sample_file.txt"
          + output_name    = (known after apply)
          + self_link      = (known after apply)
          + source         = "sample_file.txt"
          + storage_class  = (known after apply)
        }
    
    Plan: 2 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:
    
  2. yes를 입력하고 Enter 키를 누릅니다.

    성공하면 Terraform에서 다음과 비슷한 출력을 반환됩니다.

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

스토리지 버킷 및 업로드된 객체 보기

Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

버킷으로 이동

sample_file.txt 객체가 포함된 새 버킷이 나타납니다. terraform apply를 실행한 후 리소스를 프로비저닝하는 데 몇 분 정도 걸릴 수 있습니다.

프로젝트 삭제

이 빠른 시작에서 만든 Google Cloud 리소스에 대한 예기치 않은 요금이 청구되지 않도록 하려면 다음 단계별 안내를 완료하여 리소스를 삭제하세요.

  1. Cloud Shell 터미널에서 terraform 폴더를 현재 작업 디렉터리로 설정합니다.

    cd ~/terraform
    
  2. Terraform 구성 파일을 기반으로 만든 Cloud Storage 리소스를 삭제합니다.

    terraform destroy
    
  3. 성공하면 Terraform에서 다음과 비슷한 출력을 반환됩니다.

    Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
      - destroy
    
    Terraform will perform the following actions:
    
      # google_storage_bucket.static will be destroyed
      - resource "google_storage_bucket" "static" {
          - default_event_based_hold    = false -> null
          - force_destroy               = false -> null
          - id                          = "my-bucket" -> null
          - labels                      = {} -> null
          - location                    = "US" -> null
          - name                        = "" -> null
          - project                     = "example-project" -> null
          - public_access_prevention    = "inherited" -> null
          - requester_pays              = false -> null
          - self_link                   = "https://www.googleapis.com/storage/v1/b/cbonnie-bucket-9" -> null
          - storage_class               = "STANDARD" -> null
          - uniform_bucket_level_access = true -> null
          - url                         = "gs://BUCKET_NAME" -> null
        }
    
      # google_storage_bucket_object.default will be destroyed
      - resource "google_storage_bucket_object" "default" {
          - bucket           = "my-bucket" -> null
          - content_type     = "text/plain" -> null
          - crc32c           = "yZRlqg==" -> null
          - detect_md5hash   = "XrY7u+Ae7tCTyyK7j1rNww==" -> null
          - event_based_hold = false -> null
          - id               = "my-bucket-sample_file.txt" -> null
          - md5hash          = "XrY7u+Ae7tCTyyK7j1rNww==" -> null
          - media_link       = "https://storage.googleapis.com/download/storage/v1/b/BUCKET_NAME/o/sample_file.txt?generation=1675800386233102&alt=media" -> null
          - metadata         = {} -> null
          - name             = "sample_file.txt" -> null
          - output_name      = "sample_file.txt" -> null
          - self_link        = "https://www.googleapis.com/storage/v1/b/BUCKET_NAME/o/sample_file.txt" -> null
          - source           = "sample_file.txt" -> null
          - storage_class    = "STANDARD" -> null
          - temporary_hold   = false -> null
        }
    
    Plan: 0 to add, 0 to change, 2 to destroy.
    
    Do you really want to destroy all resources?
      Terraform will destroy all your managed infrastructure, as shown above.
      There is no undo. Only 'yes' will be accepted to confirm.
    
      Enter a value:
    
  4. yes를 입력하고 Enter 키를 누릅니다. 성공하면 Terraform에서 다음과 비슷한 출력을 반환됩니다.

    Destroy complete! Resources: 2 destroyed.
    
  5. Cloud Shell 편집기의 탐색기 창에서 terraform 폴더를 마우스 오른쪽 버튼으로 클릭한 후 삭제를 클릭합니다.

  6. 메시지가 나타나면 확인을 클릭합니다.

  7. 버킷과 객체가 삭제되었는지 확인하려면 Google Cloud 콘솔의 버킷 페이지로 이동합니다.

    버킷으로 이동

다음 단계