1、基于端口,用户,密码定义主机清单
格式:
ansible基于ssh连接-i(inventory)参数后指定的远程主机时,也可以写端口,用户,密码。
如:
ansible_ssh_port: 指定ssh端口
ansible_ssh_user: 指定 ssh 用户
ansible_ssh_pass: 指定 ssh 用户登录是认证密码(明文密码不安全)
ansible_sudo_pass: 指明 sudo 时候的密码
注意:使用密码时,需要把ssh的验证秘钥关闭
echo "StrictHostKeyChecking no" >> $HOME/.ssh/config
ansible默认的主机清单文件在 /etc/ansible/hosts
1) 添加的内容如下
vim /etc/ansible/hosts
[test_qy] # 组
172.31.0.12 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass="Wstest#2022"
2) 测试连通
[root@4h6wu6327422sz ansible]# ansible -i /etc/ansible/hosts test_qy -m ping
172.31.0.12 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
-i
指定主机清单的位置
test_qy
hosts文件中组中的所有主机
-m ping
-m 指定模块
2、基于ssh密钥来访问定义主机清单
1)设置密钥:
ssh-keygen # 一直回车
2)拷贝密钥:
[root@4h6wu6327422sz ansible]# ssh-copy-id 172.31.0.15
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@172.31.0.15's password: 输入密码
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '172.31.0.15'"
and check to make sure that only the key(s) you wanted were added.
3) 添加172.31.0.15主机到 /etc/ansible/hosts 的test-qy组下
[test_qy]
172.31.0.12 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass="Wstest#2022"
172.31.0.15
4) 查看test_qy组下所有主机
[root@4h6wu6327422sz ansible]# ansible test_qy --list
hosts (2):
172.31.0.12
172.31.0.15
5)测试172.31.0.15主机的连通
[root@4h6wu6327422sz ansible]# ansible -i /etc/ansible/hosts 172.31.0.15 -m ping
172.31.0.15 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}