1、测试环境
centos7.9 阿里云ECS
IP地址 | 角色 | |
10.0.0.235 | control | |
10.0.0.236 | node1 | |
10.0.0.237 | node2 |
ansible版本
[root@ceshi ~]# ansible --versionansible 2.9.27 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.7/site-packages/ansible executable location = /usr/bin/ansible python version = 2.7.5 (default, Jun 28 2022, 15:30:04) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
2、操作步骤
2.1 设置hosts
[root@ceshi ~]# cat /etc/ansible/hosts |grep -v "#" |grep -v "^$"[test]10.0.0.[236:237] ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass=password
注意:
1、这里直接在hosts文件里边指定了账号、密码、端口,也可以在环境变量里边指定2、如果是使用多台主机且IP连续,可以使用上述方式进行设置,比如:10.0.0.[1:255]表示10.0.0.1-10.0.0.255这个段的地址 10.0.[1:255].[1:255] 表示10.0.1-255.1-255这个地址段
2.2 在crontrol生成公钥和私钥
[root@ceshi ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
/root/.ssh/id_rsa already exists.
Overwrite (y/n)?
输入命令,一路回车
2.3 编写yaml文件
[root@ceshi ~]# cat add_key.yml
---
- name: add key
hosts: all
tasks:
- name: key
authorized_key:
user: root
key: "{{ lookup('file', '/root/.ssh/id_rsa.pub') }}"
state: present
注意:yml文件可以在任意路径
2.4 运行playbook
[root@ceshi ~]# ansible-playbook add_key.yml
PLAY [add key] *********************************************************************************************************************************************************
TASK [Gathering Facts] *************************************************************************************************************************************************
ok: [10.0.0.236]
ok: [10.0.0.237]
TASK [key] *************************************************************************************************************************************************************
ok: [10.0.0.236]
ok: [10.0.0.237]
PLAY RECAP *************************************************************************************************************************************************************
10.0.0.236 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
10.0.0.237 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
2.5 取消hosts文件里边关于端口、密码的设置
[root@ceshi ~]# cat /etc/ansible/hosts |grep -v "#" |grep -v "^$"
[test]
10.0.0.[236:237]
2.6 验证测试
[root@ceshi ~]# ansible all -m shell -a "ip -4 a |grep inet"
10.0.0.237 | CHANGED | rc=0 >>
inet 127.0.0.1/8 scope host lo
inet 10.0.0.237/24 brd 10.0.0.255 scope global dynamic eth0
10.0.0.236 | CHANGED | rc=0 >>
inet 127.0.0.1/8 scope host lo
inet 10.0.0.236/24 brd 10.0.0.255 scope global dynamic eth0
如果是可以正常输出IP地址,表示免密设置成功