简体   繁体   English

使用 Python 按变量名对 Terraform variables.tf 进行排序

[英]Sorting Terraform variables.tf by variable name using Python

I am working on creating a new VPC where I need to provide some variables as input.我正在创建一个新的 VPC,我需要在其中提供一些变量作为输入。

All the variables are listed in variables.tf .所有变量都列在variables.tf中。 The file is very long (I only copied couple of them here) and variables are defined in no particular order.该文件很长(我在这里只复制了几个)并且变量的定义没有特定的顺序。

I need to find a Pythonic way to sort my variables.tf by variable name .我需要找到一种Pythonic 方法来按变量名variables.tf进行排序。

variable "region" {
  description = "The region to use when creating resources"
  type        = string
  default     = "us-east-1"
}

variable "create_vpc" {
  description = "Controls if VPC should be created"
  type        = bool
  default     = true
}

variable "name" {
  description = "Name to be used, no default, required"
  type        = string
}

The sorted variables.tf should look like this:排序后variables.tf应如下所示:

variable "create_vpc" {
  description = "Controls if VPC should be created"
  type        = bool
  default     = true
}

variable "name" {
  description = "Name to be used, no default, required"
  type        = string
}

variable "region" {
  description = "The region to use when creating resources"
  type        = string
  default     = "us-east-1"
}

"Pythonic" might be the wrong approach here - you are still comfortably sitting behind a python interpreter, but for better or worse (worse) you are playing by Terraform's rules. “Pythonic”在这里可能是错误的方法 - 您仍然舒适地坐在 Python 解释器后面,但无论好坏(更糟),您都在按照 Terraform 的规则行事。 Check out the links below.检查下方的链接。 Hashicorp "enables" python via their CDK, and there are several other projects out there on github. Hashicorp 通过他们的 CDK “启用” python,并且在 github 上还有其他几个项目。

Once you are up and running with something like that, and you have Terraform fully ported over to your Python setup, then you can start thinking pythonic.一旦你启动并运行了类似的东西,并且你已经将 Terraform 完全移植到你的 Python 设置中,那么你就可以开始考虑 pythonic 了。 </IMO> </IMO>

https://github.com/hashicorp/terraform-cdk https://github.com/beelit94/python-terraform/blob/develop/python_terraform/terraform.py https://github.com/hashicorp/terraform-cdk https://github.com/beelit94/python-terraform/blob/develop/python_terraform/terraform.py

Here's what I came across last year https://github.com/hashicorp/terraform/issues/12959 and is why I created https://gist.github.com/yermulnik/7e0cf991962680d406692e1db1b551e6 out of curiosity.这是我去年遇到的https://github.com/hashicorp/terraform/issues/12959 ,这也是我出于好奇创建https://gist.github.com/yermulnik/7e0cf991962680d406692e1db1b551e6的原因。 Not Python but awk :shrugging: Simple awk script to sort TF files.不是 Python 而是awk :shrugging: 用于对 TF 文件进行排序的简单awk脚本。 Not just variables, but any of 1st level resource definition blocks.不仅是变量,还有任何一级资源定义块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM