py-libterraform 的使用和实现:一个 Terraform 的 Python 绑定

本文同步发表于字节话云公众号。

初衷

在某个使用 Python 开发的业务中,涉及到 Terraform 的交互,具体有两个需求:

  • 需要调用 Terraform 的各种命令,以完成对资源的部署、销毁等操作
  • 需要解析 Terraform 配置文件(HCL 语法)的内容,分析里面的组成

对于前者,有一个名为 python-terraform 的开源库,它封装了 Terraform 的命令,当我们在代码中调用时,背后会新启一个进程执行 Terraform 的对应命令,并能返回命令退出码和捕获的 stdoutstderrpython-terraform 用起来虽然方便,但最大的缺点在于要求执行环境事先安装了 Terraform,而且新启进程也带来了额外的开销。

对于后者,尚未找到 Python 开源库能满足要求。

我希望能有一个库无需用户事先安装 Terraform,能在当前进程执行 Terraform 命令,而且还能解析 Terraform 配置文件,py-libterraform 就这样诞生了。

使用

在说明 py-libterraform 的实现原理之前,不妨先看看是如何安装和使用的。

它的安装十分简单,执行 pip 命令即可,支持 MacLinuxWindows,并支持 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, applyshow,以部署资源并查看资源属性,那么可以这么做:

>>> 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': {
   
   
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值