快速开始¶
执行 Terraform 命令¶
为一个 Terraform 模块目录创建 TerraformCommand 实例:
初始化并校验模块:
cli.init(check=True)
validation = cli.validate(check=True)
print(validation.retcode)
print(validation.value)
生成 plan:
plan = cli.plan(check=True)
for event in plan.value:
print(event.get("@level"), event.get("@message"))
默认情况下,支持 JSON 输出的方法会把 stdout 解析为 Python 值。传入
json=False 可以保留 Terraform 的文本输出:
传递 Terraform 选项¶
Python 关键字参数会被转换为 Terraform CLI flag:
plan = cli.plan(
detailed_exitcode=True,
vars={"environment": "dev"},
target=["module.network", "module.app"],
)
TerraformCommand 会把下划线转换为连字符,因此 detailed_exitcode 会映射为
-detailed-exitcode。
解析 Terraform 配置¶
当你需要 Terraform 对配置目录的解析结果时,可以使用 TerraformConfig:
from libterraform import TerraformConfig
module, diagnostics = TerraformConfig.load_config_dir("path/to/terraform/module")
print(module["ManagedResources"].keys())
print(diagnostics)
使用 asyncio¶
当 asyncio 应用需要等待 Terraform 操作且不阻塞 event loop 时,可以使用
AsyncTerraformCommand:
from libterraform import AsyncTerraformCommand
cli = AsyncTerraformCommand("path/to/terraform/module")
validation = await cli.validate(check=True)
Terraform CLI 执行在共享库内部仍会串行化。如需真正并行的 Terraform 操作,请使用 多个进程隔离。取消 coroutine 会请求 Terraform 进入协作式 shutdown 流程,但不会 直接终止 worker thread。
完整接口见 API 参考。