在最后一步中,你将执行你的 Terraform 配置并为变量提供值。
首先,你需要初始化 Terraform 工作目录。terraform init 命令会下载并安装配置中定义的 provider(在我们的例子中是 local provider)。
运行以下命令:
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 变量创建了一个文件。