提供一个decorator,它为数据源实现terraform的外部程序协议。
terraform-external-data的Python项目详细描述
关于
提供一个decorator,该decorator为数据源实现terraform的external program protocol。
- 从
stdin
读取json。 - 验证输入。
- 将json输出到
stdout
。 - 验证输出。
- 在
stderr
上打印可读的单行错误。 - 返回错误时的非零状态代码。
这样可以避免修改规范,并且可以轻松编写多个外部数据脚本而无需重复 代码。
包装的函数必须期望其第一个位置参数是查询数据的字典。
有关开发和运行测试的说明,请参见contributing guide。
示例用法
一如既往,创建并激活一个venv。
python -m venv env source env/bin/activate
在env中安装terraform_external_data。
pip install terraform_external_data
用
terraform_external_data
(下面的@
语法)修饰的数据收集函数编写脚本。函数必须至少接受一个参数,即terraform传入的查询数据。例如,get_cool_data.py
:fromterraform_external_dataimportterraform_external_data@terraform_external_datadefget_cool_data(query):""" Dummy function that simulates data collection with a count. Here you could reach out to an API, inspect local files, etc. """count=0foriinrange(3):count+=1# Terraform requires the values you return be strings,# so terraform_external_data will error if they aren't.return{query['thing_to_count']:str(count)}if__name__=='__main__':# Always protect Python scripts from import side effects with# a condition to check the __name__. Not specifically necessary# for terraform_external_data, but it's a best practice in general.get_cool_data()
将
data
资源添加到terraform文件中。例如,terraform.tf
:data "external" "cars_count" { program = ["python", "${path.module}/get_cool_data.py"] query = { # This is the query data your function will receive as an argument. thing_to_count = "cars" } } # Reference the data like any terraform var. This example uses an # output so it doesn't modify infrastructure. output "cars_count" { value = data.external.cars_count.result.cars }