## 主服务器 ssh 公钥认证创建
ssh-keygen -t rsa
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
## 公钥传到目标服务器(首次输入密码,此处为方便将密码显示输入)
sshpass -p "remote password" ssh root@192.168.1.174 "mkdir ~/.ssh/"
sshpass -p "remote password" scp ~/.ssh/id_rsa.pub root@192.168.1.174:~/.ssh/
sshpass -p "remote password" scp ~/.ssh/authorized_keys root@192.168.1.174:~/.ssh/
## 安装
yum install -y epel-release
yum install -y ansible
ansible --version
## inventory 主机清单文件
vim /etc/ansible/hosts
[mysqlservers]
192.168.1.173
192.168.1.174
[allservers]
192.168.1.171
192.168.1.172
192.168.1.173
192.168.1.174
## 验证
ansible all --list-hosts
ansible all -m ping
ansible mysqlservers -m ping
## ansible配置文件
vim /etc/ansible/ansible.cfg
[defaults]
sudo_user=root
remote_port=22
remote_user=root
module_name=command
host_key_checking=False
command_warnings = False
inventory=/etc/ansible/hosts
roles_path=/etc/ansible/roles
log_path=/var/log/ansible.log
private_key_file=/root/.ssh/id_rsa
-------------------------------------------------
## 测试一:拷贝文件及执行命令
-------------------------------------------------
echo "systemctl disable firewalld" > /root/test.sh
ansible mysqlservers -m copy -a "src=/root/test.sh dest=/root/"
ansible mysqlservers -m shell -a "chmod 755 /root/test.sh"
-------------------------------------------------
## 测试二:调用 roles 的 playbook 任务执行
-------------------------------------------------
# 创建角色目录 test
mkdir -p /etc/ansible/roles/test/{default,files,handlers,meta,tasks,templates,vars}
# 创建配置文件 mytest.yml,指定主机组 mysqlservers,指定角色目录 test
vim /etc/ansible/roles/test/mytest.yml
- hosts: mysqlservers
remote_user: root
roles:
- test
## 创建任务脚本
vim /etc/ansible/roles/test/tasks/main.yml
- name: copy test.sh to client
copy: src=/root/test.sh dest=/root/test.sh
- name: chmod for test.sh
shell: chmod 755 /root/test.sh
## 检查脚本
ansible-playbook -C /etc/ansible/roles/test/mytest.yml
## 执行脚本
ansible-playbook /etc/ansible/roles/test/mytest.yml