如何用Terraform从JSON文件筛选scope为development的用户?
实现方案及修正代码
这个需求完全可以实现,原代码的问题在于for表达式未正确捕获用户属性值,导致无法判断scope条件。
原代码错误点
- 遍历
local.user_info时仅获取了键(用户名),未捕获对应的属性值,条件中的v未定义 - 未正确关联用户名和其属性的对应关系
正确写法
首先确保user_info.json的结构符合预期(示例结构如下):
{ "alice": { "value": "alice@example.com", "scope": "development", "service_name": "dev-api" }, "bob": { "value": "bob@example.com", "scope": "production", "service_name": "prod-api" } }
然后使用Terraform的for表达式筛选:
1. 获取符合条件的用户名列表
locals { user_info = jsondecode(file("${path.module}/user_info.json")) # 筛选scope为development的用户名 user_with_development_scope = [ for username, attrs in local.user_info : username if attrs.scope == "development" ] }
2. 获取符合条件的用户完整信息(含用户名和属性)
如果需要保留用户的全部属性,可返回键值对集合:
locals { user_info = jsondecode(file("${path.module}/user_info.json")) # 筛选scope为development的用户完整数据 user_with_development_scope = { for username, attrs in local.user_info : username => attrs if attrs.scope == "development" } }
验证输出
可以通过output输出结果验证:
output "development_users" { value = local.user_with_development_scope }
内容的提问来源于stack exchange,提问作者Datta
相关产品推荐
相关产品推荐

