Ansible详细学习笔记和实战案例(容易忘记的内容)
一、主机清单
ansible localhost -m command -a "ls"
## 主机列表文件
cat /etc/ansible/hosts
主机描述形式:
-
主机IP地址和主机名
## blue.example.com ## 192.168.100.1
-
散列主机列表和主机组列表
散列主机列表 主机组列表 嵌套主机组列表 ## blue.example.com ## [webservers] ## [server:children] ## 192.168.100.1:999 ## beta.example.com ## webservers ## 192.168.1.100
主机列表范围形式:[起始值:结束值]的ikey:value形式
## www[001:006].example.com 主机名方式表示6台目标主机
## 192.168.1.10[0:9] 主机IP地址表示10台目标主机
补充:利用sshpass
批量实现基于key验证
ssh-keygen -f /root/.ssh/id_isa -P ''
NET=192.168.100
export SSHPASS=magedu
for IP in {
1..200};do
sshpass -e ssh-copy-id $NET.$IP
done
二、Ansible命令操作主机报错
2.1 错误1 Failed to connect to the host via ssh: Permission denied
"msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password)"
- 检查
/etc/ansible/hosts
文件是否正确配置主机 - 删除
/root/.sh/known_hosts
文件,这个文件存储了错误的凭证
2.2 错误2 Failed to connect to the host via ssh: Warning: Permanetly added
"msg": "Failed to connect to the host via ssh: Warning: Permanetly added "IP" (ECDSA) to the list of known hosts.\r\nPermission denied (publickey,gssapi-keyex,gssapi-with-mic,password)"
说明没有传入主机认证信息,添加-k
参数
ansible IP -m command -a "ls" -k
2.3 错误3 Using a SSH password instead of key is not possible
192.168.8.16 | FAILED | rc=-1 >>
Using a SSH passwork instead of a key is not possible because Host key checking is enabled and sshpass does not support this. Please add this hosts's fingerprint to your known_hosts file to manage this host.
可以从错误中得出,文件knwon_hosts
没有这个主机ssh记录
只需要在运行ansible IP -m command -a "ls"
添加主机记录
三、相关工具和常见模块
相关工具:
- ansible-doc
- ansible
- ansibe-galaxy
- ansible-pull
- ansible-playbook
- ansible-vault
- ansible-console
常见模块:https://doc.ansible.com/ansible/latest/modules/modules_by_category.heml
修改配置文件/etc/ansible/ansible.cfg
中的module_name=shell
可改变默认模块为shell
-
Command模块:远程主机执行命令,默认模块,可忽略
-m
选项。不支持$VARNAME< > | ; &
等 -
shell模块:和command相似,用shell执行命令
ansible websrvs -m shell -a 'echo centos | passwd --stdin wang'
-
Script模块:远程主机上运行ansible服务器上的脚本
-
Copy模块:从ansible服务器主控端复制文件到远程主机
-
Fetch模块:从远程主机提取文件到ansible的主控端,copy相反,
src
目前不支持目录 -
File模