如何使用 ansible 从本地 git 存储库克隆到虚拟机

How to clone from a local git repository to a vm using ansible

我有一个本地 git 存储库,我正试图将其克隆到流浪机器上。我正在尝试使用 ansible 的 "git" 模块来执行此操作,我有以下任务,

- name: Clone repository
  git: repo=git://../.git dest=/home/vagrant/source accept_hostkey=True

当我 运行 这个任务时,我收到错误,

failed: [webserver] => {"cmd": "/usr/bin/git ls-remote git://../.git -h refs/heads/HEAD", "failed": true, "rc": 128}
stderr: fatal: unable to connect to ..:
..[0: 42.185.229.96]: errno=Connection timed out

msg: fatal: unable to connect to ..:
..[0: 42.185.229.96]: errno=Connection timed out

FATAL: all hosts have already failed -- aborting

它似乎在尝试在我的 VM 上而不是在我的本地计算机上查找存储库?如何从本地存储库克隆?

git 模块完全在 VM 内执行 - 您必须为其提供 VM 可访问的路径。用你的主机创建一个 vagrant NFS shared/synced 文件夹,或者通过 http/ssh 通过网络将它暴露给 VM。请注意,使用 Virtualbox(以及可能的其他提供程序)的 vagrant 中的非 NFS 共享文件夹只是来回进行哑拷贝,而不是真实的 "sharing"(即,取决于您的存储库有多大,如果它是,您可能会感到抱歉不是 NFS)。

git 命令将 运行 来自远程机器,在本例中是您的 Vagrant VM,而不是您的本地机器。

完成此操作的一种方法是通过 SSH 远程端口转发。您可以将连接从远程(Vagrant VM)上的端口转发到本地计算机的主机+端口。

您的本地计算机需要使 git 存储库可用。这可以通过 sshd 完成,但我会使用相对晦涩的 git-daemon,因为它更容易设置。

在您的 Ansible 清单文件中,将以下选项添加到您的 Vagrant VM 主机。这将在连接期间将来自远程计算机端口 9418 的请求转发到端口 9418 的本地计算机(git-daemon)。

# inventory
webserver ansible_ssh_extra_args="-R 9418:localhost:9418"

# *OR* for a group of hosts
[webservers:vars]
ansible_ssh_extra_args="-R 9418:localhost:9418"

对于这个例子,我假设您本地计算机上的 GIT_DIR 位于 /home/you/repos/your-git-repo/.git。在 运行 启用 Ansible 剧本之前,在另一个终端中启动以下命令(如果要查看输出,请添加 --verbose 选项):

git daemon \
    --listen=127.0.0.1 \
    --export-all \
    --base-path=/home/you/repos \
    /home/you/repos/your-git-repo/.git

您的任务将如下所示:

- git: repo=git://localhost/your-git-repo dest=/home/vagrant/source

现在,当 git 连接到本地主机(相对于您的 Vagrant VM)时,请求将转发到本地计算机上的 git 守护程序 运行ning。