1、基于端口,用户,密码定义主机清单
格式:
ansible基于ssh连接-i(inventory)参数后指定的远程主机时,也可以写端口,用户,密码。
如:
ansible_ssh_port: 指定ssh端口
ansible_ssh_user: 指定 ssh 用户
ansible_ssh_pass: 指定 ssh 用户登录是认证密码(明文密码不安全)
ansible_sudo_pass: 指明 sudo 时候的密码
如果你是普通用户,且需要提权那你可以使用:
ansible_become=true : 是否需要提升权限。设置为true表示需要提升权限
ansible_become_method=sudo : 这个变量用于指定提升权限的方法。常用的方法有sudo和su
ansible_become_user : 可选)如果你需要以特定的用户身份执行命令,可以设置这个变量。默认通常是root。
ansible_become_pass : 如果你需要自动输入sudo密码,可以设置这个变量。出于安全考虑,推荐使用Ansible Vault来管理密码。
注意:使用密码时,需要把ssh的验证秘钥关闭
echo "StrictHostKeyChecking no" >> $HOME/.ssh/config
或者可以为所有主机或特定主机设置 ansible_ssh_common_args 来跳过 SSH 密钥验证:
172.31.0.12 ansible_user=myuser ansible_password=mypassword ansible_ssh_common_args='-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'
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"
}