最終ステップとして、Terraform 設定を実行し、変数に値を渡します。
まず、Terraform ワーキングディレクトリを初期化する必要があります。terraform init コマンドは、設定で定義されているプロバイダ(この場合は local プロバイダ)をダウンロードしてインストールします。
次のコマンドを実行します。
terraform init
Terraform が正常に初期化されたことを示す出力が表示されるはずです。
Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/local versions matching "2.4.0"...
- Installing hashicorp/local v2.4.0...
- Installed hashicorp/local v2.4.0 (signed by HashiCorp)
Terraform has been successfully initialized!
...
これで、設定を適用できます。変数に値を渡すには、-var コマンドラインフラグを使用できます。また、対話的な確認プロンプトをスキップするために -auto-approve フラグも使用します。
filename と content の値を指定して terraform apply コマンドを実行します。
terraform apply -var="filename=hello.txt" -var="content=Hello, Terraform Variables." -auto-approve
Terraform は実行計画を生成し、ファイルを作成します。出力は次のようになります。
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.my_file will be created
+ resource "local_file" "my_file" {
+ content = "Hello, Terraform Variables."
+ directory_permission = "0777"
+ file_permission = "0777"
+ filename = "hello.txt"
+ id = "..."
}
Plan: 1 to add, 0 to change, 0 to destroy.
local_file.my_file: Creating...
local_file.my_file: Creation complete after 0s [id=...]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
すべてが機能したことを確認するために、cat コマンドを使用して新しく作成されたファイルの内容を表示します。
cat hello.txt
変数で提供したコンテンツが表示されるはずです。
Hello, Terraform Variables.
おめでとうございます!Terraform 変数を使用してファイルを正常に作成できました。