IT/Terraform

[Terraform] command

louky 2021. 3. 31. 17:25
반응형

Terraform command에 대한 필자의 정리이다. 

다른 사이트나 해쉬코프사이트에서 자세한 설명은 되어 있고 필자가 기억하기 위한 정리이다. 

 

정확한 정보는 테라폼 사이트에 확인한다.

www.terraform.io/docs/cli/run/index.html

 

Provisioning Infrastructure - Terraform CLI - Terraform by HashiCorp

Terraform by HashiCorp

www.terraform.io

help명령어를 통해 기본적인 명령어는 확인 할 수 있다. 

# terraform --help
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
  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
  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.

 

  • terraform init 

    • Terraform 구성 파일이 포함 된 작업 디렉토리를 초기화하는 데 사용되며 모듈을 사용할 경우 모듈을 설치하는 역활도 한다.
    • 외부 모듈 또는 내부 모듈을 사용하며 모듈이 수정되었을 때는 “-upgrade” 옵션을 사용하여 다시 모듈의 변경사항을 다시 설치 한다. 
    • 실행하고 나면 “.terraform.lock.hcl” 파일과 “.terraform” 디렉토리를 생성 한다. 
      • “.terraform” 하위에서는 terraform을 실행 하기 위한 플러그인과 외부 모듈이 설치 된다. 
# terraform init

Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Installing hashicorp/aws v3.34.0...
- Installed hashicorp/aws v3.34.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!

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 plan

    • 실제 ​​리소스 나 상태를 변경하지 않고 변경 집합에 대한 실행 계획이 예상과 일치하는지 여부를 확인 한다.
    • *.tf 확장자로 된 파일을 읽어 들어 이상유무를 확인한다. 
    • 잘못된 설정이 있을 경우 해당 부분에 멈추고 에러를 발생한다.
# terraform plan

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_eip.create_eip[0] will be created
  + resource "aws_eip" "create_eip" {
      + allocation_id        = (known after apply)
      + association_id       = (known after apply)
      + carrier_ip           = (known after apply)
      + customer_owned_ip    = (known after apply)
      + domain               = (known after apply)
      + id                   = (known after apply)
      + instance             = (known after apply)
      + network_border_group = (known after apply)
      + network_interface    = (known after apply)
      + private_dns          = (known after apply)
      + private_ip           = (known after apply)
      + public_dns           = (known after apply)
      + public_ip            = (known after apply)
      + public_ipv4_pool     = (known after apply)
      + tags                 = {
          + "Name" = "test-1"
        }
      + vpc                  = true
    }
    
    Plan: 6 to add, 0 to change, 0 to destroy.

 

  • terraform apply

    • 작성 된 code를 실제 적용(배포)한다. “terraform apply”를 실행하면 내부적으로 “terraform plan” 을 실행하여 실행 계획이 맞는지 확인하고 적용한다. 
    • “-auto-approve” 옵션을 사용하여 사용자 진행 여부 확인 부분을 스킵 할 수 있다. 
    • 실행 후 “terraform.tfstate” 파일 생성 된다. 
      • terraform.tfstate : 실행된 결과를 json형태로 저장된다. 

 

