本文同步发表于字节话云公众号。
初衷
在某个使用 Python 开发的业务中,涉及到 Terraform 的交互,具体有两个需求:
- 需要调用 Terraform 的各种命令,以完成对资源的部署、销毁等操作
- 需要解析 Terraform 配置文件(HCL 语法)的内容,分析里面的组成
对于前者,有一个名为 python-terraform 的开源库,它封装了 Terraform 的命令,当我们在代码中调用时,背后会新启一个进程执行 Terraform 的对应命令,并能返回命令退出码和捕获的 stdout 和 stderr。python-terraform 用起来虽然方便,但最大的缺点在于要求执行环境事先安装了 Terraform,而且新启进程也带来了额外的开销。
对于后者,尚未找到 Python 开源库能满足要求。
我希望能有一个库无需用户事先安装 Terraform,能在当前进程执行 Terraform 命令,而且还能解析 Terraform 配置文件,py-libterraform 就这样诞生了。
使用
在说明 py-libterraform 的实现原理之前,不妨先看看是如何安装和使用的。
它的安装十分简单,执行 pip 命令即可,支持 Mac、Linux和Windows,并支持 Python3.6 及以上版本:
$ pip install libterraform
py-libterraform 目前提供两个功能:TerraformCommand 用于执行 Terraform CLI,TerraformConfig 用于解析 Terraform 配置文件。后文将通过示例介绍这两个功能。假定当前有一个 sleep 文件夹,里面的 main.tf 文件内容如下:
variable "time1" {
type = string
default = "1s"
}
variable "time2" {
type = string
default = "1s"
}
resource "time_sleep" "wait1" {
create_duration = var.time1
}
resource "time_sleep" "wait2" {
create_duration = var.time2
}
output "wait1_id" {
value = time_sleep.wait1.id
}
output "wait2_id" {
value = time_sleep.wait2.id
}
Terraform CLI
现在进入 sleep 目录,需要对它执行 Terraform init, apply 和 show,以部署资源并查看资源属性,那么可以这么做:
>>> from libterraform import TerraformCommand
>>> cli = TerraformCommand()
>>> cli.init()
<CommandResult retcode=0 json=False>
>>> _.value
'\nInitializing the backend...\n\nInitializing provider plugins...\n- Reusing previous version of hashicorp/time from the dependency lock file\n- Using previously-installed hashicorp/time v0.7.2\n\nTerraform has been successfully initialized!\n\nYou may now begin working with Terraform. Try running "terraform plan" to see\nany changes that are required for your infrastructure. All Terraform commands\nshould now work.\n\nIf you ever set or change modules or backend configuration for Terraform,\nrerun this command to reinitialize your working directory. If you forget, other\ncommands will detect it and remind you to do so if necessary.\n'
>>> cli.apply()
<CommandResult retcode=0 json=True>
>>> _.value
[{
'@level': 'info', '@message': 'Terraform 1.1.7', '@module': 'terraform.ui', '@timestamp': '2022-04-08T19:16:59.984727+08:00', 'terraform': '1.1.7', 'type': 'version', 'ui': '1.0'}, ... ]
>>> cli.show()
<CommandResult retcode=0 json=True>
>>> _.value
{
'format_version': '1.0', 'terraform_version': '1.1.7', 'values': {
'outputs': {
'wait1_id': {
'sensitive': False, 'value': '2022-04-08T11:17:01Z'}, 'wait2_id': {
'sensitive': False, 'value': '2022-04-08T11:17:01Z'}}, 'root_module': {

最低0.47元/天 解锁文章
506

被折叠的 条评论
为什么被折叠?



