azure - Ansible 字符串变量到 Terraform 列表(字符串)

标签 azure variables ansible terraform

我将 Ansible 和 Terraform 一起用于 MS Azure 中的不同部署。现在我想使用模块“azurerm_virtual_network和azurerm_subnet”创建一个带有子网的Vnet。只有我遇到了“Address_space”和“address_prefixes”在terraform中定义的问题为 “list (string)”,这是在 Ansible 中通过 “string” 完成的。

我的问题是如何以正确的形式将此变量从 Ansible 获取到 Terraform,而不会收到以下消息:

“default = \u001b[4m"{{subnet1_cidr}}"\u001b[0m\n\u001b[0m\nThis default value is not compatible with the variable's type constraint: list\nof string”

我使用 ansible 角色获取 ansible 变量 “group_vars”,该角色将名为 “terraform.tfvars.j2” 的文件复制到 “{{playbook_dir} }/terraform/terraform.tfvars "。在“variables.tf”中,变量加载如下

variable "vnet_cidr" {
  type        = list(string)
  default     = "{{ [vnet_cidr] | list | to_json }}"
}

variable "subnet1_cidr" {
  type        = list(string)
  default     = "{{ [subnet1_cidr] | list | to_json }}"
}

variable "subnet2_cidr" {
  type        = list(string)
  default     = "{{ [subnet2_cidr] | list | to_json }}"
}

Ansible Group_Vars,

VNET_Name: AZ-Venet
GV_Virtual_Network_Cidr: 10.0.0.0/16

SNET1_Name: AZ-FrontEnd
GV_Subnet_Cidr1: 10.0.1.0/24
Survey_SNET2_Name: Az-Backend
GV_Subnet_Cidr2: 10.0.2.0/24

Terraform terraform.tfvars.j2/terraform.tfvars

# Networking
vnet_cidr                       = "{{ GV_Virtual_Network_Cidr }}"
subnet1_cidr                    = "{{ GV_Subnet_Cidr1 }}"
subnet2_cidr                    = "{{ GV_Subnet_Cidr2 }}"

最佳答案

如果您只需要将字符串转换为包含一项的列表,则可以使用 Ansible 过滤器。 这是一个例子:

{{ [example_variable] | list | to_json }}

但是,在您的情况下,配置会有所不同。

在variables.tf文件中,您可以尝试删除默认值,因为Ansible vars中似乎没有变量vnet_cidr、subnet1_cidr和subnet2_cidr。

variables.tf 文件将如下所示:

variable "vnet_cidr" {
  type        = list(string)
  default     = []
}

variable "subnet1_cidr" {
  type        = list(string)
  default     = []
}

variable "subnet2_cidr" {
  type        = list(string)
  default     = []
}

然后文件 terraform.tfvars.j2/terraform.tfvars 将如下所示:

# Networking
vnet_cidr                       = [ "{{ GV_Virtual_Network_Cidr }}" ]
subnet1_cidr                    = [ "{{ GV_Subnet_Cidr1 }}" ]
subnet2_cidr                    = [ "{{ GV_Subnet_Cidr2 }}" ]

关于azure - Ansible 字符串变量到 Terraform 列表(字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65759531/

相关文章:

c# - Cosmos DB - ExecuteNextAsync 返回空对象

variables - 无法在Docker容器中更改环境变量

java - Java 中 BigDecimal 和 double 的运算

ansible - 根据多种条件选择主机执行任务

azure - 从 azure 反向代理调用 https 连接时,httpClient 抛出连接重置

python - 使用 Python 在 Azure 存储 blob 中创建 PDF 文件的最佳方法是什么?

python - Python 类声明中的变量用法

ubuntu - Vagrant 中的 Redis(Ubuntu): how to forward redis port?

ansible - 为用户建立 SSH 连接 : None when specify a single host on the command line

python - 使用 python sdk 在 Azure 中创建表格数据集