将SSH作为参数传递给ansible-playbook

时间:2017-07-20 09:41:13

标签: docker ssh ansible docker-image

我有Dockerfile:

FROM ubuntu:16.04

ARG ssh_prv_key
ARG ssh_pub_key

RUN apt-get update && \
    apt-get install ... USUAL INSTALL STUFF ...

WORKDIR /app/

CMD git clone MY_REPO

我构建这样的图像:

$ docker build -t example --build-arg ssh_prv_key="$(cat ~/.ssh/id_rsa)" --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)" .

当我从这个图像创建容器时,它会自动拉取git-repo并使用-v参数将其保存在主机上,并使用--rm自我销毁。

当我尝试使用ansible docker_image模块执行相同的操作时,问题就开始了。

playbook看起来像这样:

---
- hosts: localhost
  environment:
    PYTHONPATH: /usr/local/lib/python2.7/site-packages/

  tasks:
  - name: create image from Dockerfile
    docker_image:
      path: /home/demaunt/Jun/dock_click
      dockerfile: biba.dockerfile
      name: myimage
      buildargs: 
        ssh_pub_key: '{{ pub }}'
        ssh_prv_key: '{{ pvt }}'

我这样开始:

ansible-playbook bibansible.yml --extra-vars "pub=$(cat ~/.ssh/id_rsa.pub) pvt=$(cat ~/.ssh/id_rsa)"

图像是成功构建的,但在运行容器时,我得到Permission错误(publickey)。 我也尝试将参数传递给.yml文件,如下所示:

---
- hosts: localhost
  environment:
    PYTHONPATH: /usr/local/lib/python2.7/site-packages/

  tasks:
  - name: create image from Dockerfile
    docker_image:
      path: /home/demaunt/Jun/dock_click
      dockerfile: biba.dockerfile
      name: myimage
      buildargs: 
        ssh_pub_key:
          command: cat ~/.ssh/id_rsa.pub
        ssh_prv_key: 
          command: cat ~/.ssh/id_rsa

P.S。我知道将ssh密钥传递给图像不是最好的选择,但它可以作为临时解决方案。

1 个答案:

答案 0 :(得分:1)

您无法在此级别使用command 但要获取本地文件的内容,请查看lookup

[...]
buildargs: 
    ssh_pub_key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"
    ssh_prv_key: "{{ lookup('file', '~/.ssh/id_rsa') }}"