iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 6
0
DevOps

今晚我想來點 Terraform 佐 AWS系列 第 6

今晚我想熟悉一點 Terraform 基本指令

稍微認識一點組態檔的長相之後,再來認識幾個主要的指令。

init

指令 terraform init會初始化工作資料夾,準備好需要的檔案讓 terraform 可以正常運作。

執行後,會依據資料夾內的組態檔,下載需要的供應商外掛 (provider plugins),放到 .terraform/ 位置裡面,並在 ~/.terraform.d/ 會有一份快取。

我們前面的伺服器是在 aws 平台上開啟的,所以 init 會下載 aws 對應的檔案下來,執行成功的畫面:

$ terraform init

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/aws versions matching "3.5.0"...
- Using hashicorp/aws v3.5.0 from the shared cache directory

Terraform has been successfully initialized!
...

validate

指令 terraform validate 單純的檢查組態檔內容,不會使用到供應商 API 或是其他的資料。可以安全並且快速的檢查語法正確性跟資料型態。

執行成功的範例:

$ terraform validate
Success! The configuration is valid.

plan

指令 terraform plan 會產生一份執行計劃。

這份執行計劃是跟據你設計好的組態檔以及基礎架構的狀態所產生的,上面寫著要達成組態檔內容所需要的動作。

這個指令很適合用來檢查你的修改,會對基礎架構造成什麼樣的變動。

$ 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_instance.example will be created
  + resource "aws_instance" "example" {
      + ami                          = "ami-0461b11e2fad8c14a"
      + 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                = "t2.micro"
      ...
    }

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

apply

指令 terraform apply 會先產生一份執行計劃跟 terraform plan 一樣的內容,接著詢問你是否確定要執行。

輸入 "yes" 就會開始執行,並能看到 terraform 印出處理過程的資訊,最後會有一個完成的訊息。

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: Creation complete after 34s [id=i-03149105e5e5a166d]

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

destroy

指令 terraform destroy 會刪除經由 terraform 控制的基礎架構。

terraform apply 相同,會印出執行計劃,讓你知道預計會做哪些動作,並詢問是否要執行。

再三確定你要刪除的內容,輸入 "yes" 就會開始執行,這個動作是無法回復的。

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

aws_instance.example: Destroying... [id=i-0ab21c3f140f6d9b2]
...

Destroy complete! Resources: 1 destroyed.

上一篇
今晚我想認識 Terraform 組態檔
下一篇
今晚我想看透 Terraform 狀態檔
系列文
今晚我想來點 Terraform 佐 AWS30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言