# terraform apply -auto-approve
aws_instance.my-instance[0]: Creating...
aws_instance.my-instance[2]: Creating...
aws_instance.my-instance[1]: Creating...
aws_instance.my-instance[0]: Still creating... [10s elapsed]
aws_instance.my-instance[2]: Still creating... [10s elapsed]
aws_instance.my-instance[1]: Still creating... [10s elapsed]
aws_instance.my-instance[1]: Still creating... [20s elapsed]
aws_instance.my-instance[2]: Still creating... [20s elapsed]
aws_instance.my-instance[0]: Still creating... [20s elapsed]
aws_instance.my-instance[1]: Still creating... [30s elapsed]
aws_instance.my-instance[0]: Still creating... [30s elapsed]
aws_instance.my-instance[2]: Still creating... [30s elapsed]
aws_instance.my-instance[2]: Creation complete after 32s [id=i-0cf56b28ac61c5f08]
aws_instance.my-instance[1]: Creation complete after 32s [id=i-0ee96aa1a418b37f6]
aws_instance.my-instance[0]: Creation complete after 32s [id=i-0b1461344c4a3b4f7]
aws_eip.create_eip[1]: Creating...
aws_eip.create_eip[0]: Creating...
aws_eip.create_eip[2]: Creating...
aws_eip.create_eip[0]: Creation complete after 4s [id=eipalloc-9fff41ad]
aws_eip.create_eip[1]: Creation complete after 4s [id=eipalloc-9d02bdaf]
aws_eip.create_eip[2]: Creation complete after 4s [id=eipalloc-e1fa44d3]

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

 

 

 

 

 

 

  • terraform destroy

    • code로 적용된 인프라를 삭제(파괴)한다.
    • “-auto-approve” 옵션을 사용하여 사용자 진행 여부 확인을 스킵 할 수 있다. 
    • 실행 후 “terraform.tfstate.backup” 파일이 생성된다. 
      • terraform.tfstate.backup : “terraform.tfstate”과 동일하게 백업하고 “terraform.tfstate”은 초기화 한다
# terraform destroy -auto-approve
aws_eip.create_eip[2]: Destroying... [id=eipalloc-e1fa44d3]
aws_eip.create_eip[1]: Destroying... [id=eipalloc-9d02bdaf]
aws_eip.create_eip[0]: Destroying... [id=eipalloc-9fff41ad]
aws_eip.create_eip[2]: Destruction complete after 3s
aws_eip.create_eip[0]: Destruction complete after 3s
aws_eip.create_eip[1]: Destruction complete after 3s
aws_instance.my-instance[2]: Destroying... [id=i-0cf56b28ac61c5f08]
aws_instance.my-instance[1]: Destroying... [id=i-0ee96aa1a418b37f6]
aws_instance.my-instance[0]: Destroying... [id=i-0b1461344c4a3b4f7]
aws_instance.my-instance[2]: Still destroying... [id=i-0cf56b28ac61c5f08, 10s elapsed]
aws_instance.my-instance[0]: Still destroying... [id=i-0b1461344c4a3b4f7, 10s elapsed]
aws_instance.my-instance[1]: Still destroying... [id=i-0ee96aa1a418b37f6, 10s elapsed]
aws_instance.my-instance[2]: Still destroying... [id=i-0cf56b28ac61c5f08, 20s elapsed]
aws_instance.my-instance[1]: Still destroying... [id=i-0ee96aa1a418b37f6, 20s elapsed]
aws_instance.my-instance[0]: Still destroying... [id=i-0b1461344c4a3b4f7, 20s elapsed]
aws_instance.my-instance[0]: Still destroying... [id=i-0b1461344c4a3b4f7, 30s elapsed]
aws_instance.my-instance[1]: Still destroying... [id=i-0ee96aa1a418b37f6, 30s elapsed]
aws_instance.my-instance[2]: Still destroying... [id=i-0cf56b28ac61c5f08, 30s elapsed]
aws_instance.my-instance[1]: Destruction complete after 34s
aws_instance.my-instance[2]: Destruction complete after 34s
aws_instance.my-instance[0]: Destruction complete after 34s

Destroy complete! Resources: 6 destroyed.

 

 

크게 위의 4가지만 사용해도 인프라를 구성하는데 문제는 없다. 

 

 

반응형

'IT > Terraform' 카테고리의 다른 글

[Terraform] Terraform tf파일내에서 줄바꿈 방법  (0) 2022.05.17
[Terraform] install Tool - tfswitch  (0) 2021.04.01
[Terraform] Install (tfenv 포함)  (0) 2021.03.17