这是我正在处理的问题。
我有一个ansible服务器 我有另一台服务器M. 我有其他服务器B1,B2,B3 ......都是ansible所知的
我有一个像
这样的主机文件[CTRL]
M
[SLAVES]
B1
B2
B3
我想在我的主服务器上生成一个ssh密钥(不是ansible本身),并将其部署在我的其他从服务器上,以允许主服务器通过密钥连接到服务器上。
以下是我的尝试:
- hosts: CTRL
remote_user: root
vars_prompt:
- name: ssh_password
prompt : Please enter password for ssh key copy on remote nodes
private: yes
tasks:
- yum: name=sshpass state=present
sudo: yes
- name: generate ssh key on the controller
shell : ssh-keygen -b 2048 -t rsa -f /root/.ssh/id_rsa -q -N /dev/null
- name: copy ssh key to the other nodes
shell : sshpass -p '{{ ssh_password }}' ssh-copy-id root@'{{ item }}'
with_items: groups['SLAVES']
delegate_to: "{{ groups['CTRL'][0] }}"
密钥生成有效,但无论我如何工作,我都有将密钥复制到从属主机的问题
failed: [M -> M] => (item=B1) => {"changed": true, "cmd": "sshpass -p 'mypassword' ssh-copy-id root@'B1'", "delta": "0:00:00.101102", "end": "2016-07-18 11:08:56.985623", "item": "B1", "rc": 6, "start": "2016-07-18 11:08:56.884521", "warnings": []}
failed: [M -> M] => (item=B2) => {"changed": true, "cmd": "sshpass -p 'mypassword' ssh-copy-id root@'B2'", "delta": "0:00:00.101102", "end": "2016-07-18 11:08:56.985623", "item": "B1", "rc": 6, "start": "2016-07-18 11:08:56.884521", "warnings": []}
failed: [M -> M] => (item=B3) => {"changed": true, "cmd": "sshpass -p 'mypassword' ssh-copy-id root@'B3'", "delta": "0:00:00.101102", "end": "2016-07-18 11:08:56.985623", "item": "B1", "rc": 6, "start": "2016-07-18 11:08:56.884521", "warnings": []}
你知道我如何纠正我的代码,或者你有更简单的方法去做我想做的事吗?
谢谢。
答案 0 :(得分:2)
这是没有文件获取的更简洁的解决方案:
---
- hosts: M
tasks:
- name: generate key pair
shell: ssh-keygen -b 2048 -t rsa -f /root/.ssh/id_rsa -q -N /dev/null
args:
creates: /root/.ssh/id_rsa
- name: test public key
shell: ssh-keygen -l -f /root/.ssh/id_rsa.pub
changed_when: false
- name: retrieve public key
shell: cat /root/.ssh/id_rsa.pub
register: master_public_key
changed_when: false
- hosts: SLAVES
tasks:
- name: add master public key to slaves
authorized_key:
user: root
key: "{{ hostvars['M'].master_public_key.stdout }}"
可能的解决方案之一(我的第一个答案):
---
- hosts: M
tasks:
- name: generate key pair
shell: ssh-keygen -b 2048 -t rsa -f /root/.ssh/id_rsa -q -N /dev/null
- name: fetch public key
fetch:
src: /root/.ssh/id_rsa.pub
dest: tmp/
flat: yes
- hosts: SLAVES
tasks:
- name: add master public key to slaves
authorized_key:
user: root
key: "{{ lookup('file', 'tmp/id_rsa.pub') }}"