ansible批量管理主机免密

1. 安装ansible

# yum install -y ansible

  

2. 创建hosts文件,将所有需要被管理的主机的IP地址都写到文件中

vim /etc/ansible/hosts

[all]
192.168.8.157
192.168.8.159

  

3. 使用ansible-keyscan扫描所有机器的密钥写入~/.ssh/known_hosts中,相当于ssh远程的时候不需要输入 yes

for i in `cat /etc/ansible/hosts`
do
    ssh-keyscan $i >> ~/.ssh/known_hosts
done

  

4. 编写剧本

# vim authkey.yml
---
- name: Set authorized key took from file
  hosts: all
  tasks:
  - name: set ssh key
    authorized_key:
      user: root
      state: present
      key: "{{ lookup('file', '/root/.ssh/id_rsa.pub') }}"

  

5. 检查剧本,看是否有语法报错

[root@host-192-168-8-155 ~]# ansible-playbook --syntax-check /etc/ansible/authkey.yml 

playbook: /etc/ansible/authkey.yml

  

6. 执行剧本,输入密码,批量免密

# ansible-playbook /etc/ansible/authkey.yml -k
SSH password: 

PLAY [Set authorized key taken from file] ************************************************************************************************************************************************************************

TASK [Gathering Facts] *******************************************************************************************************************************************************************************************
ok: [192.168.8.159]
ok: [192.168.8.157]

TASK [set ssh key] ***********************************************************************************************************************************************************************************************
changed: [192.168.8.157]
changed: [192.168.8.159]

PLAY RECAP *******************************************************************************************************************************************************************************************************
192.168.8.157              : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.8.159              : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

  

7. 测试

ssh 192.168.8.157
ssh 192.168.8.159

免密登陆成功

  

 

playbook语法用的是yaml,为了方便书写,设置vim为如下格式,方便快速缩进

[root@room8pc16 myansi]# vim ~/.vimrc
set ai # 自动缩进
set ts=4 # 按tab键缩进4个空格
set et # 将tab键转换成空格
autocmd FileType yaml setlocal sw=2 ts=2 et ai   # 编辑yaml结尾的文件时,一个tab缩进2个空格

  



posted @ 2022-04-07 18:18  江戸川のコナン  阅读(340)  评论(0编辑  收藏  举报
……