如何配置凭据在Windows上通过Ansible克隆含子模块的Git仓库?
问题:Ansible克隆含子模块的Git仓库到Windows失败
问题背景
此前用以下命令克隆仓库正常:
git clone https://[username]:[password]@myServer.com/bitbucket/scm/[project]/[repo].git
但仓库添加子模块后,使用git clone --recurse-submodules拉取子模块时,出现**“登录会话不存在”**错误,推测原因是凭据仅通过父仓库URL传递一次,未在Git全局配置中持久化。
已尝试的方法及问题
- 使用
ansible.builtin.git模块:实际测试发现该模块不支持Windows环境(官方文档未明确说明)。 - 通过Windows凭据管理器配置凭据:使用
community.windows.win_credential模块时必须加become: true,但执行账户虽属于本地Administrators组,却没有SeAllowLogonLocally权限,导致任务失败。 - 用
git config设置全局凭据:执行以下命令后,已验证~\.gitconfig中配置正确,但仍报错:
git config --global credential.https://myServer.com.username {{ username }} git config --global credential.https://myServer.com.password {{ password }}
报错信息:
fatal: A specified logon session does not exist. It may already have been terminated
git: 'credential-winscred' is not a git command. See 'git --help'.
fatal: could not read Password for 'https://[username]@myServer.com': No such file or directory
可行解决方案
方案1:修复Git凭据助手+全局凭据配置
报错中的credential-winscred是过时的凭据助手,Windows下Git官方推荐用manager-core,先配置正确的助手,再设置全局凭据:
- name: 配置Git凭据助手为manager-core win_command: git config --global credential.helper manager-core - name: 设置Git全局用户名(对应仓库域名) win_command: git config --global credential.https://myServer.com.username {{ username }} - name: 设置Git全局密码(对应仓库域名) win_command: git config --global credential.https://myServer.com.password {{ password }} - name: 递归克隆仓库及子模块 win_command: git clone --recurse-submodules https://myServer.com/bitbucket/scm/[project]/[repo].git {{ target_clone_path }}
此方案中,全局凭据会被父仓库和子模块拉取时自动调用,无需在URL中嵌入明文凭据。
方案2:修复账户本地登录权限+使用Windows凭据管理器
如果偏好使用系统凭据管理器,先给执行账户添加本地登录权限,再配置凭据:
- name: 给执行账户添加「允许本地登录」权限 community.windows.win_user_right: name: SeInteractiveLogonRight users: - "{{ ansible_user }}" action: add - name: 添加仓库凭据到Windows凭据管理器 community.windows.win_credential: name: https://myServer.com type: generic username: "{{ username }}" secret: "{{ password }}" state: present become: true - name: 递归克隆仓库及子模块 win_command: git clone --recurse-submodules https://myServer.com/bitbucket/scm/[project]/[repo].git {{ target_clone_path }}
配置完成后,Git会自动从系统凭据管理器读取认证信息,无需在命令中传递明文。
方案3:分步克隆父仓库+更新子模块
如果递归克隆仍有问题,可拆分步骤操作:
- name: 克隆父仓库 win_command: git clone https://myServer.com/bitbucket/scm/[project]/[repo].git {{ target_clone_path }} - name: 初始化子模块 win_command: git submodule init args: chdir: "{{ target_clone_path }}" - name: 递归更新子模块 win_command: git submodule update --recursive --remote args: chdir: "{{ target_clone_path }}"
此方案需确保全局凭据已配置(参考方案1),或子模块使用相对路径(继承父仓库的认证上下文)。
内容的提问来源于stack exchange,提问作者jeremywat
相关产品推荐
相关产品推荐

