amazon-web-services - 如果我不添加默认变量,则 Terraform/Terragrunt 错误
问题描述
我是一个地形新手。我已经为 cloudfront 编写了一个模块。我想将我的原始配置作为对象传递。当我运行 terragrunt 时,我收到此错误:
Error: Invalid default value for variable
on variables.tf line 9, in variable "origin_config":
9: default = {
10: protocol_policy = "https-only"
11: ssl_protocol = ["TLSv1.2"]
12: http_port = 80
13: https_port = 443
14: }
This default value is not compatible with the variable's type constraint:
attribute "domain_name" is required.
这是我的模块代码:
resource "aws_cloudfront_distribution" "this" {
# origin config
origin {
domain_name = var.origin_config.domain_name
origin_id = local.origin_id
custom_origin_config {
origin_protocol_policy = var.origin_config.protocol_policy
origin_ssl_protocols = var.origin_config.ssl_protocol
http_port = var.origin_config.http_port
https_port = var.origin_config.https_port
}
}
这是我的变量.tf
variable "origin_config" {
type = object({
domain_name = string
protocol_policy = string
ssl_protocol = list(string)
http_port = number
https_port = number
})
default = {
protocol_policy = "https-only"
ssl_protocol = ["TLSv1.2"]
http_port = 80
https_port = 443
}
}
这是我的 terraform.tfvars:
origin_config = {
domain_name = "test.example.com"
}
如果我将变量添加domain_name
为默认值,那么它可以工作。似乎它没有从 terraform.tvars 读取我的输入?
解决方案
您的type
包含domain_name = string
使其成为强制性的。因此,如果您不想设置固定值,则必须设置一个空字符串,例如:
variable "origin_config" {
type = object({
domain_name = string
protocol_policy = string
ssl_protocol = list(string)
http_port = number
https_port = number
})
default = {
domain_name = ""
protocol_policy = "https-only"
ssl_protocol = ["TLSv1.2"]
http_port = "80"
https_port = "443"
}
}
否则,domain_name
从您的type
. 还有一个实验性的 可选关键字:
terraform {
experiments = [module_variable_optional_attrs]
}
variable "origin_config" {
type = object({
domain_name = optional(string)
protocol_policy = string
ssl_protocol = list(string)
http_port = number
https_port = number
})
default = {
protocol_policy = "https-only"
ssl_protocol = ["TLSv1.2"]
http_port = "80"
https_port = "443"
}
}
推荐阅读
- matlab - 使用 h5py 读取 matlab .mat 文件
- airflow - 气流:是否可以在 DAG 中配置任务级超时?
- javascript - 在javascript中排列对象键(字符串,字符串中的数字)
- laravel - Laravel - 如何在“whereHas”中检查关系中的所有记录?
- android - 使用 ADB shell 命令在 android 上禁用绝对蓝牙音量
- python - 在 Python 中估计或绑定浮点转换错误
- hibernate - LiquiBase - 找不到数据库驱动程序 liquibase.ext.hibernate.database.connection.HibernateDriver
- android - 使用颤振不停地振动
- php - 使用 laravel 理解模型关系
- javascript - 如何在 JS 中传递 C# 变量