DDetB.Log
article thumbnail
Published 2023. 7. 9. 11:38
Terraform 기본 사용 (1) DevOps/Terraform
이 포스팅은 CloudNet@ 팀이 진행하는 테라폼 기초 입문 스터디에 참여하며 ‘테라폼으로 시작하는 IaC’ 책을 기준하여 정리한 글입니다.

주요 커맨드

주요 커맨드

'terraform' 입력 시 입력 가능한 명령어 셋을 확인할 수 있습니다.

$ terraform
Usage: terraform [global options] <subcommand> [args]

The available commands for execution are listed below.
The primary workflow commands are given first, followed by
less common or more advanced commands.

Main commands:
  init          Prepare your working directory for other commands
  validate      Check whether the configuration is valid
  plan          Show changes required by the current configuration
  apply         Create or update infrastructure
  destroy       Destroy previously-created infrastructure

All other commands:
  console       Try Terraform expressions at an interactive command prompt
  fmt           Reformat your configuration in the standard style
  force-unlock  Release a stuck lock on the current workspace
  get           Install or upgrade remote Terraform modules
  graph         Generate a Graphviz graph of the steps in an operation
  import        Associate existing infrastructure with a Terraform resource
  login         Obtain and save credentials for a remote host
  logout        Remove locally-stored credentials for a remote host
  metadata      Metadata related commands
  output        Show output values from your root module
  providers     Show the providers required for this configuration
  refresh       Update the state to match remote systems
  show          Show the current state or a saved plan
  state         Advanced state management
  taint         Mark a resource instance as not fully functional
  test          Experimental support for module integration testing
  untaint       Remove the 'tainted' state from a resource instance
  version       Show the current Terraform version
  workspace     Workspace management

Global options (use these before the subcommand, if any):
  -chdir=DIR    Switch to a different working directory before executing the
                given subcommand.
  -help         Show this help output, or the help for a specified subcommand.
  -version      An alias for the "version" subcommand.

main.tf

아래의 테라폼 파일을 통해 기본 동작을 확인합니다.

resource "local_file" "abc" {
content  = "abc!"
filename = "${path.module}/abc.txt"
}

help 

help command

# 서브커맨드로서의 help 옵션
terraform console -help
terraform init -help

init

init command

테라폼 구성 파일이 있는 작업 디렉토리를 초기화하는데 사용합니다.

$ terraform init
Initializing the backend...

Initializing provider plugins...
- Reusing previous version of hashicorp/local from the dependency lock file
- Using previously-installed hashicorp/local v2.4.0
...

validation

$ tree .terraform
.terraform
└── providers
    └── registry.terraform.io
        └── hashicorp
            └── local
                └── 2.4.0
                    └── linux_amd64
                        └── terraform-provider-local_v2.4.0_x5

초기화 없이 다음 스탭으로 넘어가면?

$ terraform plan
│ Error: Inconsistent dependency lock file
│ 
│ The following dependency selections recorded in the lock file are inconsistent with the current configuration:
│   - provider registry.terraform.io/hashicorp/local: required by this configuration but no version is selected
│ 
│ To make the initial dependency selections that will initialize the dependency lock file, run:
│   terraform init

-> 에러 발생

plan

plan command

plan 명령은 테라폼으로 적용할 인프라의 변경 사항에 관한 실행 계획생성하는 동작을 수행하며, 실제 적용 전에 예상한 구성이 맞는지 검토하는 명령어입니다.

$ 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.abc will be created
  + resource "local_file" "abc" {
      + content              = "abc!"
      + 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             = "./abc.txt"
      + id                   = (known after apply)
    }

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

-out option

-out 옵션을 통해 plan을 file형태로 내보낼 수 있습니다.

$terraform plan -out=tfplan
local_file.abc: Refreshing state... [id=5678fb68a642f3c6c8004c1bdc21e7142087287b]

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.

$ file tfplan
tfplan: Zip archive data, at least v2.0 to extract

apply

apply command

