1. 程式人生 > >Ansible推送ssh秘鑰

Ansible推送ssh秘鑰

Linux Ansible 運維 自動化

一、系統環境和安裝軟件版本
1),系統安裝
[root@centos6 ~]# cat /etc/issue
CentOS release 6.5 (Final)
[root@centos6 ~]# uname -r
2.6.32-431.el6.x86_64
2)4臺主機Ansible(192.168.0.22)另外3臺主機IP分別是(192.168.0.24,192.168.0.156和192.168.0.157)
3)安裝YUM源
[root@centos6 ~]# rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
[root@centos6 ~]# yum install ansible -y
[root@centos6 ~]# ansible --version
ansible 2.4.2.0
config file = /etc/ansible/ansible.cfg
configured module search path = [u‘/root/.ansible/plugins/modules‘, u‘/usr/share/ansible/plugins/modules‘]
ansible python module location = /usr/lib/python2.6/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.6.6 (r266:84292, Aug 18 2016, 15:13:37) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)]
二、在Ansible主機上配置
1)在推送主機上做ssh秘鑰
[root@Ansible .ssh]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
a3:08:ab:02:bf:7b:12:7d:d9:8f:9c:a9:67:38:53:a1 [email protected]
The key‘s randomart image is:
+--[ RSA 2048]----+
. .. +S. . .o..E.o. .......+ = ..o . + B . o o= .*

+-----------------+
2)查看生成的秘鑰。
[root@Ansible .ssh]# ls -a
. .. id_rsa id_rsa.pub
3)在Ansible上配置hosts
[root@Ansible ansible]#vim hosts
在內容最後加上如下內容:
[test]
192.168.0.24 ansible_user=root ansible_ssh_pass="hwg123"
192.168.0.156 ansible_user=root ansible_ssh_pass="hwg123"
192.168.0.157 ansible_user=root ansible_ssh_pass="hwg123"
4)接著創建push.ssh.ymal腳本
[root@Ansible ansible]# cat push.ssh.ymal
#Using alternate directory locations:

  • hosts: test
    user: root
    tasks:
    • name: ssh-copy
      authorized_key:
      user=root
      key="{{ lookup(‘file‘ ,‘/root/.ssh/id_rsa.pub‘) }}"
      tags:
      • sshkey
        5)需要修改ansible.cfg的#host_key_checking= False取消註釋
        [root@Ansible ansible]# vim ansible.cfg
        host_key_checking = False
        三、最後運行push.ssh.ymal
        [root@Ansible ansible]# ansible-playbook push.ssh.ymal

PLAY [test] ****

TASK [Gathering Facts] *****
ok: [192.168.0.24]
ok: [192.168.0.157]
ok: [192.168.0.156]

TASK [ssh-copy] ****
changed: [192.168.0.157]
changed: [192.168.0.156]
changed: [192.168.0.24]

PLAY RECAP *****
192.168.0.156 : ok=2 changed=1 unreachable=0 failed=0
192.168.0.157 : ok=2 changed=1 unreachable=0 failed=0
192.168.0.24 : ok=2 changed=1 unreachable=0 failed=0
技術分享圖片
好了,Ansible主機端使用ssh [email protected] 看看需要密碼不,不需要證明配置正確。

Ansible推送ssh秘鑰