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

如何在Ansible Playbook中从Hashi Vault为多仓库匹配对应账号密码

解决多仓库与Hashi Vault凭证匹配的问题

首先修正你的config.yml结构,原平级写法会导致user和password被后续条目覆盖,改成嵌套列表形式:

repositories:
  - name: repo1
    url: docker
    user: user1
  - name: repo2
    url: docker1
    user: user2

调整Ansible Playbook

修正Vault参数的错误引用,并添加循环逻辑为每个仓库匹配对应凭证:

tasks:
  - name: 加载仓库配置
    include_vars:
      file: config.yml
      name: repo_config

  - name: 从Hashi Vault获取所有凭证
    set_fact:
      repo_cred: "{{ lookup('hashi_vault', hashi_vault_params) }}"
    delegate_to: localhost
    vars:
      hashi_vault_params: >-
        secret={{ hashi_vault.secret }}
        url={{ hashi_vault.url }}
        token={{ hashi_vault.token }}
        ca_cert={{ hashi_vault.ca_cert }}
      hashi_vault:
        secret:  "test/repo_pass" 
        token:   "{{ vault_token }}"
        url:     "{{ service }}"
        ca_cert: "{{ ca_cert }}"

  - name: 为每个仓库生成对应配置文件
    template:
      src: config.json.j2
      dest: "./{{ item.name }}_config.json"  # 可自定义输出路径
    loop: "{{ repo_config.repositories }}"
    vars:
      url: "{{ item.url }}"
      username: "{{ item.user }}"
      # 从Vault凭证字典中匹配对应用户的密码,转为JSON格式避免语法错误
      repo_cred: "{{ repo_cred[item.user] | to_json }}"

更新模板文件config.json.j2

补充username字段的变量引用:

{
  "url": "{{ url }}",
  "username": "{{ username }}",
  "password": {{ repo_cred }}
}

逻辑说明

  1. 加载仓库配置后,repo_config.repositories会成为包含所有仓库信息的列表
  2. 循环遍历每个仓库条目,通过item.user从Vault获取的repo_cred字典中提取对应密码
  3. 使用to_json过滤器确保密码值符合JSON语法要求(比如包含特殊字符时不会出错)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 02:45:41