You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible中如何将字典列表映射转换为MongoDB用户配置列表

实现方法

你可以通过以下两种常用方式完成变量转换:

方法1:set_fact + 循环(可读性高,方便扩展逻辑)

直接在playbook中添加如下任务即可:

- name: 生成MongoDB用户列表
  set_fact:
    users: "{{ users | default([]) + [
        {
          'database': 'client_' ~ item.name,
          'name': 'client_' ~ item.name,
          'password': item.db_pwd,
          'roles': ['readWrite', 'dbAdmin']
        }
      ] }}"
  loop: "{{ clients }}"

如果需要仅生成生产环境的用户,额外添加when条件即可:

- name: 生成MongoDB生产环境用户列表
  set_fact:
    users: "{{ users | default([]) + [
        {
          'database': 'client_' ~ item.name,
          'name': 'client_' ~ item.name,
          'password': item.db_pwd,
          'roles': ['readWrite', 'dbAdmin']
        }
      ] }}"
  loop: "{{ clients }}"
  when: item.production

方法2:json_query过滤器(精简写法,适合简单转换)

如果偏好更简洁的一行式写法,可以使用json_query过滤器实现:

- name: 生成MongoDB用户列表
  set_fact:
    users: "{{ clients | json_query('[].{database: join(`_`, [`client`, name]), name: join(`_`, [`client`, name]), password: db_pwd, roles: [`readWrite`, `dbAdmin`]}') }}"

以上两种方法最终输出的users变量都完全匹配你要求的结构。


内容的提问来源于stack exchange,提问作者spiroski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 15:06:06