ansible是一个批量执行命令的工具

安装软件

安装 EPEL 仓库

1
yum install epel-release -y

安装 Ansible

1
yum install ansible -y

使用

  • 使用前需要定义两个文件:
    一个指定需要批量执行的主机hosts.ini,可以随意指定名称;一个指定需要运行的命令和动作command.yml,虽然可以直接指定需要运行的命令,但通过该文件可以回显执行成功或失败的主机和成功或失败的动作。
  1. hosts.ini:
1
2
3
4
5
[hostst_g]
此处填写ip
[hosts_g:vars]
ansible_ssh_user=root ##账号
ansible_ssh_pass=123456 ##密码
  1. command.yml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- name: 在远程主机上执行任意命令  
hosts: all
gather_facts: no
tasks:
- name: 执行一个特定命令
command: echo "你好,世界!"
# 使用 command 模块执行简单命令,不支持管道和重定向
- name: 列出目录中的文件
command: ls /path/to/directory
# 列出指定目录中的所有文件
- name: 使用 shell 运行包含管道的命令
shell: echo "你好,世界!" | grep 你好
# 使用 shell 模块支持管道、变量和重定向等 shell 特性
- name: 使用 hell 特性运行命令
shell: cat /etc/passwd | grep root
# 通过管道过滤包含 "root" 的行

可使用shell:模拟终端上所有执行的命令。

  • 使用命令
1
ansible-playbook -i hosts.ini command.yml

安装ansible示例

文件结构

1
2
3
4
5
6
7
project_dir/
├── install_tomcat.yml # Ansible 剧本
├── hosts.ini # 主机信息
└── html/ # 本地网页目录(你已经准备好了)
├── index.html
└── images/
└── logo.png

hosts.ini 文件内容:

目标主机信息

1
2
3
4
5
6
7
8
[test]
192.168.1.101
192.168.1.102

[test:vars]
ansible_user=root
ansible_ssh_pass=你的密码
ansible_python_interpreter=/usr/bin/python3

install_tomcat.yml 内容

执行的任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
---
- name: 在所有 test 主机上安装并配置 Tomcat
hosts: test
become: yes
tasks:

- name: 安装 Java(Tomcat 依赖)
package:
name: java-1.8.0-openjdk
state: present

- name: 创建 tomcat 用户
user:
name: tomcat
shell: /bin/false
system: yes
create_home: no

- name: 下载 Tomcat 安装包
get_url:
url: https://dlcdn.apache.org/tomcat/tomcat-9/v9.0.89/bin/apache-tomcat-9.0.89.tar.gz
dest: /tmp/tomcat.tar.gz

- name: 创建 Tomcat 安装目录
file:
path: /opt/tomcat
state: directory
owner: tomcat
group: tomcat
mode: '0755'

- name: 解压 Tomcat 安装包
unarchive:
src: /tmp/tomcat.tar.gz
dest: /opt/tomcat
remote_src: yes
creates: /opt/tomcat/apache-tomcat-9.0.89

- name: 配置 Tomcat 环境变量(可选)
copy:
dest: /etc/profile.d/tomcat.sh
content: |
export CATALINA_HOME=/opt/tomcat/apache-tomcat-9.0.89

- name: 备份默认 webapps 目录
command: mv /opt/tomcat/apache-tomcat-9.0.89/webapps /opt/tomcat/apache-tomcat-9.0.89/webapps.bak
args:
creates: /opt/tomcat/apache-tomcat-9.0.89/webapps.bak

- name: 创建网页目录 /var/www/html
file:
path: /var/www/html
state: directory
owner: tomcat
group: tomcat
mode: '0755'

- name: 上传本地 html 文件到远程 /var/www/html
copy:
src: html/
dest: /var/www/html/
owner: tomcat
group: tomcat
mode: '0644'

- name: 创建 /var/www/html 到 Tomcat webapps 的符号链接
file:
src: /var/www/html
dest: /opt/tomcat/apache-tomcat-9.0.89/webapps
state: link
force: yes

- name: 启动 Tomcat 服务
shell: nohup /opt/tomcat/apache-tomcat-9.0.89/bin/startup.sh &
args:
chdir: /opt/tomcat/apache-tomcat-9.0.89/bin