Skip to main content

简单的 Terraform 测试助手

项目描述

Terraform 的 Python 测试助手

这个简单的帮助程序通过包装 Terraform 可执行文件并公开方便的方法来设置固定装置、执行 Terraform 命令并解析其输出,从而有助于从 Python 单元测试中测试 Terraform 模块。

它允许不同类型的测试:仅使用 Terraforminit并确保代码在语法上正确并且应该创建正确数量和类型的资源的轻量级测试,或者plan运行完整 // 循环的完整测试,apply然后可以用于测试实际创建的资源,或状态文件。outputdestroy

作为额外的便利,该模块还提供了一种简单的方法来请求和访问计划输出(通过terraform plan -out和terraform show)和输出(通过terraform output -json),并将它们返回包装在简化访问其属性的简单类中。

这个模块深受两个项目的启发:Terratest用于测试 Terraform 的轻量级方法,python-terraform用于在 Python 中包装 Terraform 命令。

示例用法

该文件夹包含有关如何使用合成装置(计划输出和输出文件的简单表示)或最小根模块为和test编写测试的简单示例。可以在为此模块开发的Cloud Foundation Fabric存储库中找到更多示例。planapply

这是一个在实际模块上使用计划输出的测试:

import pytest
import tftest


@pytest.fixture
def plan(fixtures_dir):
  tf = tftest.TerraformTest('plan', fixtures_dir)
  tf.setup(extra_files=['plan.auto.tfvars'])
  return tf.plan(output=True)


def test_variables(plan):
  assert 'prefix' in plan.variables
  assert plan.variables['names'] == ['one', 'two']


def test_outputs(plan):
  assert sorted(plan.outputs['gcs_buckets'].keys()) == plan.variables['names']


def test_root_resource(plan):
  res = plan.resources['google_project_iam_member.test_root_resource']
  assert res['values']['project'] == plan.variables['project_id']


def test_modules(plan):
  mod = plan.modules['module.gcs-buckets']
  res = mod.resources['google_storage_bucket.buckets[0]']
  assert res['values']['location'] == plan.variables['gcs_location']

Terragrunt 支持

对 Terragrunt 的支持实际上遵循了瘦TerraformTest包装器的相同原则。

请参阅以下示例以了解如何使用它:

import pytest
import tftest


@pytest.fixture
def run_all_apply_out(fixtures_dir):
  # notice for run-all, you need to specify when TerragruntTest is constructed
  tg = tftest.TerragruntTest('tg_apply_all', fixtures_dir, tg_run_all=True)
  # the rest is very similar to how you use TerraformTest
  tg.setup()
  # to use --terragrunt-<option>, pass in tg_<option in snake case>
  tg.apply(output=False, tg_non_interactive=True)
  yield tg.output()
  tg.destroy(auto_approve=True, tg_non_interactive=True)

  
def test_run_all_apply(run_all_apply_out):
    triggers = [o["triggers"] for o in run_all_apply_out]
    assert [{'name': 'foo', 'template': 'sample template foo'}] in triggers
    assert [{'name': 'bar', 'template': 'sample template bar'}] in triggers
    assert [{'name': 'one', 'template': 'sample template one'},
            {'name': 'two', 'template': 'sample template two'}] in triggers
    assert len(run_all_apply_out) == 3

兼容性

从版本开始需要1.0.0Terraform 0.12,并且使用此模块的先前版本编写的测试不兼容。检查CHANGELOG.md文件以获取有关更改内容的详细信息。

测试

测试使用该pytest框架,除了对 Terraform 二进制文件没有其他依赖项。开发过程中使用的版本在DEV-REQUIREMENTS.txt文件中。

免责声明

这不是官方支持的 Google 产品。

项目详情


下载文件

下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。

源分布

tftest-1.7.2.tar.gz (19.1 kB 查看哈希)

已上传 source

内置分布

tftest-1.7.2-py3-none-any.whl (13.8 kB 查看哈希)

已上传 py3