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

使用SSH密钥验证时,Ansible Git模块更新代码需输密码的解决方法

解决Ansible Git模块更新时要求凭据的问题

核心问题分析

克隆新目录时正常,更新旧目录需输入凭据,大概率是旧目录内的Git配置未继承主仓库的SSH密钥设置,或是子模块的远程URL未采用SSH格式,导致更新时触发了HTTPS凭据验证流程。

可行解决方案

1. 优化Ansible Git模块配置

添加track_submodules: yes参数,确保子模块更新时复用主仓库的SSH密钥配置,同时强制子模块跟踪主仓库的远程设置:

- git:
    key_file: '/home/pi/ansible/key'
    repo: 'git@bitbucket.org:space/repo_with_submodules.git'
    dest: "{{ build_dir }}"
    update: yes
    version: main
    recursive: yes
    accept_hostkey: yes
    track_submodules: yes  # 关键参数,让子模块继承主仓库的认证配置

如果子模块原本使用HTTPS格式的远程URL,需要先在主仓库中修改子模块URL为SSH格式:

git submodule set-url <子模块相对路径> git@bitbucket.org:space/对应子模块仓库.git

提交主仓库的修改后,后续更新时子模块会自动使用SSH拉取代码。

2. 清理目标目录的Git凭据缓存

若目标目录残留了Git凭据助手配置,会干扰SSH密钥的使用,可在更新前清理:

- name: 清理Git凭据配置
  command: "{{ item }}"
  loop:
    - git -C {{ build_dir }} config --unset credential.helper
    - git -C {{ build_dir }} submodule foreach --recursive git config --unset credential.helper
  ignore_errors: yes  # 忽略目录不存在或无对应配置的错误

3. 确保SSH密钥权限合规

SSH密钥文件权限过宽会被SSH客户端拒绝使用,需设置为仅所有者可读:

- name: 设置SSH密钥权限
  file:
    path: '/home/pi/ansible/key'
    mode: '0600'
    owner: pi
    group: pi

4. 替代方案:直接执行Git命令

如果上述方法仍无效,可绕过Ansible Git模块,直接用command模块指定SSH密钥执行拉取:

- name: 更新主仓库及子模块
  command: |
    GIT_SSH_COMMAND='ssh -i /home/pi/ansible/key -o StrictHostKeyChecking=accept-new' git pull --recurse-submodules
  args:
    chdir: "{{ build_dir }}"
  when: ansible_facts.stat.path == "{{ build_dir }}" and ansible_facts.stat.isdir

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:24:13