2017-07-07 86 views
8

我想创建一个Ansible操作手册,它将从我们的开发团队计算机和CI/CD服务器运行。Ansible任务 - 无需SSH转发克隆私人git

剧本中的任务之一是从私人仓库获取我们项目的源代码。由于剧本必须从CI/CD服务器运行,因此我们无法使用SSH转发。

我想到的是将必要的SSH私钥复制到远程主机,然后使用密钥从私有git存储库克隆代码。

但是,尝试此操作时,克隆任务将挂起。当试图手动启动命令时,它会要求输入SSH私钥的密码。 SSH密钥不使用密码(空白)。

任何人都可以分享他们的解决方案(可能很常见)的问题?

如果有人需要,这是我目前的剧本:

- name: Create SSH directory 
    file: path=/root/.ssh state=directory 

- name: Copy SHH key for Git access 
    copy: 
    content: "{{ git_ssh_key }}" 
    dest: /root/.ssh/id_rsa 
    owner: root 
    group: root 
    mode: 0600 

# Also tried this, but it also hangs 
#- name: Start SSH agent and add SSH key 
# shell: eval `ssh-agent -s` && ssh-add 

- name: Get new source from GIT 
    git: 
    key_file: /root/.ssh/id_rsa 
    repo: "[email protected]:user/repo.git" 
    dest: "{{ staging_dir }}" 
    depth: 1 
    accept_hostkey: yes 
    clone: yes 

我使用ansible 2.3.1.0, python version = 2.7.12

+0

“*当试图手动启动命令时,它会要求输入SSH私钥的密码*” - 这是一个编程问题? – techraf

+0

我需要一种方法来编写一个任务来输入密码(编程问题)或一个不同的方法,我根本不需要输入它(操作问题)。 –

+0

使用没有密码的密钥。 – techraf

回答

2

下面是步骤,使其工作(与Ansible 2.3.1和Python 2.7的测试。 10上的MacOS,Ubuntu的LTS):

  1. 生成新SSH密钥对没有密码ssh-keygen -f my_ssh_key -N ''

  2. 添加my_ssh_key.pub到你的资料库服务器的用户配置文件

  3. 测试有以下剧本:

_

--- 
- hosts: localhost 
    gather_facts: no 
    vars: 
    git_ssh_public_key: "Your public ssh key" 
    git_ssh_key: | 
       -----BEGIN RSA PRIVATE KEY----- 
       .... actual key here .... 
       -----END RSA PRIVATE KEY----- 
    tasks: 
    - name: Copy SSH public key file 
    copy: 
     content: "{{ git_ssh_public_key }}" 
     dest: /root/.ssh/id_rsa.pub 
     mode: 0644 

    - name: Copy SSH private key file 
    copy: 
     content: "{{ git_ssh_key }}" 
     #src: id_rsa 
     dest: /root/.ssh/id_rsa 
     mode: 0600 

    - name: Get new source from GIT 
    git: 
     repo: "[email protected]:user/repo.git" 
     dest: "/var/www/" 
     depth: 1 
     accept_hostkey: yes 
     clone: yes 

重要的安全通告

如果你想在现实世界中使用示例,请不要保存私钥明文 - 使用Ansible Vault

你也应该不是使用root作为你的用户。创建没有sudo权限的新用户会更安全。

+0

这对我仍然不起作用。当试图'''git fetch'''它仍然要求输入密码'''输入密码'/root/.ssh/id_rsa'的密码短语:'''。也许有一些SSH配置参数会绕过密码询问它什么时候是空的? –

+0

为什么'git fetch'?检查一下可靠的'git'模块。并确保提供的密钥文件对您的回购服务器有效。 –

+0

在一个可靠的脚本中,我使用了默认的命令。但它无所事事。这就是为什么我手动连接到目标机器,并测试连接到我的私人回购的git命令。即使密钥是在无密码的情况下生成的,仍然会要求输入密钥(只需按Enter键)。 –

0

我想这个问题是,对于自动化任务,Git是不使用SSH密钥。我读过(由四处找一两分钟),与git的2.10,可以提供SSH的东西叫混帐时候传球....所以我想你可以尝试这样的:

git -c core.sshCommand='ssh -i /path/to/private/key' fetch origin 

或者无论你想使用什么其他命令。你也可以将其固定配置:

git config core.sshCommand 'ssh -i /path/to/private/key' 

不管怎样,希望帮助一点点

Specify private SSH-key to use when executing shell command with or without Ruby?

+0

我使用的是git v.1.7.1,所以这对我不起作用。 –