[Terraform] 테라폼 기본 명령어

민수·2023년 6월 10일
0

실습 환경

  • ubuntu 22.04

init

terraform init [options]

테라폼 구성 파일이 포함된 작업 디렉토리를 초기화 합니다.
이 작업을 실행하는 디렉토리를 루트 모듈이라고 부릅니다.
테라폼에서 사용되는 프로바이더, 모듈 등의 지정된 버전에 맞춰 루트 모듈을 구성하는 역할을 수행합니다.
이 명령어는 테라폼의 구성 파일이나 상태 파일을 삭제하지 않기 때문에 여러 번 실행해도 됩니다.

options

-upgrade

terraform init을 실행 시 작업 당시의 버전 정보를 기입한 .terraform.lock.hcl 파일이 생겨 다른 작업자가 원래 작업자가 사용한 버전을 그대로 사용할 수 있도록 해줍니다.
.terraform.lock.hcl 파일이 있으면 해당 파일에 명시된 버전으로 init을 수행합니다.
tf 파일에 명시한 버전의 최신버전으로 변경하려면 terraform init -upgrade를 수행해야 합니다.

실습

main.tf

resource "local_file" "name" {
  content = "cloudcoke"
  filename = "${path.module}/cloudcoke.txt"
}
terraform init
Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/local...
- Installing hashicorp/local v2.4.0...
- Installed hashicorp/local v2.4.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

Terraform has been successfully initialized!

... 생략

validate

terraform validate [options]

디렉토리에 있는 테라폼 구성 파일의 유효성을 검사합니다.
이 명령어는 테라폼의 remote-state, provider API등과 같은 외부 서버스에 접근하지 않고 오직 구성 파일의 코드적인 유효성만 검토합니다.
API 작업이 발생하는 테라폼 Plan 동작과 달리 작성된 구성의 문법, 종속성, 속성 이름이나 연결된 값의 정확성 확인을 수행합니다.

실습

main.tf

  • 필수 인자를 기입하지 않았을 때
