ansible.builtin.git 模块是 Ansible 的内置模块,用于从 Git 仓库检出代码到目标主机。通过 SSH 检出仓库时,需要指定 SSH 私钥路径,并确保目标主机上的用户已经配置了正确的 SSH 公钥。

主要参数

  • repo:字符串,指定 Git 仓库的 URL(必需参数)。在 SSH 模式下,通常以 git@ 开头。
  • dest:字符串,指定目标主机上的检出路径(必需参数)。
  • update:布尔值,是否从已同步的远程仓库中获取新修订版本,默认为 true。
  • key_file:字符串,指定目标主机上 SSH 私钥文件的路径。这是通过 SSH 检出仓库时的必需参数。

返回值

  • after:返回值,包含更新后最新的提交哈希值。

示例:通过 SSH 检出 Git 仓库

以下是一个示例 Playbook,展示如何使用 git 模块通过 SSH 检出 Git 仓库。

---
- name: git module demo
  hosts: all
  vars:
    repo: "git@github.com:lucab85/ansible-pilot.git"
    dest: "/home/devops/ansible-pilot"
    sshkey: "~/.ssh/id_rsa"
  tasks:
    - name: ensure git pkg installed
      ansible.builtin.yum:
        name: git
        state: present
        update_cache: true
      become: true

    - name: checkout git repo
      ansible.builtin.git:
        repo: "{{ repo }}"
        dest: "{{ dest }}"
        key_file: "{{ sshkey }}"

执行步骤

  1. 准备主机清单文件 确保你的 inventory 文件中包含了目标主机的列表。例如:

    ini [targets] demo.example.com

  2. 配置 SSH 密钥 确保目标主机上的用户已经配置了正确的 SSH 公钥,并且目标主机可以访问 Git 仓库。

  3. 运行 Playbook 使用以下命令运行 Playbook:

    bash ansible-playbook -i inventory git_ssh.yml

执行结果

如果任务成功执行,输出将类似于以下内容:

PLAY [git module demo] *******************************************************

TASK [Gathering Facts] ******************************************************
ok: [demo.example.com]

TASK [ensure git pkg installed] **********************************************
changed: [demo.example.com]

TASK [checkout git repo] *****************************************************
changed: [demo.example.com]

PLAY RECAP *******************************************************************
demo.example.com           : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

注意事项

  1. 安装 Git:确保目标主机上安装了 Git。如果未安装,可以通过 yum 或 apt 模块安装。
  2. 权限问题:如果需要使用 sudo 权限,确保 become: true。
  3. SSH 密钥:
    • key_file 参数指定的是目标主机上的 SSH 私钥路径。
    • 确保目标主机上的用户已经配置了正确的 SSH 公钥,并且公钥已经添加到 Git 服务器。
  4. SSH URL:通过 SSH 检出仓库时,仓库 URL 通常以 git@ 开头。
  5. 返回值:after 返回值可以用于验证最新的提交哈希值。

总结

通过 SSH 检出 Git 仓库时,git 模块需要指定 key_file 参数来指定目标主机上的 SSH 私钥路径。确保目标主机上的用户已经配置了正确的 SSH 公钥,并且公钥已经添加到 Git 服务器。通过灵活使用 repo、dest 和 key_file 参数,你可以轻松地通过 SSH 检出 Git 仓库。