在最后一步中,你将使用标准的 Terraform 命令来初始化(initialize)、规划(plan)和应用(apply)你的配置。这将执行模块中的代码并创建本地文件。
首先,初始化 Terraform 工作目录。此命令会下载必要的 provider 插件(在本例中是 hashicorp/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!
...
接下来,运行 terraform plan 来查看 Terraform 将要进行哪些更改。这是一个“干运行”(dry run),它不会改变任何东西,但会向你展示执行计划。
terraform plan
输出将显示将创建一个资源(模块内的 local_file)。
...
Plan: 1 to add, 0 to change, 0 to destroy.
Changes to Outputs:
+ created_file_path = (known after apply)
...
现在,应用配置以创建文件。我们将使用 -auto-approve 标志来跳过交互式确认提示。
terraform apply -auto-approve
Terraform 将执行计划并创建文件。输出将确认创建并显示你定义的输出值。
...
module.file_creator_instance.local_file.example: Creating...
module.file_creator_instance.local_file.example: Creation complete after 0s [id=f73598097552a798110a31388c54c1194b539a53]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Outputs:
created_file_path = "./modules/localfile_creator/my_test_file.txt"
最后,验证文件是否已使用正确的内容创建。列出模块目录中的文件,然后显示新文件的内容。
ls -l modules/localfile_creator/
cat modules/localfile_creator/my_test_file.txt
cat 命令的输出应该是:
Hello from the root module!
恭喜你,你已成功创建并使用了 Terraform 模块!