resource "local_file" "name" {
  content = "cloudcoke"
#   filename = "${path.module}/cloudcoke.txt"
}
terraform validate
│ Error: Missing required argument
│ 
│   on main.tf line 1, in resource "local_file" "name":1: resource "local_file" "name" {
│ 
│ The argument "filename" is required, but no definition was found.

main.tf

  • 설정이 올바를 때
resource "local_file" "name" {
  content = "cloudcoke"
  filename = "${path.module}/cloudcoke.txt"
}
terraform validate
Success! The configuration is valid.

plan & apply & destroy

plan

terraform plan [options]

테라폼으로 적용할 인프라의 변경 사항에 관한 실행 계획을 생성 합니다.
출력되는 결과를 확인하여 어떤 변경이 적용되는지 사용자가 검토할 수 있습니다.
plan 명령은 변경 사항이 실제로 적용되지는 않고 적용 전에 예상한 구성이 맞는지 검토하는데 주로 사용합니다.

  • 테라폼 실행 이전의 상태와 비교해 현재 상태가 최신화 되었는지 확인
  • 적용하고자 하는 구성을 현재 상태와 비교하고 변경점을 확인
  • 구성이 적용되는 경우 대상이 테라폼 구성에 어떻게 반영되는지 확인

plan -out=[plan_name]

[plan name]으로 플랜 결과가 생성됩니다.
바이너리이기 때문에 내용을 확인할 수는 없습니다.

apply

terraform apply [options] [plan_name]

plan에서 작성된 적용 내용을 토대로 작업을 실행합니다.
terraform plan 명령으로 생성되는 실행 계획이 필요하지만 없다면 새 실행 계획을 자동으로 생성하고 해당 계획을 승인할 것인지 묻는 메시지를 표시합니다.

-auto-approve

자동 승인 기능으로 실행 계획이 없어도 바로 계획을 적용합니다.
작업자가 결과를 완벽히 예상할 때 사용해야 합니다.

destroy

terraform destroy [options]

테라폼 구성에서 관리하는 모든 개체를 제거합니다.
테라폼 코드로 구성된 리소스의 일부만 제거하기 위해서는 테라폼의 선언적 특성에 따라 삭제하려는 항목에서 코드를 제거하고 다시 terraform apply를 실행해야 합니다.
모든 개체를 제거하려면 terraform destroy를 실행하면 됩니다.

plan -destroy

실제로 적용되지는 않고 적용 전에 destroy 되는 내용을 확인 해 볼 수 있습니다.

plan -destroy -out=[plan_name]

미리 실행 계획을 만든 다음 terraform apply를 실행해 destroy를 실행할 수 있습니다.

-auto-approve

자동 승인 기능으로 실행 계획이 없어도 바로 계획을 적용합니다.
작업자가 결과를 완벽히 예상할 때 사용해야 합니다.

실습 1 - plan, apply & destroy

main.tf

resource "local_file" "name" {
  content = "cloudcoke"
  filename = "${path.module}/cloudcoke.txt"
}
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:

  # local_file.name will be created
  + resource "local_file" "name" {
      + content              = "cloudcoke"
      + content_base64sha256 = (known after apply)
      + content_base64sha512 = (known after apply)
      + content_md5          = (known after apply)
      + content_sha1         = (known after apply)
      + content_sha256       = (known after apply)
      + content_sha512       = (known after apply)
      + directory_permission = "0777"
      + file_permission      = "0777"
      + filename             = "./cloudcoke.txt"
      + id                   = (known after apply)
    }

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

──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.
  • + : 새로 생성될 때
  • - : 삭제될 때
  • -/+ : 삭제하고 생성될 때
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:

  # local_file.name will be created
  + resource "local_file" "name" {
      + content              = "cloudcoke"
      + content_base64sha256 = (known after apply)
      + content_base64sha512 = (known after apply)
      + content_md5          = (known after apply)
      + content_sha1         = (known after apply)
      + content_sha256       = (known after apply)
      + content_sha512       = (known after apply)
      + directory_permission = "0777"
      + file_permission      = "0777"
      + filename             = "./cloudcoke.txt"
      + id                   = (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

local_file.name: Creating...
local_file.name: Creation complete after 0s [id=ceb01b909cbcc8eb5d5f0385b6b67d947c64d470]

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

해당 계획을 적용할 것인지 묻는 메시지가 나오면 yes를 입력합니다.
cloudcoke.txt 파일이 생성된 것을 확인할 수 있습니다.

terraform destroy
local_file.name: Refreshing state... [id=ceb01b909cbcc8eb5d5f0385b6b67d947c64d470]

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:

  # local_file.name will be destroyed
  - resource "local_file" "name" {
      - content              = "cloudcoke" -> null
      - content_base64sha256 = "T1OhxSY/czScfMVPRh91m70DBzCl5Ud+D05751RJfUs=" -> null
      - content_base64sha512 = "Z5P8EF7Tz5Y/MVT2bjkEHk0+JaRk0nzhxUN+SUX23Wfhy8YlJF3AhjPjAp+pLRpFxwrz23AQtuMI7JvBRyFgfw==" -> null
      - content_md5          = "b38d0a55de2c61aed3ad7a1f61194afe" -> null
      - content_sha1         = "ceb01b909cbcc8eb5d5f0385b6b67d947c64d470" -> null
      - content_sha256       = "4f53a1c5263f73349c7cc54f461f759bbd030730a5e5477e0f4e7be754497d4b" -> null
      - content_sha512       = "6793fc105ed3cf963f3154f66e39041e4d3e25a464d27ce1c5437e4945f6dd67e1cbc625245dc08633e3029fa92d1a45c70af3db7010b6e308ec9bc14721607f" -> null
      - directory_permission = "0777" -> null
      - file_permission      = "0777" -> null
      - filename             = "./cloudcoke.txt" -> null
      - id                   = "ceb01b909cbcc8eb5d5f0385b6b67d947c64d470" -> null
    }

Plan: 0 to add, 0 to change, 1 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: yes

local_file.name: Destroying... [id=ceb01b909cbcc8eb5d5f0385b6b67d947c64d470]
local_file.name: Destruction complete after 0s

모든 리소스를 제거할 것인지 묻는 메시지가 나오면 yes를 입력해 모든 리소스를 제거합니다.
cloudcoke.txt 파일이 제거된 것을 확인할 수 있습니다.

-detailed-exitcode

terraform plan -detailed-exitcode

결과는 옵션이 없던 때와 같지만 exitcode가 환경 변수로 구성되어 파이프라인 설계에서 활용할 수 있습니다.

echo $?
2

exitcode

  • 0 : 변경 사항이 없는 성공
  • 1 : 오류가 있음
  • 2 : 변경 사항이 있는 성공

실습 2 - plan 저장 후 apply & destroy

main.tf

resource "local_file" "name" {
  content = "cloudcoke"
  filename = "${path.module}/cloudcoke.txt"
}
terraform plan -out=tfplan
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:

  # local_file.name will be created
  + resource "local_file" "name" {
      + content              = "cloudcoke"
      + content_base64sha256 = (known after apply)
      + content_base64sha512 = (known after apply)
      + content_md5          = (known after apply)
      + content_sha1         = (known after apply)
      + content_sha256       = (known after apply)
      + content_sha512       = (known after apply)
      + directory_permission = "0777"
      + file_permission      = "0777"
      + filename             = "./cloudcoke.txt"
      + id                   = (known after apply)
    }

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

──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Saved the plan to: tfplan

To perform exactly these actions, run the following command to apply:
    terraform apply "tfplan"

실행 계획을 보여주고 tfplan 파일이 생성됩니다.

terraform apply tfplan
local_file.name: Creating...
local_file.name: Creation complete after 0s [id=ceb01b909cbcc8eb5d5f0385b6b67d947c64d470]

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

적용할 것인지 묻는 메시지 없이 바로 cloudcoke.txt 파일이 생성됩니다.

terraform plan -destroy -out=tfplan_destroy
local_file.name: Refreshing state... [id=ceb01b909cbcc8eb5d5f0385b6b67d947c64d470]

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:

  # local_file.name will be destroyed
  - resource "local_file" "name" {
      - content              = "cloudcoke" -> null
      - content_base64sha256 = "T1OhxSY/czScfMVPRh91m70DBzCl5Ud+D05751RJfUs=" -> null
      - content_base64sha512 = "Z5P8EF7Tz5Y/MVT2bjkEHk0+JaRk0nzhxUN+SUX23Wfhy8YlJF3AhjPjAp+pLRpFxwrz23AQtuMI7JvBRyFgfw==" -> null
      - content_md5          = "b38d0a55de2c61aed3ad7a1f61194afe" -> null
      - content_sha1         = "ceb01b909cbcc8eb5d5f0385b6b67d947c64d470" -> null
      - content_sha256       = "4f53a1c5263f73349c7cc54f461f759bbd030730a5e5477e0f4e7be754497d4b" -> null
      - content_sha512       = "6793fc105ed3cf963f3154f66e39041e4d3e25a464d27ce1c5437e4945f6dd67e1cbc625245dc08633e3029fa92d1a45c70af3db7010b6e308ec9bc14721607f" -> null
      - directory_permission = "0777" -> null
      - file_permission      = "0777" -> null
      - filename             = "./cloudcoke.txt" -> null
      - id                   = "ceb01b909cbcc8eb5d5f0385b6b67d947c64d470" -> null
    }

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

──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Saved the plan to: tfplan_destroy

To perform exactly these actions, run the following command to apply:
    terraform apply "tfplan_destroy"

실행 계획을 보여주고 tfplan_destroy 파일이 생성됩니다.

terraform apply tfplan_destroy
local_file.name: Destroying... [id=ceb01b909cbcc8eb5d5f0385b6b67d947c64d470]
local_file.name: Destruction complete after 0s

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

적용할 것인지 묻는 메시지 없이 바로 cloudcoke.txt 파일이 제거됩니다.

fmt

terraform fmt [options] [DIR]

format또는 reformat의 줄임말로 테라폼 구성 파일에 표준 형식과 표준 스타일을 적용해 줍니다.
주로 구성 파일에 작성된 테라폼 코드의 가독성을 높이거나 코드 협업 과정에서 각 작업자들마다 다른 들여쓰기 같은 스타일을 정렬하는데 사용합니다.

-recursive

하위 디렉토리의 테라폼 구성 파일을 모두 포함해 fmt 명령을 적용해 줍니다.

실습

terraform fmt
main.tf

참고

0개의 댓글