目录
- ansible
- 环境准备
- 安装
- 简单使用
- ansible常用模块
- command模块
- copy模块
- 案例1:传输文件
- 案例2:指定用户、组
- 案例3:文件备份
- 查看
- shell模块
- fetch模块
- file模块
- 创建文件夹
- 创建文件
- 创建软链接
- 查看
- 删除文件/目录/软链接
- yum模块
- get_url模块
- script模块
- service模块
- 开机启动网络服务
- 关闭防火墙
- mount模块
- 案例
- 查看挂载
- crond模块
- 创建计划任务
- 在客户端查看
- 删除计划任务
- 用户管理模块
- user
- group
- ansible-playbook
- 使用
- 1、在所有机器的/tmp下面创建shengxia.txt
- 2、添加定时同步时间的定时任务
- 3、安装redis服务
- 4、带配置文件的安装redis服务
- 变量
- 1、vars,vars_files变量
- 2、ansible-facts变量
- 3、ansible-register变量
- tags标签
- handlers和template
ansible
Ansible是一款开源的自动化工具,它可以帮助用户自动化配置、部署和管理多台服务器。它使用一个基于Python的简单语言描述系统配置,可以轻松地扩展和自定义功能。Ansible是一个开源工具,可以运行在Linux、macOS和Windows操作系统上。它使用SSH协议来远程管理计算机,可以快速地部署、配置和管理复杂的IT环境。Ansible被广泛应用于DevOps和自动化领域,可以帮助企业实现快速部署、快速响应和持续交付。
环境准备
1.准备两台centos7的服务器
服务端IP:192.168.40.137
客户端IP:192.168.40.150
2.服务端建立免密连接
[root@ansible-server ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:/GuqSZngT59SjHOslepF3OAFffzJ4s0FwnXb/W8WJwQ root@ansible-server
The key's randomart image is:
+---[RSA 2048]----+
| .. oE.. .|
| .. =...+|
| . .. +.+o|
| + + ..+ o|
| . +S... +.oo|
| . .o+B. . o.+|
| . =B. . +|
| +++ ... o |
| .=o+o. |
+----[SHA256]-----+
[root@ansible-server ~]# ssh-copy-id root@192.168.40.150
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/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@192.168.40.150's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.40.150'"
and check to make sure that only the key(s) you wanted were added.
[root@ansible-server ~]# ssh root@192.168.40.150
Last login: Mon May 22 15:52:18 2023 from 192.168.40.137
[root@ansible-client ~]# ##登录成功
安装
在管理节点上(server端)安装epel源,ansible
[root@ansible-server ~]# yum install epel-release -y
[root@ansible-server ~]# yum install ansible -y
查看版本
[root@ansible-server lianxi]# ansible --version
ansible 2.9.27
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Oct 14 2020, 14:45:30) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
简单使用
使用格式
HOST-PATTERN #匹配主机模式,如all表示所有主机
-m MOD_NAME #模块名 如:ping
-a MOD_ARGS #模块执行的参数
-f FORKS #生成几个子进行程执行
-C #(不执行,模拟跑)
-u Username #某主机的用户名
-c CONNection #连接方式(default smart)
进入ansible目录,配置主机清单
[root@ansible-server ansible]# vim hosts
[root@ansible-server ansible]# pwd
/etc/ansible
############################################
[webservers]
192.168.40.150
[nfs]
192.168.40.138
[db]
192.168.40.152
给主机清单上的主机安装tree命令
[root@ansible-server ansible]# ansible webservers -m yum -a "name=tree state=installed"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"installed": [
"tree"
]
},
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.ustc.edu.cn\n * epel: mirrors.cqu.edu.cn\n * extras: mirrors.ustc.edu.cn\n * updates: mirrors.ustc.edu.cn\nResolving Dependencies\n--> Running transaction check\n---> Package tree.x86_64 0:1.6.0-10.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n tree x86_64 1.6.0-10.el7 base 46 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 46 k\nInstalled size: 87 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : tree-1.6.0-10.el7.x86_64 1/1 \n Verifying : tree-1.6.0-10.el7.x86_64 1/1 \n\nInstalled:\n tree.x86_64 0:1.6.0-10.el7 \n\nComplete!\n"
]
}
显示ip地址
[root@ansible-server ansible]# ansible webservers -m shell -a "ip add"
192.168.40.150 | CHANGED | rc=0 >>
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 00:0c:29:04:07:da brd ff:ff:ff:ff:ff:ff
inet 192.168.40.150/24 brd 192.168.40.255 scope global ens33
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fe04:7da/64 scope link
valid_lft forever preferred_lft forever
ansible常用模块
command模块
这个模块是默认模块,ansible不加上模块,默认就使用这个模块,仅支持简单命令,不支持特殊符号,管道……
[root@ansible-server .ssh]# ansible all -a 'ip add'
copy模块
注意src路径后面带/ 表示带里面的所有内容复制到目标目录下(目录内容),不带/是目录递归复制过去(目录+目录内容)
从本地copy文件分发到目录主机路径 | |
src | 源文件路径 |
dest | 目标路径 |
owner | 属主 |
group | 属组 |
mode | 权限 |
backup | 指定为yes,如果文件存在且没有修改,则不会进行变化,如果文件进行修改,则会在覆盖前进行备份,并且会加上时间 |
案例1:传输文件
[root@ansible-server lianxi]# ansible webservers -m copy -a "src=ip.txt dest=/tmp/ mode=755"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "9a8969fb43754bd90bc5354a136c96a3a9471b7f",
"dest": "/tmp/ip.txt",
"gid": 0,
"group": "root",
"md5sum": "f267f938878fbf8c4e8af9679ffac5de",
"mode": "0755",
"owner": "root",
"size": 199,
"src": "/root/.ansible/tmp/ansible-tmp-1684758967.64-20158-249795873318248/source",
"state": "file",
"uid": 0
}
案例2:指定用户、组
[root@ansible-server lianxi]# ansible all -m copy -a "src=/lianxi/count_word.sh dest=/tmp/ owner=xia group=xia"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "eeef5b8ccc32712a8b63469293360c2976586eae",
"dest": "/tmp/count_word.sh",
"gid": 1003,
"group": "xia",
"md5sum": "98c830d57131ebd4f6389d0b6f28aac7",
"mode": "0644",
"owner": "xia",
"size": 192,
"src": "/root/.ansible/tmp/ansible-tmp-1685349234.32-15692-220581171639992/source",
"state": "file",
"uid": 1003
}
案例3:文件备份
[root@ansible-server lianxi]# ansible webservers -m copy -a "src=ip.txt dest=/tmp/ mode=755 backup=yes"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"backup_file": "/tmp/ip.txt.8810.2023-05-23@08:37:54~",
"changed": true,
"checksum": "bfd2af727833fc1f66268c3074f1c183f9509eda",
"dest": "/tmp/ip.txt",
"gid": 0,
"group": "root",
"md5sum": "2d458f30b3aadee983835ac95af705d0",
"mode": "0755",
"owner": "root",
"size": 218,
"src": "/root/.ansible/tmp/ansible-tmp-1685349753.46-16194-96160567283668/source",
"state": "file",
"uid": 0
}
查看
[root@ansible-client tmp]# ll
总用量 4
-rwxr-xr-x 1 root root 199 5月 22 19:33 ip.txt
[root@ansible-client tmp]# ls
count_word.sh ip.txt.8810.2023-05-23@08:37:54~ ## 修改文件后的备份文件
glances.log ip.txt
shell模块
shell模块与command模块类似,shell模块支持特殊符号,执行脚本
[root@ansible-server lianxi]# ansible webservers -m shell -a "cat /tmp/ip.txt"
192.168.40.150 | CHANGED | rc=0 >>
172.16.130.26 16274.7
172.16.20.126 8783.61
172.16.130.33 5876.59
172.16.130.33 5876.59
172.16.13.145 5389.23
172.16.130.26 16274.7
172.16.130.26 16274.7
172.16.145.173 4974.36
172.16.130.33 5876.59
fetch模块
从远程主机拉取文件到本地,如将一键安装安装nginx脚本拉取到本地目录
[root@ansible-server lianxi]# ansible all -m fetch -a "src=/lianxi/onekey-install-nginx.sh dest=/root"
192.168.40.150 | CHANGED => {
"changed": true,
"checksum": "d1313df71677b74d3c56a62d6317bb4cedd7295f",
"dest": "/root/192.168.40.150/lianxi/onekey-install-nginx.sh",
"md5sum": "bbc2ca06e1645df3ab194b7c281befdf",
"remote_checksum": "d1313df71677b74d3c56a62d6317bb4cedd7295f",
"remote_md5sum": null
}
[root@ansible-server lianxi]# cd ~
[root@ansible-server ~]# ls
192.168.40.150 anaconda-ks.cfg
[root@ansible-server ~]# cd 192.168.40.150/
[root@ansible-server 192.168.40.150]# ls
lianxi
[root@ansible-server 192.168.40.150]# cd lianxi/
[root@ansible-server lianxi]# ls
onekey-install-nginx.sh
file模块
管理文件或目录,软连接
file模块中的选项 | |
path | 路径(⽬录,⽂件) 必须要写 |
src | 源⽂件⼀般⽤于link (创建软连接模式)⽤于指定源⽂件 |
state | state状态(模式) state=directory 创建⽬录 state=file (默认) 更新⽂件,如果⽂件不存在也不创建. state=link 创建软连接 state=touch 创建⽂件 state=absent删除 |
创建文件夹
[root@ansible-server lianxi]# ansible all -m file -a "path=/lianxi/ansible state=directory"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/lianxi/ansible",
"size": 6,
"state": "directory",
"uid": 0
}
[root@ansible-server ~]# ansible all -a 'ls -ld /lianxi/ansible'
192.168.40.150 | CHANGED | rc=0 >>
drwxr-xr-x 2 root root 6 8月 9 22:59 /lianxi/ansible
192.168.40.138 | CHANGED | rc=0 >>
drwxr-xr-x. 2 root root 6 8月 10 10:35 /lianxi/ansible
创建文件
[root@ansible-server lianxi]# ansible all -m file -a "path=/lianxi/ansible/test.txt state=touch"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/lianxi/ansible/test.txt",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"size": 0,
"state": "file",
"uid": 0
}
[root@ansible-server ~]# ansible all -a 'ls -l /lianxi/ansible/test.txt'
192.168.40.150 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 8月 9 23:03 /lianxi/ansible/test.txt
192.168.40.138 | CHANGED | rc=0 >>
-rw-r--r--. 1 root root 0 8月 10 10:39 /lianxi/ansible/test.txt
创建软链接
[root@ansible-server lianxi]# ansible all -m file -a "src=/lianxi/snat.sh path=/lianxi/ansible/snat.sh.link state=link"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/lianxi/ansible/snat.sh.link",
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"size": 15,
"src": "/lianxi/snat.sh",
"state": "link",
"uid": 0
}
查看
[root@ansible-client lianxi]# cd ansible/
[root@ansible-client ansible]# ll
总用量 0
lrwxrwxrwx 1 root root 15 5月 22 19:59 snat.sh.link -> /lianxi/snat.sh
-rw-r--r-- 1 root root 0 5月 22 19:55 test.txt
删除文件/目录/软链接
[root@ansible-server ~]# ansible all -m file -a "path=/lianxi/ansible/test.txt state=absent"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"path": "/lianxi/ansible/test.txt",
"state": "absent"
}
[root@ansible-server ~]# ansible all -m file -a "path=/lianxi/ansible/snat.sh.link state=absent"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"path": "/lianxi/ansible/snat.sh.link",
"state": "absent"
}
[root@ansible-server ~]# ansible all -m file -a "path=/lianxi/ansible state=absent"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"path": "/lianxi/ansible",
"state": "absent"
}
yum模块
软件包模块 | ||
name | 安装的包名 | |
state | 安装的模式 present、installed、latest 表示安装 absent、removed 表示删除 |
[root@ansible-server lianxi]# ansible all -m yum -a "name=glances state=installed"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"installed": [
"glances"
]
},
"msg": "https://epel.excellmedia.net/7/x86_64/Packages/p/python2-psutil-5.6.7-1.el7.x86_64.rpm: [Errno 14] curl#35 - \"Encountered end of file\"\nTrying other mirror.\n",
"rc": 0,
"results": [
……………………
]
}
get_url模块
get_url下载功能 | |
url | 指定要下载的路径 |
dest | 下载到哪个目录 |
## 创建目录
[root@ansible-server ~]# ansible all -m file -a "path=/server/tools/ state=directory"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/server/tools/",
"size": 6,
"state": "directory",
"uid": 0
}
## 下载软件包
[root@ansible-server ~]# ansible all -m get_url -a "url=https://tengine.taobao.org/download/tengine-2.3.3.tar.gz dest=/server/tools"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum_dest": null,
"checksum_src": "19201832563541de00995f326333ca778ccbbe5a",
"dest": "/server/tools/tengine-2.3.3.tar.gz",
"elapsed": 3,
"gid": 0,
"group": "root",
"md5sum": "01651b1342c406b933490dd8f2962b36",
"mode": "0644",
"msg": "OK (2848144 bytes)",
"owner": "root",
"size": 2848144,
"src": "/root/.ansible/tmp/ansible-tmp-1685362457.74-25720-39406406786423/tmpB_tPb1",
"state": "file",
"status_code": 200,
"uid": 0,
"url": "https://tengine.taobao.org/download/tengine-2.3.3.tar.gz"
}
查看
[root@ansible-server ~]# ansible all -a "tree /server"
192.168.40.150 | CHANGED | rc=0 >>
/server
└── tools
└── tengine-2.3.3.tar.gz
1 directory, 1 file
script模块
把本地的脚本传到远端执行
[root@ansible-server lianxi]# vim test.sh
[root@ansible-server lianxi]# cat test.sh
#!/bin/bash
echo "ansible script test!" >>/lianxi/ansible_script.txt
[root@ansible-server lianxi]# ansible all -m script -a "test.sh"
192.168.40.150 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 192.168.40.150 closed.\r\n",
"stderr_lines": [
"Shared connection to 192.168.40.150 closed."
],
"stdout": "",
"stdout_lines": []
}
在客户端查看
[root@ansible-client lianxi]# ls
ansible ansible_script.txt nginx onekey-install-nginx.sh snat.sh
[root@ansible-client lianxi]# cat ansible_script.txt
ansible script test!
service模块
服务管理模块 | |
name | 服务的名字 |
state | 服务的状态 state=started 开启 state=stopped 关闭 state=reloaded重新读取配置文件 state=restarted 重启 |
enabled | 是否开机启动 |
runlevel | 启动级别 |
daemon_reload | yes表示启动 <==> systemctl daemon-reolad 重新加载systemctl配置 |
开机启动网络服务
[root@ansible-server etc]# ansible all -m service -a "name=network state=restarted enabled=true daemon_reload=yes"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"enabled": true,
"name": "network",
"state": "started",
"status": {
…………………………
}
}
关闭防火墙
[root@ansible-server etc]# ansible all -m service -a "name=firewalld state=stopped"
192.168.40.138 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"name": "firewalld",
"state": "stopped",
"status": {
"ActiveEnterTimestampMonotonic": "0",
……
}
}
192.168.40.150 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"name": "firewalld",
"state": "stopped",
"status": {
……
"WatchdogUSec": "0"
}
}
mount模块
mount挂载功能 | |
fstype | 指定文件系统(nfs) |
src | 源地址(nfs服务器端地址 例如:192.168.40.138/share) |
path | 挂载点 |
/etc/fstab
文件是一个配置文件,用于在 Linux 系统启动时自动挂载文件系统。系统在启动时会读取 /etc/fstab
文件中的配置信息,并按照其中的指示挂载文件系统
mount模块的state参数 | |
absent | 卸载并修改/etc/fstab(清理配置) |
unmounted | 卸载不修改/etc/fstab |
present | 仅修改/etc/fstab不挂载 |
mounted |
|
remounted | 重新挂载 |
案例
将nfs共享的目录(/data/share)
挂载到ansible-server(/lianxi/share_mount)
目录下
[root@ansible-server lianxi]# ansible nfs -m mount -a "fstype=nfs src='192.168.40.138:/data/share' path=/lianxi/share_mount state=mounted"
192.168.40.138 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dump": "0",
"fstab": "/etc/fstab",
"fstype": "nfs",
"name": "/lianxi/share_mount",
"opts": "defaults",
"passno": "0",
"src": "192.168.40.138:/data/share"
}
查看挂载
[root@ansible-server lianxi]# ansible nfs -a "df -Th"
192.168.40.138 | CHANGED | rc=0 >>
文件系统 类型 容量 已用 可用 已用% 挂载点
devtmpfs devtmpfs 475M 0 475M 0% /dev
tmpfs tmpfs 487M 0 487M 0% /dev/shm
tmpfs tmpfs 487M 20M 467M 5% /run
tmpfs tmpfs 487M 0 487M 0% /sys/fs/cgroup
/dev/mapper/centos-root xfs 17G 6.1G 11G 36% /
/dev/sda1 xfs 1014M 138M 877M 14% /boot
tmpfs tmpfs 98M 0 98M 0% /run/user/0
192.168.40.138:/data/share nfs4 17G 6.1G 11G 36% /lianxi/share_mount
crond模块
通过cron模块对目标主机生成计划任务 | 定时任务配置中的内容 | |
name | 定时任务的名字 | |
minute | */2 | 分钟,表示每两分钟执行一次 |
hour | 小时 | |
day | 天 | |
month | 月 | |
week | 周 | |
job | 命令/脚本 | 任务 |
state | 状态 | present 添加定时任务 absent 删除定时任务 |
创建计划任务
## 编写一个脚本,实现备份功能
[root@ansible-server ansible]# cat backup_pwd.sh
#!/bin/bash
mkdir -p /backup
tar czf /backup/passwd.tar.gz /etc/passwd
[root@ansible-server ansible]# chmod +x backup_pwd.sh
## 把脚本传过去
[root@ansible-server ansible]# ansible all -m copy -a "src=backup_pwd.sh dest=/lianxi"
## 实现计划任务,每天2点半执行脚本
[root@ansible-server ansible]# ansible all -m cron -a "minute=30 hour=2 job='bash /lianxi/backup_pwd.sh' name=backup_pwd"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"backup_pwd"
]
}
在客户端查看
[root@ansible-client lianxi]# crontab -l
#Ansible: backup_pwd
30 2 * * * bash /lianxi/backup_pwd.sh
删除计划任务
[root@ansible-server ansible]# ansible all -m cron -a "name=backup_pwd state=absent"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": []
}
用户管理模块
user
user模块 | |
name | 指定用户名 |
uid | 指定uid |
group | 指定用户组 |
shell | 指定命令解释器 |
create_home | 是否创建家目录(yes/no) |
state | present 添加 absent 删除 |
创建一个用户zhangsan
,uid为5555
,shell解释器为/bin/sh
,创建家目录
[root@ansible-server ~]# ansible all -m user -a "name=zhangsan uid=5555 shell=/bin/sh create_home=yes state=present"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"comment": "",
"create_home": true,
"group": 5555,
"home": "/home/zhangsan",
"name": "zhangsan",
"shell": "/bin/sh",
"state": "present",
"system": false,
"uid": 5555
}
##### 查看
[root@ansible-server ~]# ansible all -a "id zhangsan"
192.168.40.150 | CHANGED | rc=0 >>
uid=5555(zhangsan) gid=5555(zhangsan) 组=5555(zhangsan)
group
group模块 | |
name | 指定用户组名字 |
gid | 指定组的gid |
state | present 添加 absent 删除 |
创建一个组lisi
,gid为6666
[root@ansible-server ansible]# ansible all -m group -a "name=lisi gid=6666 state=present"
192.168.40.150 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"gid": 6666,
"name": "lisi",
"state": "present",
"system": false
}
ansible-playbook
playbook是一种YAML格式的文件,其中定义了Ansible在特定主机或主机组上执行操作的指令集。它可以用来自动化各种IT任务,如部署应用程序、配置服务器、管理网络设备等。Playbook通常包含一些任务,这些任务对应了一些模块,这些模块可以执行系统管理任务,如在服务器上安装软件包、复制文件、启动服务等。Playbook还可以包含变量和模板,以实现更灵活和可配置的自动化任务。
在 Ansible Playbook 中,包含以下元素:
-
hosts
: 定义主机或组的名称。 -
vars
: 定义变量或变量组。 -
tasks
: 定义要执行的任务列表。 -
roles
: 定义角色的名称和任务。 -
handlers
: 定义需要执行的处理程序任务。 -
templates
: 定义模板文件以使用变量替换。 -
environment
: 定义环境变量。 -
pre_tasks
: 在任何任务之前运行的任务。 -
post_tasks
: 在所有任务之后运行的任务。 -
gather_facts
: 可选的元素,用于在执行任务之前收集有关远程主机的信息。
通过定义这些元素,您可以编写具有复杂逻辑的 Playbook,可以在多个主机之间执行各种操作,并使用变量和模板来灵活配置和管理您的环境。
使用
1、在所有机器的/tmp下面创建shengxia.txt
[root@ansible-server playbook]# vim touch_file.yaml
[root@ansible-server playbook]# cat touch_file.yaml
- hosts: all
vars:
filename: shengxia.txt
tasks:
- name: touch file
file: path=/tmp/{{filename}} state=touch
[root@ansible-server playbook]# ansible-playbook touch_file.yaml
PLAY [all] ******************************************************************************
TASK [Gathering Facts] ******************************************************************ok: [192.168.40.150]
ok: [192.168.40.138]
TASK [touch file] ***********************************************************************changed: [192.168.40.150]
changed: [192.168.40.138]
PLAY RECAP ******************************************************************************192.168.40.138 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
192.168.40.150 : ok=2 changed=1 unreachable=0 failed=0 skipped=0
2、添加定时同步时间的定时任务
[root@ansible-server playbook]# vim cron_time.yaml
[root@ansible-server playbook]# cat cron_time.yaml
- hosts: all
tasks:
- name: add cron sync time
cron:
name: "sync time"
minute: "*/2"
job: "/sbin/ntpdate ntp1.aliyun.com &>/dev/null"
state: present
[root@ansible-server playbook]# ansible-playbook cron_time.yaml
PLAY [all] ******************************************************************************
TASK [Gathering Facts] ******************************************************************ok: [192.168.40.150]
ok: [192.168.40.138]
TASK [add cron sync time] ***************************************************************changed: [192.168.40.150]
changed: [192.168.40.138]
PLAY RECAP ******************************************************************************192.168.40.138 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
192.168.40.150 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
查看
[root@ansible-server playbook]# ansible all -a "crontab -l"
192.168.40.150 | CHANGED | rc=0 >>
#Ansible: sync time
*/2 * * * * /sbin/ntpdate ntp1.aliyun.com &>/dev/null
192.168.40.138 | CHANGED | rc=0 >>
#Ansible: sync time
*/2 * * * * /sbin/ntpdate ntp1.aliyun.com &>/dev/null
3、安装redis服务
[root@ansible-server playbook]# vim redis_first.yaml
[root@ansible-server playbook]# cat redis_first.yaml
- hosts: all
remote_user: root
tasks:
- name: install redis
yum: name=redis state=latest
- name: start redis
service: name=redis state=started
验证是否语法正确
[root@ansible-server playbook]# ansible-playbook --syntax-check redis_first.yaml
playbook: redis_first.yaml
执行
[root@ansible-server playbook]# ansible-playbook redis_first.yaml
PLAY [all] *********************************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.40.150]
TASK [install redis] ***********************************************************
changed: [192.168.40.150]
TASK [start redis] *************************************************************
changed: [192.168.40.150]
PLAY RECAP *********************************************************************
192.168.40.150 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
在客户端查看,安装成功
[root@ansible-client ~]# ps aux | grep redis
redis 4783 0.6 0.3 143056 5776 ? Ssl 22:59 0:00 /usr/bin/redis-server 127.0.0.1:6379
root 4808 0.0 0.0 112824 980 pts/0 S+ 23:02 0:00 grep --color=auto redis
4、带配置文件的安装redis服务
## 把配置文件fetch过来
[root@ansible-server playbook]# ansible all -m fetch -a "src=/etc/redis.conf dest=/lianxi/ansible/playbook"
192.168.40.150 | CHANGED => {
"changed": true,
"checksum": "07eedef3014b6ed6d95b95b38577dff5ac3ecf12",
"dest": "/lianxi/ansible/playbook/192.168.40.150/etc/redis.conf",
"md5sum": "d98629fded012cd2a25b9db0599a9251",
"remote_checksum": "07eedef3014b6ed6d95b95b38577dff5ac3ecf12",
"remote_md5sum": null
}
[root@ansible-server playbook]# ls
192.168.40.150 redis_first.yaml
[root@ansible-server playbook]# cp 192.168.40.150/etc/redis.conf .
[root@ansible-server playbook]# ls
192.168.40.150 redis.conf redis_first.yaml
## 修改bind为0.0.0.0
[root@ansible-server playbook]# vim redis.conf
修改后的yaml文件
[root@ansible-server playbook]# cat redis_second.yaml
- hosts: all
remote_user: root
tasks:
- name: copy config file # 复制配置文件到远程目标主机
copy: src=/lianxi/ansible/playbook/redis.conf dest=/etc/redis.conf owner=redis notify: restart redis # 触发的动作
tags: configfile # 任务标记名
handlers: # 接收到其它任务的通知时触发
- name: restart redis
service: name=redis state=restarted
执行
[root@ansible-server playbook]# ansible-playbook redis_second.yaml
PLAY [all] ***********************************************************************
TASK [Gathering Facts] ***********************************************************ok: [192.168.40.150]
TASK [copy config file] **********************************************************changed: [192.168.40.150]
RUNNING HANDLER [restart redis] **************************************************changed: [192.168.40.150]
PLAY RECAP ***********************************************************************192.168.40.150 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
查看端口是否为0.0.0.0
[root@ansible-client ~]# netstat -aplut | grep redis
tcp 0 0 0.0.0.0:6379 0.0.0.0:* LISTEN 5339/redis-server 0
变量
变量 | |
命令行 | 临时使用,较少用 |
变量文件vars_files | 某一个主机使用,较少用 |
主机组共用的变量文件group_files | 应用范围广泛 |
ansible内置变量(facts变量) | 搜集主机的基本信息,IP地址,主机名,系统及版本 |
register变量 | 实现命令行$()或``功能 |
1、vars,vars_files变量
[root@ansible-server playbook]# vim vars_dir.yaml
[root@ansible-server playbook]# cat vars_dir.yaml
- hosts: all
vars:
dir_name: /lianxi/var_test
file_name: var_test.txt
tasks:
- name: mkdir dir
file:
path: "{{ dir_name }}"
state: directory
- name: touch file
file:
path: "{{ dir_name }}/{{ file_name }}"
state: touch
[root@ansible-server playbook]# ansible-playbook vars_dir.yaml
当剧本比较大的时候,可以将变量存放到一个文件中
[root@ansible-server vars]# ls
var_files_dir.yaml vars.yaml
[root@ansible-server vars]# cat vars.yaml
dir_name: /lianxi/vars_file_test
file_name: shengxia_vars_test.txt
[root@ansible-server vars]# cat var_files_dir.yaml
- hosts: all
remote_user: root
vars_files: ./vars.yaml
tasks:
- name: mkdir vars_test
file:
path: "{{dir_name}}"
state: directory
- name: touch shengxia_vars_test txt
file:
path: "{{dir_name}}/{{file_name}}"
state: touch
[root@ansible-server playbook]# ansible-playbook var_files_dir.yaml
2、ansible-facts变量
查看ansible facts 变量内容
常⽤fact变量
ansible_hostname #主机名
ansible_memtotal_mb #内存⼤⼩(总计) 单位mb
ansible_processor_vcpus #cpu数量
ansible_default_ipv4.address#默认的⽹卡
ansible_distribution #系统发⾏版本名字
ansible_processor_cores #核⼼总数
ansible_date_time.date #当前时间 年-⽉-⽇
系统巡检,获取所有机器的基础信息保存到/tmp/主机名命名文件中
[root@ansible-server facts]# cat vars_sys_info.yaml
- hosts: all
remote_user: root
tasks:
- name: 创建文件并写入系统基本信息
lineinfile: # 在文件中查找指定的行
path: /tmp/{{ansible_hostname}}
create: yes
line: "主机名:{{ansible_hostname}}\n
ip地址:{{ansible_default_ipv4.address}}\n
内存总计:{{ansible_memtotal_mb}}"
[root@ansible-server facts]# ansible-playbook vars_sys_info.yaml
[root@ansible-server facts]# ansible all -a "cat /tmp/ansible-client"
192.168.40.150 | CHANGED | rc=0 >>
主机名:ansible-client
ip地址:192.168.40.150
内存总计:1819
192.168.40.138 | CHANGED | rc=0 >>
主机名:ansible-client
ip地址:192.168.40.138
内存总计:1819
3、ansible-register变量
创建以主机名命名的文件/lianxi/主机名
[root@ansible-server facts]# cat vars_register.yaml
- hosts: all
remote_user: root
tasks:
- name: 获取主机名
shell: hostname
register: hostname #取出命令的结果
- name: 输出变量内容
debug:
msg: "{{ hostname }}"
- name: 创建文件
file:
path: /lianxi/{{hostname.stdout}} ## 取出命令的输出结果
state: touch
[root@ansible-server facts]# ansible-playbook vars_register.yaml
PLAY [all] ******************************************************************************
TASK [Gathering Facts] ******************************************************************ok: [192.168.40.150]
ok: [192.168.40.138]
TASK [获取主机名] ****************************************************************************
changed: [192.168.40.150]
changed: [192.168.40.138]
TASK [输出变量内容] ***************************************************************************
ok: [192.168.40.150] => {
"msg": {
"changed": true,
"cmd": "hostname",
"delta": "0:00:00.004792",
"end": "2023-08-10 16:37:29.304199",
"failed": false,
"rc": 0,
"start": "2023-08-10 16:37:29.299407",
"stderr": "",
"stderr_lines": [],
"stdout": "ansible-client",
"stdout_lines": [
"ansible-client"
]
}
}
ok: [192.168.40.138] => {
"msg": {
"changed": true,
"cmd": "hostname",
"delta": "0:00:00.016540",
"end": "2023-08-10 16:37:29.356411",
"failed": false,
"rc": 0,
"start": "2023-08-10 16:37:29.339871",
"stderr": "",
"stderr_lines": [],
"stdout": "ansible-client",
"stdout_lines": [
"ansible-client"
]
}
}
TASK [创建文件] *****************************************************************************
changed: [192.168.40.150]
changed: [192.168.40.138]
PLAY RECAP ******************************************************************************192.168.40.138 : ok=4 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
192.168.40.150 : ok=4 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
tags标签
⼀般⽤于调试剧本,给剧本个每个task可以设置标签,运⾏剧本的时候可以运⾏指定标签,运⾏剧本的时候排除某些标签
。
[root@ansible-server playbook]# vim tags_nginx.yaml
[root@ansible-server playbook]# cat tags_nginx.yaml
- hosts: all
tasks:
- name: 安装nginx
yum:
name: nginx
state: present
tags:
- install_nginx
- name: 启动nginx
service:
name: nginx
state: started
tags:
- start_nginx
运行指定的标签
[root@ansible-server playbook]# ansible-playbook --tags install_nginx tags_nginx.yaml
排除指定的标签
[root@ansible-server playbook]# ansible-playbook --skip-tags start_nginx tags_nginx.yaml
handlers和template
处理程序(handlers)是在任务发生变化时触发的操作,处理程序通常用于在配置更改后执行服务重启或其他操作
。
模块(template)用于根据模板文件生成目标文件。它通常与Jinjia2模板引擎一起使用,可以处理变量、条件语句和循环等逻辑,生成动态的配置文件或其他文本文件
。
创建一个nginx.conf.j2文件
[root@ansible-server handler_template]# vim nginx.conf.j2
[root@ansible-server handler_template]# cat nginx.conf.j2
worker_processes {{ ansible_processor_count }}; # 这个变量,它会被 Ansible 解析并替换为实际主机的处理器数量
user nginx;
events {
worker_connections 1024;
}
http {
server {
listen 8099; # 修改端口,查看效果
server_name localhost;
location / {
root /usr/share/nginx/html/;
index index.html;
}
}
}
[root@ansible-server handler_template]# cat handlers_j2_nginx.yaml
- hosts: all
tasks:
- name: 安装nginx
yum:
name: nginx
state: present
tags:
- install_nginx
- name: 启动nginx
service:
name: nginx
state: started
tags:
- start_nginx
- name: 修改配置文件
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: restart nginx #通知处理程序处理重新启动nginx
handlers:
- name: restart nginx #名字要和notify的对上
service:
name: nginx
state: restarted
[root@ansible-server handler_template]# ansible-playbook handlers_j2_nginx.yaml
PLAY [all] *************************************************************************************************************************************
TASK [Gathering Facts] *************************************************************************************************************************ok: [192.168.40.150]
ok: [192.168.40.138]
TASK [安装nginx] *********************************************************************************************************************************
ok: [192.168.40.150]
ok: [192.168.40.138]
TASK [启动nginx] *********************************************************************************************************************************
ok: [192.168.40.150]
changed: [192.168.40.138]
TASK [修改配置文件] **********************************************************************************************************************************
ok: [192.168.40.150]
changed: [192.168.40.138]
RUNNING HANDLER [restart nginx] ****************************************************************************************************************changed: [192.168.40.138]
PLAY RECAP *************************************************************************************************************************************192.168.40.138 : ok=5 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
192.168.40.150 : ok=4 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0