前置条件:假如需要使用服务器A控制服务器B(172.17.0.1)、C(172.17.0.2)、D(172.17.0.3)。
一、安装&配置ansible
1、安装
yum install ansible -y
2、配置
1、准备IP文件ip_list,内容:
172.17.0.1
172.17.0.2
172.17.0.3
2、生成配置项
for n in `cat ip_list`;do echo "$n ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='Ekwing_111111'">>ip_config;done #生成配置项到文件ip_config中
3、添加配置项到ansible配置文件/etc/ansible/hosts中:
echo "[webservers]">/etc/ansible/hosts #webservers是你给需要管理的远程机器们起的一个代号,可随意更改。
cat ip_config >>/etc/ansible/hosts #把刚才生成的配置项追加到配置文件中。
#也可手动编写/etc/ansible/hosts文件为如下内容(功能和上面是一样的):
[webservers]
172.17.0.1 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='Ekwing_111111'
#Ekwing_111111是该机器root用户的登录密码,需要根据实际情况进行修改成你的机器密码
172.17.0.2 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='Ekwing_111111'
172.17.0.3 ansible_ssh_user=root ansible_ssh_port=22 ansible_ssh_pass='Ekwing_111111'
二、使用
1、执行不耗时的命令:
命令:#ansible webservers -f 3 -m shell -a "ls /root"
说明:webservers-你刚才给他们取的名字
-f 3: 相当于多线程. f是参数名,3是线程数量
-m shell: 命令模式. shell表示是shell命令,区别于copy-文件复制。
-a "ls /root": 需要执行的命令。
2、执行耗时的命令(如启动某个服务等):
命令:#ansible webservers -f 3 -m shell -a "nohup your_cmd>>log.txt &"
说明:webservers-你刚才给他们取的名字
-f 3: 相当于多线程. f是参数名,3是线程数量
-m shell: 命令模式. shell表示是shell命令,区别于copy-文件复制。
-a : 需要执行的命令。
nohup: 使子进程跳出父进程的生命周期的限制而独立运行,避免应为A机器断开SSh连接而关闭B、C、D机器上的相关服务.
3、文件拷贝
命令:#ansible webservers -f 3 -m copy -a "src=/root/A.txt dest=/root/copy.txt"
说明:webservers-你刚才给他们取的名字
-f 3: 相当于多线程. f是参数名,3是线程数量
-m copy : 命令模式. 表示这是一个复制文件的命令
-a "src=/root/A.txt dest=/root/copy.txt": 需要执行的命令。src:源文件地址。dest: 目标文件地址。本句含义:将当前机器上的/root/A.txt这个文件拷贝到webservers下的机器们的/root目录下,并且重命名为copy.txt。