AdSense

網頁

2021/11/3

Terraform 輸入變數簡單範例 input variables example

Terraform使用輸入變數(input variables)作為module參數簡單範例。


在「Terraform local_file hello world」範例的hello.tf中利用了local_file resouce產生一個內容為Hello world!的文字檔hello.txt。下面則把local_file resource的content的值以input variable的方式傳入。

hello.tf同個目錄中新增variables.tf內容如下。
variable為定義module變數的variable block,後面的label為變數名稱;
type參數定義變數型態,例如stringnumberboollistmap等;
default定義變數的預設值。

variables.tf

variable "content" {
    type = string
    default = "Hello world!"
}

所以上面定義的變數名稱為content,型態為string,預設值為Hello world!


接著把hello.tf中的content值改為var.content,則Terraform執行時會把變數content的值Hello world!傳入。

hello.tf

resource "local_file" "hello" {
    filename = "${path.module}/hello.txt"
    content  = var.content
}

hello.tf所在目錄以命令列輸入terraform apply執行。

/.../terraform-demo$ terraform apply
local_file.hello: Refreshing state... [id=d3486ae9136e7856bc42212385ea797094475802]

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.

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

因為執行結果的內容沒改變仍是Hello world!,所以可看到No changes的訊息。



variables.tf中的變數content的預設內容修改如下。

variables.tf

variable "content" {
    type = string
    default = "Good to see you"
}

再次執行terraform apply則文字檔內容改變所以出現下面訊息。

/.../terraform-demo$ local_file.hello: Refreshing state... [id=d3486ae9136e7856bc42212385ea797094475802]

Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
-/+ destroy and then create replacement

Terraform will perform the following actions:

  # local_file.hello must be replaced
-/+ resource "local_file" "hello" {
      ~ content              = "Hello world!" -> "Good to see you" # forces replacement
      ~ id                   = "d3486ae9136e7856bc42212385ea797094475802" -> (known after apply)
        # (3 unchanged attributes hidden)
    }

Plan: 1 to add, 0 to change, 1 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.hello: Destroying... [id=d3486ae9136e7856bc42212385ea797094475802]
local_file.hello: Destruction complete after 0s
local_file.hello: Creating...
local_file.hello: Creation complete after 0s [id=f6223772272ac430c8211036fb62cc8b3f41c09f]

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

執行後hello.txt的內容如下。

hello.txt

Good to see you

參考github


沒有留言:

AdSense