apply 명령은 plan 계획을 기반으로 작업을 실행하는 명령어입니다.

$ terraform apply
...
Enter a value: yes
...

or

$ terraform apply -auto-approve

Command test

코드 파일 수정

resource "local_file" "abc" {
content = "abc!"
filename = "${path.module}/abc.txt"
}

resource "local_file" "dev" {
  content  = "def!"
  filename = "${path.module}/def.txt"
}

실행

$ terraform apply
local_file.abc: Refreshing state... [id=5678fb68a642f3c6c8004c1bdc21e7142087287b]

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.dev will be created
  + resource "local_file" "dev" {
 ...

=> 변경 부분만 반영

현재와 다른 상태의 plan 적용

파일 수정 이전의 plan 파일을 적용 시도하면?

$ terraform apply tfplan 
╷
│ Error: Saved plan is stale
│ 
│ The given plan file can no longer be applied because the state was changed by another operation after the plan was created.
╵

=> 에러 발생. 수정 이전 상태로 다시 저장해도 에러 발생.

=> 현재 상태와 적용할 상태(Destroy 1)를 비교하기 때문. tfplan의 적용할 상태는 Create 1에 해당.

destroy

테라폼 구성에서 관리하는 모든 개체를 제거하는 명령어

$ terraform destroy
local_file.dev: Refreshing state... [id=15f946cb27f0730866cefea4f0923248d9366cb0]
local_file.abc: Refreshing state... [id=5678fb68a642f3c6c8004c1bdc21e7142087287b]

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.abc will be destroyed
...

  # local_file.dev will be destroyed
...
  Enter a value: yes
...
Destroy complete! Resources: 2 destroyed.

fmt

테라폼 구성 파일을 표준 형식과 표준 스타일로 적용하여 코드 가독성 높힙니다.

before

$ cat main.tf
resource "local_file" "abc" {
content = "abc!"
filename = "${path.module}/abc.txt"
}

after

$ terraform fmt   
main.tf

$ cat main.tf
resource "local_file" "abc" {
  content  = "abc!"
  filename = "${path.module}/abc.txt"
}

HCL

HCL은 HashiCorp Configuration Language의 약자로, 하시코프 사에서 IaC와 구성정보를 명시하기 위해 개발된 툴킷입니다. 테라폼에서 HCL을 통해 코드를 작성합니다.

HCL 표현식에서는 코드에서 사용되는 주석 표기부터 변수 정의 등을 포함하고, 프로그래밍적인 연산과 구성 편의성을 높이기 위해 사전 정의된 function이나 조건문 등의 동작을 제공합니다. 이는 JSON이나 YAML에서 데이터 및 타입만 표현하던 것과는 달리, 필요에 따라 코드 선언 레벨에서 로직을 작성함으로써 유연성을 가져갈 수 있는 장점을 가집니다.

// 한줄 주석 방법1
# 한줄 주석 방법2

/*
라인
주석
*/

locals {
  key1     = "value1"     # = 를 기준으로 키와 값이 구분되며
  myStr    = "TF ♡ UTF-8" # UTF-8 문자를 지원한다.
  multiStr = <<EOF
  Multi
  Line
  String
  with anytext
EOF

  boolean1    = true   # boolean true
  boolean2    = false  # boolean false를 지원한다.
  deciaml     = 123    # 기본적으로 숫자는 10진수,
  octal       = 0123   # 0으로 시작하는 숫자는 8진수,
  hexadecimal = "0xD5" # 0x 값을 포함하는 스트링은 16진수,
  scientific  = 1e10   # 과학표기 법도 지원한다.

  # funtion 호출 예
  myprojectname = format("%s is myproject name", var.project)

  # 3항 연산자 조건문을 지원한다.
  credentials = var.credentials == "" ? file(var.credentials_file) : var.credentials
}

HCL 표현식에 사용할 수 있는 function들은 아래의 링크에서 확인 가능합니다.

https://developer.hashicorp.com/terraform/language/functions

profile

DDetB.Log

@DDetMok

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!