[root@localhost ~]# ssh [email protected]
The authenticity of host '192.168.2.2 (192.168.2.2)' can't be established.
ECDSA key fingerprint is 4e:76:0e:e5:44:a9:4c:75:ea:67:a6:66:5a:23:6c:67.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.2.2' (ECDSA) to the list of known hosts.
[email protected]'s password:
#生成密钥对(私钥和公钥)
[root@localhost ~]# ssh-keygen -t rsa -b 4096
-t;指定加密算法
-b:指定密钥长度
[root@localhost ~]# ll -A /root/.ssh/
总用量 8
-rw------- 1 root root 3243 2月 20 15:41 id_rsa
-rw-r--r-- 1 root root 752 2月 20 15:41 id_rsa.pub
#上传公钥
[root@localhost ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
[root@localhost ~]# vi /server/scripts/fenfa.sh
#!/bin/bash
#你要分发的IP主机
ip_list="192.168.2.2 192.168.2.3 192.168.2.4"
#创建key
ssh-keygen -t rsa -b 4096
#分发密钥
for ip in $ip_list
do
ssh-copy-id -i /root/.ssh/id_rsa.pub root@$ip
done
[root@localhost ~]# bash /server/scripts/fenfa.sh
ssh分发密钥
#epel源安装ansible
wget -O /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-7.repo
[root@localhost ~]# yum -y install ansible
[root@localhost ~]# 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, Nov 6 2016, 00:28:07) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)]
[root@localhost ~]# vi /etc/ansible/hosts
[test]
192.168.2.2
192.168.2.3
[root@localhost ~]# ansible test -m ping
192.168.2.2 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.2.3 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
绿色表示正常
黄色表示执行正常,并作出了改变
红色表示错误,输出错误信息
紫色表示警告,建议
ansible [主机分组] -m(module) [指定模块] -a(action) [指定模块中的选项]
例:
[root@localhost ~]# ansible test -m command -a 'hostname'
192.168.2.3 | CHANGED | rc=0 >>
localhost.localdomain
192.168.2.2 | CHANGED | rc=0 >>
localhost.localdomain
[root@localhost ~]# vi /etc/ansible/ansible.cfg
host_key_checking = False #关闭ansible的认证
[root@localhost ~]# cat /etc/ansible/hosts #默认的主机清单
[test] #组名
192.168.2.2 #主机地址
192.168.2.3
或者192.168.2.[1:10]
1.本地生成密钥(SSH密钥对)
2.主机清单指定
192.168.2.2 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='1'
3.多主机指定相同密码(指定主机组)
[all:vars]
ansible_ssh_port=22
ansible_ssh_user=root
ansible_ssh_pass='1'
子组创建
[web]
192.168.2.2
[data]
192.168.2.3
多组合并
[test:children]
web
data
[root@localhost ~]# ansible test -m command -a 'hostname'
192.168.2.3 | CHANGED | rc=0 >>
data_01
192.168.2.2 | CHANGED | rc=0 >>
web_01
命令和脚本 |
描述 |
command |
默认的模块,执行简单的命令,不支持特殊的字符 |
shell |
执行命令 ,支持特殊的字符 |
script |
分发脚本执行 |
文件 |
描述 |
file |
创建目录,文件,软链接 |
copy |
远程分发文件,修改权限,所有者,备份 |
服务管理 |
描述 |
systemd |
服务管理,开启关闭,状态查询 |
service |
服务管理(了解) |
软件包下载 |
描述 |
yum |
安装软件包,卸载软件包 |
get_url |
下载软件包(wget命令) |
系统管理模块 |
描述 |
mount |
挂载磁盘,镜像文件 |
cron |
定时任务 |
调试模块 |
描述 |
ping |
检查主机是否存活 |
debug |
用于检测显示 变量 函数 |
用户管理 |
描述 |
user |
管理用户 创建用户 权限管理 |
group |
管理组 创建组 |
其他模块 |
描述 |
docker |
容器 |
zabbix |
监控 |
mysql |
数据库 |
rsync |
远程同步 |
[root@localhost ~]# ansible all -a 'hostname' #默认加command
192.168.2.3 | CHANGED | rc=0 >>
data_01
192.168.2.2 | CHANGED | rc=0 >>
web_01
[root@localhost ~]# ansible all -m shell -a 'ip a s ens33 | sed -n 3p' #shell支持特殊字符 如果使用command会报错
192.168.2.3 | CHANGED | rc=0 >>
inet 192.168.2.3/24 brd 192.168.2.255 scope global ens33
192.168.2.2 | CHANGED | rc=0 >>
inet 192.168.2.2/24 brd 192.168.2.255 scope global ens33
[root@localhost ~]# vi /server/scripts/install-sl.sh
#!/bin/bash
yum -y install sl
[root@localhost ~]# ansible all -m script -a '/server/scripts/install-sl.sh'
测试:
[root@web_01 ~]# sl
file模块中的选项 |
描述 |
path |
路径(目录,文件) |
src |
源文件(一般用于link创建软连接模式用于指定源文件) |
state |
状态(模式)state=directory(创建目录) state=file(默认,更新文件,如果文件不存在也不创建)state=link(创建软链接) state=touch(创建文件) state=absent(删除) |
owner |
指定所有者(属主) |
group |
指定所有组(属组) |
mode |
设置权限 |
[root@localhost ~]# ansible all -m file -a "path=/test state=directory"
[root@localhost ~]# ansible all -a "ls -ld /test"
192.168.2.3 | CHANGED | rc=0 >>
drwxr-xr-x 2 root root 6 2月 20 20:10 /test
192.168.2.2 | CHANGED | rc=0 >>
drwxr-xr-x 2 root root 6 2月 20 20:10 /test
[root@localhost ~]# ansible all -m file -a 'path=/test/file1.txt state=touch'
[root@localhost ~]# ansible all -a "ls -l /test"
192.168.2.3 | CHANGED | rc=0 >>
总用量 0
-rw-r--r-- 1 root root 0 2月 20 20:13 file1.txt
192.168.2.2 | CHANGED | rc=0 >>
总用量 0
-rw-r--r-- 1 root root 0 2月 20 20:13 file1.txt
[root@localhost ~]# ansible all -m file -a 'src=/test/file1.txt path=/tmp/file.txt state=link'
[root@localhost ~]# ansible all -a "ls -l /tmp/file.txt"
192.168.2.3 | CHANGED | rc=0 >>
lrwxrwxrwx 1 root root 15 2月 20 20:15 /tmp/file.txt -> /test/file1.txt
192.168.2.2 | CHANGED | rc=0 >>
lrwxrwxrwx 1 root root 15 2月 20 20:15 /tmp/file.txt -> /test/file1.txt
[root@localhost ~]# ansible all -m file -a 'path=/test/file1.txt state=absent'
[root@localhost ~]# ansible all -m file -a 'path=/test state=absent'
[root@localhost ~]# ansible all -m file -a 'path=/tmp/file.txt state=absent'
[root@localhost ~]# ansible all -m file -a 'path=/tmp/test.txt owner=root group=root mode=755 state=touch'
[root@localhost ~]# ansible all -a 'ls -l /tmp/test.txt'
192.168.2.3 | CHANGED | rc=0 >>
-rwxr-xr-x 1 root root 0 2月 20 20:23 /tmp/test.txt
192.168.2.2 | CHANGED | rc=0 >>
-rwxr-xr-x 1 root root 0 2月 20 20:23 /tmp/test.txt
选项 |
描述 |
src |
source源文件 |
dest |
destination目标位置 |
backup |
backup=yes 则会在覆盖前进行备份 |
mode |
修改权限 |
owner |
修改为指定所有者 |
group |
指定所有组 |
[root@localhost ~]# ansible all -m copy -a "src=/etc/hosts dest=/etc/hosts"
[root@localhost ~]# ansible all -a 'cat /etc/hosts'
192.168.2.2 | CHANGED | rc=0 >>
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.2.1 server
192.168.2.2 web1
192.168.2.3 data1
192.168.2.3 | CHANGED | rc=0 >>
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.2.1 server
192.168.2.2 web1
192.168.2.3 data1
[root@localhost ~]# ansible all -m copy -a 'src=/etc/hosts dest=/etc/hosts backup=yes'
[root@localhost ~]# ansible all -m shell -a 'ls -l /etc/hosts*'
192.168.2.3 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 229 2月 20 20:37 /etc/hosts
-rw-r--r-- 1 root root 212 2月 20 20:29 /etc/hosts.21223.2023-02-20@20:37:39~
-rw-r--r--. 1 root root 370 6月 7 2013 /etc/hosts.allow
-rw-r--r--. 1 root root 460 6月 7 2013 /etc/hosts.deny
192.168.2.2 | CHANGED | rc=0 >>
选项 |
描述 |
name |
用于指定服务器的 |
enabled |
控制主机的开机自启动 enabled=yes enable=no |
daemon-reload |
yes是否重新加载对应的服务的管理配置文件 |
state |
表示指定操作服务器的状态的 state=started(开启) state=stopped(关闭) state=reloaded(重读配置文件的) state=restarted(重启) |
[root@localhost ~]# ansible all -m systemd -a 'name=firewalld enabled=no state=stopped'
[root@localhost ~]# ansible all -a "systemctl status firewalld"
192.168.2.3 | FAILED | rc=3 >>
● firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
Active: inactive (dead)
Docs: man:firewalld(1)non-zero return code
192.168.2.2 | FAILED | rc=3 >>
● firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
Active: inactive (dead)
Docs: man:firewalld(1)non-zero return code
[root@localhost ~]# ansible all -m systemd -a 'name=sshd enabled=yes state=started'
[root@localhost ~]# ansible all -a "systemctl status sshd"
[root@localhost ~]# ansible data -m systemd -a 'name=mysqld state=restarted'
选项 |
描述 |
开机自启 |
enabled |
服务器名称 |
name |
服务开关重启 |
state |
运行级别 |
runlevel |
yum_repository源选项 |
yum源配置文件内容 |
作用 |
name |
[epel] |
yum源中名字(中括号 里面的名字即可) |
description |
name=xxxxx |
yum源的注释说明 |
baseurl |
baseurl= |
yum源中下载软件包的地址(可以直接访问到repodata目录) |
enable=yes/no |
enable=1/0 |
是否启动这个源 |
gpgcheck=yes/no |
gpgcheck=0 |
是否启动gpgcheck功能 |
file(可以不加) |
无 |
指定yum源文件,自动添加.repo |
[root@localhost ~]# ansible all -m yum_repository -a 'name=nginx description="nginx" baseurl="http://nginx.org/packages/centos/$releasever/$basearch/" gpgcheck=no enabled=yes'
192.168.2.2 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"repo": "nginx",
"state": "present"
}
192.168.2.3 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"repo": "nginx",
"state": "present"
}
选项 |
描述 |
name |
指定软件包名字 |
state |
installed安装 removed(删除) latest(如果安装就检查更新 没安装则安装) |
[root@localhost ~]# ansible all -a 'rpm -e lrzsz'
[root@localhost ~]# ansible all -m yum -a 'name=lrzsz state=installed'
[root@localhost ~]# ansible web -m yum -a 'name=sl,cowsay,aalib state=installed'
选项 |
描述 |
url |
指定要下载的地址 |
dest |
下载到那个目录 |
[root@localhost ~]# ansible web -m file -a 'path=/server/tools/ state=directory'
[root@localhost ~]# ansible web -m get_url -a "url=https://tengine.taobao.org/download/tengine-2.3.3.tar.gz dest=/server/tools/"
[root@localhost ~]# ansible web -a 'ls /server/tools'
192.168.2.2 | CHANGED | rc=0 >>
tengine-2.3.3.tar.gz
选项 |
描述 |
fstype |
指定文件类型 |
src |
源地址 |
path |
挂载点 |
state |
state=absent(卸载并修改fstab(清理配置)) state=unmounted(卸载不修改/etc/fstab) state=present(仅修改/etc/fstab不挂载) state=remounted(重新挂载) |
[root@localhost ~]# ansible web -m file -a 'path=/nfs-data state=directory'
[root@localhost ~]# ansible web -m mount -a 'fstype=nfs src="192.168.2.3:/data" path=/nfs-data state=mounted'
cron的选项 |
定时任务配置中的内容 |
描述 |
name |
#及后面的内容 |
定时任务名字 |
minute |
*/2 |
分钟minute=“*/2”,如果没有用到不用填写即可 |
hour |
小时 |
|
day |
日 |
|
month |
月份 |
|
week |
周 |
|
job |
命令(脚本) |
指定命令或脚本 |
state |
present默认是添加 添加定时任务 absent删除 |
* / 2 * * * * / sbin / ntpdat e ntp
[root@localhost ~]# ansible all -m cron -a 'name="sync time by" minute="*/2" job="/sbin/ntpdate ntp1.aliyun.com &> /dev/null state=present"'
选项 |
描述 |
name |
用户名 |
uid |
指定uid |
group |
知道用户组 |
shell |
指定命令解释器 |
create_home |
是否创建家目录 |
state |
state=present(添加) state=absent(删除) |
[root@localhost ~]# ansible web -m user -a 'name=www'
[root@localhost ~]# ansible web -m user -a 'name=cjx uid=10085 shell=/shell/nologin create_home=no state=present'
选项 |
描述 |
name |
指定用户组名字 |
gid |
指定组的gid |
state |
state=present(添加)state=adsent(删除) |
服务部署:yum安装(更新)rsync
配置文件
创建虚拟用户rsync
创建密码和分配权限
同步对应目录,改所有者
重启服务
yum -y install rsync
配置好rsync文件然后scp上传替换
创建虚拟用户:useradd -s /sbin/nologin -M rsync
密码文件和权限:echo 'rsync_back:1' > /etc/rsync.password 修改权限:chmod 600 /etc/rsync.password
创建共享目录:mkdir /data 分配所有者 chown rsync.rsync /data
重启服务:systemctl restart rsync
[root@localhost ~]# mkdir /data/
[root@localhost ~]# vi /data/rsyncd.conf
uid = root
gid = root
port 873
address = 192.168.2.2
hosts allow = 192.168.2.0/24
max connections = 4
pid file = /var/run/rsyncd.pid
timeout = 900
dont compress = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2
[data]
path = /data
read only = no
auth users = test
secrets file = /etc/rsync.password
[root@localhost ~]# ansible rsync -m yum -a 'name=rsync state=installed'
[root@localhost ~]# ansible rsync -m copy -a 'src=/data/rsyncd.conf dest=/etc/rsyncd.conf backup=yes'
[root@localhost ~]# ansible rsync -m user -a 'name=rsync shell=/sbin/nologin create_home=no state=present
[root@localhost ~]# ansible rsync -m file -a 'path=/etc/rsync.password mode=600 state=touch'
[root@localhost ~]# ansible rsync -m shell -a "echo 'test:1' > /etc/rsync.password"
[root@localhost ~]# ansible rsync -m file -a 'path=/data owner=rsync group=rsync state=directory'
[root@localhost ~]# ansible rsync -m systemd -a 'name=rsyncd enabled=yes state=started'
[root@localhost ~]# rsync -avz --password-file=/etc/server.pass /test/ [email protected]::data
sending incremental file list
./
sent 47 bytes received 23 bytes 140.00 bytes/sec
total size is 0 speedup is 0.00
命令 |
含义 |
应用场景 |
ad-hoc |
ans命令运行对应模块与选项 |
临时使用,测试使用 |
playbook |
通过文件执行(类似脚本) |
用于批量管理,部署,收集信息,分发(文件重复执行) |
剧本与脚本 |
应用场景 |
playbook剧本 |
批量管理,批量部署,批量分发 |
shell脚本 |
某一台,服务脚本,系统巡查,定时备份 |
剧本格式叫yaml格式(yml)
缩进(不要使用Tab,使用空格)
核心格式剧本中所有的内容要对齐
对齐的时候不能使用Tab
在不同层级中需要使用两个空格来分层
hosts:用于指定那些主机
tasks:用于对这些主机,运行什么模块
参数:
参数 |
描述 |
-i |
指定hosts文件(默认/etc/ansible/hosts) |
-C |
检测yml文件是否有误 |
--list-hosts |
列出清单 |
--list-tasks |
列出任务 |
--list-tags |
列出标签 |
--syntax-check |
语法检查 |
[root@localhost playbook]# vi touch.yml
- hosts: all
vars:
filename: test1.txt
tasks:
- name: touch file
shell: touch /tmp/{{filename}}
[root@localhost playbook]# vi cron.yml
- hosts: all
tasks:
- name: add cron sync time
cron:
name: "sync time by"
minute: "*/2"
job: "/sbin/ntpdate ntp1.aliyun.com &> /dev/null"
state: present
[root@localhost playbook]# ansible-playbook -C cron.yml
[root@localhost playbook]# vi zabbix_agent.yml
- hosts: all
tasks:
- name: download zabbix agent2
get_url:
url: https://mirrors.tuna.tsinghua.edu.cn/zabbix/zabbix/6.0/rhel/7/x86_64/zabbix-agent2-6.0.0-1.el7.x86_64.rpm
dest: /tmp/
validate_certs: no
- name: install zabbix agent2
yum:
name: /tmp/zabbix-agent2-6.0.0-1.el7.x86_64.rpm
state: installed
- name: start zabbix agent2
systemd:
name: zabbix-agent2
enabled: yes
state: started
[root@localhost playbook]# ansible-playbook -C zabbix_agent.yml
案例4:配置rsync服务器端
[root@localhost playbook]# vi rsync_backup.yml
- hosts: rsync
tasks:
- name: install rsync
yum:
name: rsync
state: latest
- name: config
copy:
src: /data/rsyncd.conf
dest: /etc/rsyncd.conf
backup: yes
- name: virtual user
user:
name: rsync
shell: /sbin/nologin
create_home: no
state: present
- name: password txt
shell:
'echo "rsync_backup:1" > /etc/rsync.password'
- name: password
file:
path: /etc/rsync.password
owner: rsync
group: rsync
state: file
- name: reload rsync
systemd:
name: rsyncd
enabled: yes
state: started
[root@localhost playbook]# ansible-playbook -C rsync_backup.yml
yum -y install ansible
ssh-keygen -t rsa
ssh-copy-id root@IP
[root@localhost ~]# mkdir -p /etc/ansible/ansible_playbook/{conf,file,scripts,tools}
[root@localhost ~]# vi /etc/ansible/hosts
[rsync]
192.168.2.2
[data]
192.168.2.3
[web]
192.168.2.4
#NFS共享
[root@localhost conf]# vi /etc/ansible/ansible_playbook/conf/exports
/data 192.168.2.0/24(rw,sync,all_squash)
#httpd文件
cp /etc/httpd/httpd.conf /etc/ansible/ansible_playbook/conf/
#rsync配置文件
[root@localhost conf]# vi /etc/ansible/ansible_playbook/conf/rsyncd.conf
uid = www
gid = www
port 873
address = 192.168.2.2
hosts allow = 192.168.2.0/24
max connections = 4
pid file = /var/run/rsyncd.pid
timeout = 900
dont compress = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2
[backup]
path = /backup
read only = no
auth users = rsync_backup
secrets file = /etc/rsync.password
#设置rsync执行文件权限
[root@localhost conf]# vi /etc/ansible/ansible_playbook/scripts/rsync_backup.sh
#!/usr/bin/bash
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
#1.定义变量
Host=$(hostname)
Addr=$(ifconfig ens33|awk 'NR==2{print $2}')
Date=$(date +%F)
Dest=${Host}_${Addr}_${Date}
Path=/backup
#2.创建备份目录
[ -d $Path/$Dest ] || mkdir -p $Path/$Dest
#3.备份对应的文件
cd / && \
[ -f $Path/$Dest/system.tar.gz ] || tar czf $Path/$Dest/system.tar.gz etc/fstab etc/rsyncd.conf && \
[ -f $Path/$Dest/log.tar.gz ] || tar czf $Path/$Dest/log.tar.gz var/log/messages var/log/secure && \
#4.携带md5验证信息
[ -f $Path/$Dest/flag ] || md5sum $Path/$Dest/*.tar.gz >$Path/$Dest/flag_${Date}
#4.推送本地数据至备份服务器
export RSYNC_PASSWORD=1
rsync -avz $Path/ rsync_backup@rsync1::backup
#5.本地保留最近7天的数据
find $Path/ -type d -mtime +7|xargs rm -rf
#检查rsync状态
[root@localhost conf]# vi /etc/ansible/ansible_playbook/scripts/rsync_check.sh
#!/usr/bin/bash
#1.定义全局的变量
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
#2.定义局部变量
Path=/backup
Date=$(date +%F)
#3.查看flag文件,将校验的结果保存至result_时间
find $Path/*_${Date} -type f -name "flag$Date" >$Path/result_${Date}
#4.将校验的结果发送邮件给管理员
mail -s "Rsync Backup $Date" [email protected] <$Path/result_${Date}
#5.删除超过7天的校验结果文件, 删除超过180天的备份数据文件
find $Path/ -type f -name "result*" -mtime +7|xargs rm -f
find $Path/ -type d -mtime +180|xargs rm -rf
(1)在ansible服务器先下载sersync
(2)解压到/etc/ansible/ansible_playbook/并修改配置文件
(3)推送到nfs
(4)启动sersync
(1)网络环境(关闭firewall selinux)
(2)epel仓库
(3)安装rsync,nfs-utils
(4)创建组
(5)创建用户
(6)创建目录,并修改权限
(7)推送脚本
(8)推送rsync客户端密码文件,修改权限
(9)计划任务
[root@localhost ~]# cd /etc/ansible/ansible_playbook/
[root@localhost ansible_playbook]# vi base.yaml
- hosts: all
tasks:
- name: clear repos.d
file: path=/etc/yum.repos.d/ state=absent
- name: create repos.d
file: path=/etc/yum.repos.d/ state=directory
- name: install base repo
get_url: url=http://mirrors.aliyun.com/repo/Centos-7.repo
dest: /etc/yum.repos.d/CentOS-Base.repo
- name: install epel repo
get_url: url=http://mirrors.aliyun.com/repo/epel-7.repo
dest: /etc/yum.repos.d/epel.repo
- name: install rsync nfs-utils
yum: name=rsync,nfs-utils state=installed
crea
- name: create group www
group: name=www gid=666
- name: create user www
user: name=www uid=666 create_home=no shell=/sbin/nologin
- name: create rsync client password
copy: content='1' dest=/etc/rsync.pass mode=600
- name: create scripts directory
file: path=/server/scripts/ recurse=yes state=directory
- name: push scripts
copy: src=./scripts/rsync_backup.sh dest=/server/scripts
- name: crontab
cron: name="backup scripts" hour=01 minute=00 job="/usr/bin/bash /server/scripts/rsync_backup.sh &> /dev/null"
[root@localhost ansible_playbook]# vi rsync.yaml
- hosts: rsync
tasks:
- name: install rsync
yum: name=rsync state=installed
- name: config rsync
copy: src=/etc/ansible/ansible_playbook/conf/rsyncd.conf dest=/etc/rsyncd.conf
notify: restart rsync
- name: create rsync local user
copy: content='rsync_backup:1' dest=/etc/rsync.password mode=600
- name: create data
file: path=/data state=directory recurse=yes owner=www group=www mode=755
- name: create backup
file: path=/backup state=directory recurse=yes owner=www group=www mode=755
- name: start rsync
service: name=rsyncd state=started enabled=yes
- name: push check scripts
copy: src=./scripts/rsync_check.sh dest=/server/scripts
- name: crond check scripts
cron: name="check scripts" hour=05 minute=00 job="/usr/bin/bash /server/scripts/rsync_check.sh &> /dev/null"
handlers:
- name: restart rsync
service: name=rsyncd state=restarted
vim /etc/ansible/ansible_playbook/nfs.yaml
- hosts: nfs
tasks:
- name: install nfs
yum: name=nfs-utils state=installed
- name: config nfs
copy: src=./conf/exports dest=/etc/exports
notify: restart nfs
- name: create data
file: path=/data state=directory recurse=yes owner=www group=www mode=755
- name: start nfs
service: name=nfs-server state=started enabled=yes
handlers:
- name: restart nfs
service: name=nfs-server state=restarted
vim /etc/ansible/ansible_playbook/sersync.yaml
- hosts: nfs
tasks:
- name: scp sersync
copy: src=./tools/sersync/ dest=/usr/local/sersync owner=www group=www mode=755
- name: start sersync
shell: pgrep sersync;
[ $? -eq 0 ] || /usr/local/sersync/sersync2 -dro /usr/local/sersync/confxml.xml
vim /etc/ansible/ansible_playbook/web.yaml
- hosts: web
tasks:
- name: mount nfs
mount: src=nfs:/data path=/data fstype=nfs state=mounted
- name: install httpd
yum: name=httpd state=installed
- name: config httpd
copy: src=./conf/httpd.conf dest=/etc/httpd/conf/httpd.conf
notify: restart httpd
- name: start httpd
service: name=httpd state=started enabled=yes
handlers:
- name: restart httpd
service: name=httpd state=restarted
vim main.yaml
- import_playbook: base.yaml
- import_playbook: rsync.yaml
- import_playbook: nfs.yaml
- import_playbook: sersync.yaml
- import_playbook: web.yaml
预检测:ansible-playbook -C main.yaml
执行: ansible-playbook main.yaml
变量 |
描述 |
命令行vars |
临时使用,较少用 |
变量文件vars_files |
某一个主机使用,较少使用 |
主机组共用的变量文件group_vars |
应用范围广泛 |
ansible内置变量(facts变量) |
收集主机的基本信息,IP地址,主机名,系统及版本 |
register变量 |
实现命令行$()或``功能 |
注意:在调用变量时不可以变量开头,如果需要的话需要添加双引号
[root@localhost playbook]# vi vars_dir.yml
- hosts: test
vars:
dir_name: /test
file_name: file.txt
tasks:
- name: print var
debug:
msg: 变量 {{ dir_name }}
[root@localhost playbook]# ansible-playbook vars_dir.yml
TASK [print var] ***********************************************************************************************************************************
ok: [192.168.2.2] => {
"msg": "变量 /test"
}
把变量存放到一个文件中
[root@localhost playbook]# vi vars.yml
dir: /data_dir
file: file.txt
[root@localhost playbook]# vi vars_dir.yml
- hosts: test
vars_files: ./vars.yml
tasks:
- name: print var
debug:
msg: 目录 {{ dir }}
- name: print file
debug:
msg: 文件 {{ file }}
[root@localhost playbook]# ansible-playbook vars_dir.yml
TASK [print var] ***********************************************************************************************************************************
ok: [192.168.2.2] => {
"msg": "目录 /data_dir"
}
TASK [print file] **********************************************************************************************************************************
ok: [192.168.2.2] => {
"msg": "文件 file.txt"
}
要求:需要创建一个group_vars目录,目录下面创建以主机组命名,存放变量名文件vars.yml
例:
group_vars/目录:
lb/vars.yml #存在lb组的变量
web/vars.yml #存放web组的变量
data/vars.yml #存放data组的变量
all/vars.yml #存放所有主机公用的变量
为test组和所有主机组(all)创建变量
#创建组变量
[root@localhost playbook]# mkdir -p group_vars/test/
[root@localhost playbook]# vi group_vars/test/vars.yml
dir: /test
[root@localhost playbook]# mkdir -p group_vars/all/
[root@localhost playbook]# vi group_vars/all/vars.yml
file: file.txt
#在ansible-playbook文件中直接调用即可
[root@localhost playbook]# vi vars_dir.yml
- hosts: test
tasks:
- name: print var
debug:
msg: 目录 {{ dir }}
- name: print file
debug:
msg: 文件 {{ file }}
#测试
[root@localhost playbook]# ansible-playbook vars_dir.yml
ok: [192.168.2.2] => {
"msg": "目录 /test"
}
TASK [print file] **********************************************************************************************************************************
ok: [192.168.2.2] => {
"msg": "文件 file.txt"
}
[root@localhost ~]# ansible all -m setup
ansible_hostname #主机名
ansible_memtotal_mb #内存⼤⼩(总计) 单位mb
ansible_processor_vcpus # cpu数量
ansible _default_ipv4.address #默认网卡ip etn0
ansible_distribution #系统发行版本名称
ansible_processor_cores #核心总数
ansible_date_time.date #当前时间 年-月-日
[root@localhost playbook]# vi vars_sys_info.yml
- hosts: all
tasks:
- name: create file system
lineinfile:
path: /tmp/{{ ansible_hostname }}
create: yes
line: "主机名:{{ ansible_hostname }}\nip地址:{{ ansible_default_ipv4.address }}"
[root@localhost playbook]# ansible-playbook vars_sys_info.yml
[root@localhost playbook]# ansible all -m shell -a "cat /tmp/rsync_01"
192.168.2.2 | CHANGED | rc=0 >>
主机名:rsync_01
ip地址:192.168.2.2
如果ansible中使用到一些系统的基础信息,就可以直接使用内置变量调用,无需定义,如果没有这种需求或通过别的方式实现这个需求,可以关闭facts功能,让剧本加速,使用:用gather_facts: no
- hosts: all
gather_facts: no
vars:
dir: /test
file: file.txt
tasks:
- name: mkdir
file:
path: "{{ dir }}"
state: directory
ansible-register用于提取linux命令中的命令的输出信息,作为变量使用
[root@localhost playbook]# vi vars_register.yml
- hosts: all
tasks:
- name: date time
shell: date
register: date
- name: export
debug:
msg: "{{date}}"
#获取
[root@localhost playbook]# ansible-playbook vars_register.yml
TASK [export] *****************************************************************************************************
ok: [192.168.2.2] => {
"msg": {
"changed": true,
"cmd": "date",
"delta": "0:00:00.001997",
"end": "2023-02-23 22:24:23.071061",
"failed": false,
"rc": 0,
"start": "2023-02-23 22:24:23.069064",
"stderr": "",
"stderr_lines": [],
"stdout": "2023年 02月 23日 星期四 22:24:23 CST",
"stdout_lines": [
"2023年 02月 23日 星期四 22:24:23 CST"
]
}
}
[root@localhost playbook]# vi vars_register.yml
- hosts: all
tasks:
- name: date time
shell: date
register: date
- name: export
debug:
msg: "{{ date.stdout }} \n {{ date.start }}"
#查看一下
[root@localhost playbook]# ansible-playbook vars_register.yml
ok: [192.168.2.2] => {
"msg": "2023年 02月 23日 星期四 22:26:57 CST \n 2023-02-23 22:26:57.386379"
}
变量 |
含义与特点 |
应用场景 |
命令行 |
临时使用,较少 |
一次性使用 |
剧本文件中vars定义 |
当前这个剧本生效,涉及多个剧本不方便 |
单个剧本使用 |
变量文件vars_files |
所有变量写入到文件中,再通过剧本调用 |
方便多个剧本使用相同变量来使用 |
主机组公用变量文件group_vars |
应用范围广泛,根据主机清单分组创建变量组,存放vars.yml |
根据主机自动读取,适合于小中型项目 |
ansible内置变量 |
大量内置变量,无需定义,使用方便 |
通用 |
register |
实现linux命令信息作为变量 |
当需要提取linux命令信息作为变量时来进行调用 |
debug模块
tags标签
忽略错误
选项 |
描述 |
msg |
相当于echo命令,配合着register一起用 |
[root@localhost playbook]# vi debug-nfs.yml
- hosts: nfs
tasks:
- name: yum install nfs
yum:
name: nfs-utils
state: installed
- name: config nfs
lineinfile:
path: /etc/exports
line: "/data 192.168.2.0/24(rw,sync,no_root_squash)"
state: present
backup: yes
- name: group nfs
group:
name: nfs
state: present
- name: user nfs
user:
name: nfs
shell: /shell/nologin
create_home: no
state: present
- name: mkdir file
file:
path: /data/
owner: nfs
group: nfs
state: directory
register: file_state
- name: echo nfs
debug:
msg: "{{ file_state }}"
- name: system serive
systemd:
name: rpcbind
enabled: yes
state: started
- name: system nfs
systemd:
name: nfs
enabled: yes
state: started
[root@localhost playbook]# ansible-playbook debug-nfs.yml
TASK [echo nfs] ************************************************************************************************************************************
ok: [192.168.2.2] => {
"msg": {
"changed": false,
"diff": {
"after": {
"path": "/data/"
},
"before": {
"path": "/data/"
}
},
"failed": false,
"gid": 10087,
"group": "nfs",
"mode": "01363",
"owner": "nfs",
"path": "/data/",
"size": 24,
"state": "directory",
"uid": 10087
}
}
一般用于调试剧本,给剧本每一个task可以设置标签
运行剧本的时候可以运行指定的标签
运行剧本的时候可以排除某些标签
[root@localhost playbook]# vi tags-nfs-server.yml
- hosts: nfs
tasks:
- name: install nfs
yum:
name: nfs-utils
state: installed
tags:
- install
- name: config nfs
lineinfile:
path: /etc/exports
line: "/data 192.168.2.0/24(rw)"
state: present
backup: yes
tags:
- conf
- conf_file
- name: mkdir dir
file:
path: /data
owner: nfs
group: nfs
state: directory
tags:
- conf
- conf_dir
- name: system rpc
systemd:
name: rpcbind
enabled: yes
state: started
tags:
- start_srv
- name: system nfs
systemd:
name: nfs
enabled: yes
state: started
tags:
- start_srv
选项 |
描述 |
--tags |
只运行指定的tags标签 |
--skip-tags |
反向运行标签,除了指定标签以外的运行 |
[root@localhost playbook]# ansible-playbook --tags install tags-nfs-server.yml
PLAY [nfs] *****************************************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************************
ok: [192.168.2.2]
TASK [install nfs] *********************************************************************************************************************************
ok: [192.168.2.2]
PLAY RECAP *****************************************************************************************************************************************
192.168.2.2 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
[root@localhost playbook]# ansible-playbook --skip-tags install,conf_file tags-nfs-server.yml
PLAY [nfs] *****************************************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************************
ok: [192.168.2.2]
TASK [mkdir dir] ***********************************************************************************************************************************
ok: [192.168.2.2]
TASK [system rpc] **********************************************************************************************************************************
ok: [192.168.2.2]
TASK [system nfs] **********************************************************************************************************************************
ok: [192.168.2.2]
用于运行剧本的时候,强制让某个任务(模块)运行即使出错了,也不要中断我们的剧本
[root@localhost playbook]# vi ignore-nfs.yml
- hosts: nfs
tasks:
- name: install nfs
yum:
name: nfs-utils
state: installed
ignore_errors: yes
tags:
- install
#如果install nfs字段出现问题,则直接跳过
include
handler
when判断
循环
include文件包含,把一个任务分成多个剧本来实现,书写一个总剧本文件,通过include_tasks:引用子剧本文件
注意:子剧本文件中只需要些模块部分(task部分即可)
ansible选项 |
作用 |
-i |
指定主机清单文件 |
ansible-playbook命令 |
作用 |
-i |
指定主机清单文件 |
-C |
模拟运行剧本,查看问题 |
--syntax-check |
仅仅检查剧本格式是否有误 |
--skip-tags |
跳过指定的tags标签 |
--tags(-t) 标签 |
运行指定的标签 |