问题描述
我有解码 JSON 和 CSV 文件的 terraform 代码
provider "azurerm" {
features{}
}
locals {
resource_groupname = csvdecode(file("./ResourceTypes.csv"))
json_data = jsondecode(file("${path.module}/Monitor.json"))
}
resource "azurerm_resource_group" "Main" {
count = length(local.resource_groupname)
name = local.resource_groupname[count.index].resourcetype
location = "north europe"
}
resource "azurerm_resource_group" "name" {
# (other settings)
name = local.json_data.name
location = "north europe"
}
output "local_json_data" {
value = local.json_data
}
# azurerm_resource_group.Main[212] will be created
+ resource "azurerm_resource_group" "Main" {
+ id = (kNown after apply)
+ location = "northeurope"
+ name = "Wandisco.Fusion"
}
# azurerm_resource_group.name will be created
+ resource "azurerm_resource_group" "name" {
+ id = (kNown after apply)
+ location = "northeurope"
+ name = "Azure-apimanagement-FailedRequests"
}
Plan: 214 to add,0 to change,0 to destroy.
Changes to Outputs:
+ local_json_data = {
+ classification = "anomaly"
+ id = 16020941
+ message = <<-EOT
Azure - API Management - Failed Requests
{{name.name}} exceeds the prevIoUsly estimated average.
Please refer to the following reaction process:
https://apptemetry/kNowledgebase/Article.aspx?id=54321
Alerts generate an aim ticket,viewable here (search via CI or Alert Name):
https://apptemetry/aim/alertsearch.aspx
EOT
+ name = "Azure-apimanagement-FailedRequests"
+ options = {
+ escalation_message = ""
+ include_tags = true
+ locked = false
+ new_host_delay = 300
+ no_data_timeframe = null
+ notify_audit = false
+ notify_no_data = false
+ renotify_interval = 0
+ require_full_window = true
+ silenced = {}
+ threshold_windows = {
+ recovery_window = "last_15m"
+ trigger_window = "last_15m"
}
+ thresholds = {
+ critical = 1
+ critical_recovery = 0
}
+ timeout_h = 1
}
+ priority = null
+ query = "avg(last_4h):anomalies(avg:azure.apimanagement_service.Failed_requests{*} by {name},'agile',2,direction='above',alert_window='last_15m',interval=60,count_default_zero='true',seasonality='hourly') >= 1"
+ tags = [
+ "Sev:54",]
+ type = "query alert"
}
有没有办法可以保存 JSON 和 CSV 文件中的属性,并将其作为 terraform 中的字符串保存到变量中?然后从变量中创建一个新的 terraform 脚本?
我的最终目标是尝试从 JSON 文件创建一个 terraform 脚本。
解决方法
如果我没记错的话。您想在另一个 Terraform 脚本中引用从 JSON 文件加载值的变量。所以你可以使用 Terraform 模块来实现它。例子如下:
./modules/monitor.json
{
"resource_group_name": "testGroup"
}
./modules/main.tf
locals {
json_data = jsondecode(file("./Monitor.json"))
}
output "group_name" {
value = local.json_data.resource_group_name
}
main.tf
modules "groups" {
source = "./modules/"
}
resource "azurerm_resource_group" "group" {
name = module.groups.group_name
...
}
但是为什么不直接使用 locals
块来引用 JSON 文件中的数据?它更容易并且符合逻辑。当然,这是一个建议,您可以根据需要使用该方法。