Day02-Ansible Ad-Hoc

2024-04-04 08:52
文章标签 ad hoc ansible day02

本文主要是介绍Day02-Ansible Ad-Hoc,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Day02-Ansible Ad-Hoc

  • 1. Ansible Ad-Hoc
    • 1.1 什么是ad-hoc
    • 1.2 ad-hoc模式的使用场景
    • 1.3 ad-hoc模式的命令使用
    • 1.4 使用ad-hoc执行一次远程命令,注意观察返回结果的颜色
    • 1.5 ad-hoc模式的常用模块有如下
      • 1.5.1 执行命令模块
      • 1.5.2 软件管理模块
      • 1.5.3 文件管理模块
      • 1.5.4 服务管理模块
      • 1.5.5 用户管理模块
      • 1.5.6 定时任务模块
      • 1.5.7 磁盘挂载模块
      • 1.5.8 防火墙管理模块 主要看iptables

1. Ansible Ad-Hoc

Ansible模块最全的参考
传送门: https://docs.ansible.com/ansible/latest/collections/index.html
精准传送门: https://docs.ansible.com/ansible/latest/collections/ansible/builtin/index.html#plugins-in-ansible-builtin
在这里插入图片描述

命令行查询模块:

ansible-doc -s copy
ansible-doc -l |grep ali
ansible-doc -l |grep copy
ansible-doc -l |grep yum
ansible-doc yum

1.1 什么是ad-hoc

ad-hoc简而言之就是“临时命令”,执行完即结束,并不会保存

1.2 ad-hoc模式的使用场景

临时获取主机的数据、状态。
比如在多台机器上查看某个进程是否启动,或拷贝指定文件到本地,等等

1.3 ad-hoc模式的命令使用

ansible ‘oldboy’ -m command -a ‘df -h’,含义如下图
在这里插入图片描述

1.4 使用ad-hoc执行一次远程命令,注意观察返回结果的颜色

绿色:代表被管理端主机没有被修改(成功)
黄色:代表被管理端主机发现变更(成功)
红色:代表出现了故障,注意查看提示(失败)
紫色/粉色:警告信息,建议

ansible all -m ping

1.5 ad-hoc模式的常用模块有如下

command # 执行shell命令(不支持管道等特殊字符) 管道 * > . ..
shell # 执行shell命令 支持特殊符号
script # 执行shell脚本yum_repository # 配置yum仓库 yum源
yum # 安装软件copy # 变更配置文件 远程复制
file # 建立目录或文件service # 启动与停止服务 设置开机自启动 systemctl
mount # 挂载设备 磁盘 光盘 nfs ....
cron # 定时任务 设置/删除定时任务firewalld # 防火墙
iptables ※ # 防火墙
get_url # 下载软件 wget。。。。。
压缩解压....

使用过程中需要先了解ansible-doc帮助手册

[root@m01 ~]# ansible-doc -l # 查看所有模块说明
[root@m01 ~]# ansible-doc copy # 表示指定模块方法
[root@m01 ~]# ansible-doc -s copy # 表示指定模块参数

1.5.1 执行命令模块

1.command命令模块,不支持重定向或管道

command模块
直接写上命令即可,不支持特殊符号 | > >> {} *
# 默认模块, 执行命令
[root@m01 ~]# ansible oldboy -a "hostname"

2.shell模块,如果需要一些管道操作,则使用shell
使用起来与command一致,shell模块支持管道 特殊符号

[root@m01 ~]# ansible oldboy -m shell -a "ifconfig|grep eth0" -f 50
[root@m01 ~]# ansible web -i hosts -m command -a 'ip a |grep eth0'
172.16.1.10 | FAILED | rc=255 >>
Command "|grep" is unknown, try "ip address help".non-zero
return code
172.16.1.7 | FAILED | rc=255 >>
Command "|grep" is unknown, try "ip address help".non-zero
return code
172.16.1.9 | FAILED | rc=255 >>
Command "|grep" is unknown, try "ip address help".non-zero
return code
172.16.1.8 | FAILED | rc=255 >>
Command "|grep" is unknown, try "ip address help".non-zero
return code
[root@m01 ~]# ansible web -i hosts -m shell -a 'ip a |grep eth0'
172.16.1.7 | CHANGED | rc=0 >>
2: eth0: <BROADCAST,MULTICAST> mtu 1500 qdisc pfifo_fast
state DOWN group default qlen 1000
172.16.1.8 | CHANGED | rc=0 >>
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc
pfifo_fast state UP group default qlen 1000
inet 10.0.0.8/24 brd 10.0.0.255 scope global eth0
172.16.1.10 | CHANGED | rc=0 >>
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc
pfifo_fast state UP group default qlen 1000
inet 10.0.0.10/24 brd 10.0.0.255 scope global eth0
172.16.1.9 | CHANGED | rc=0 >>
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc
pfifo_fast state UP group default qlen 1000
inet 10.0.0.9/24 brd 10.0.0.255 scope global eth0

3.script脚本模块
说明:

  • 把对应脚本传输过去
  • 运行对应的脚本

应用 :批量执行脚本

# 编写脚本
[root@m01 ~]# mkdir -p /server/scripts
[root@m01 ~]# cat /server/scripts/yum.sh
#!/usr/bin/bash
yum install -y iftop
#在本地运行模块,等同于在远程执行,不需要将脚本文件进行推送目标主机执行
[root@m01 ~]# ansible oldboy -m script -a "/server/scripts/yum.sh"
/usr/bin/python2 -Es /usr/sbin/tuned -l -P
/usr/sbin/sshd -D
\_ sshd: root@pts/0
| \_ /bin/sh -c /root/.ansible/tmp/ansible-tmp-
1622793591.59-27092-255580592839178/yum.sh && sleep 0
| \_ /bin/bash /root/.ansible/tmp/ansible-tmp-
1622793591.59-27092-255580592839178/yum.sh
| \_ /usr/bin/python /usr/bin/yum install
ipvsadm

命令和脚本模块小结

  • command 模块用于执行简易的命令,不包含特殊符号,管道,重定向,通配符
  • shell 与command 类似,支持含特殊符号,管道,重定向,通配符
  • script 分发脚本并执行脚本

1.5.2 软件管理模块

yum

yum模块
name=指定软件名字 sl cowsay 软件名字-版本
state=状态(present 或 installed 安装软件)
absent或removed 删除
latest更新
download_only=true仅下载,不安装
enablerepo安装的时候临时开启被关闭的yum源
exclude排除
ansible webserver -m yum -a "name=httpd state=present" -i hosts
ansible webserver -m yum -a "name=httpd state=absent" -i hostsansible nfs -m yum -a 'name=sl state=installed'
ansible nfs -m yum -a 'name=sl,cowsay state=installed'
#示例一、安装当前最新的Apache软件,如果存在则不安装
[root@ansible ~]# ansible webserver -m yum -a "name=httpd state=present" -i hosts
ansible lb -i hosts -m yum -a 'name=httpd state=present'
Whether to install (present or installed, latest), or remove (absent or removed) a package.#示例二、安装当前最新的Apache软件,通过epel仓库安装
[root@ansible ~]# ansible webserver -m yum -a "name=httpd state=present enablerepo=epel" -i hosts
Repoid of repositories to enable for the install/update operation. # 为了yum安装启动特点的yum源
These repos will not persist beyond the transaction. # 在本次操作中生效
When specifying multiple repos, separate them with a ",". # 如果需要指定多个通过逗号分割.
[root@m01 ~]# ansible 172.16.1.5 -i hosts -m yum -a 'name=cowsay state=present'
172.16.1.5 | FAILED! => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"msg": "No package matching 'cowsay' found available,
installed or updated",
"rc": 126,
"results": [
"No package matching 'cowsay' found available,
installed or updated"
]
}
[root@m01 ~]# ansible 172.16.1.5 -i hosts -m yum -a 'name=cowsay state=present '
[root@m01 ~]# ansible 172.16.1.5 -i hosts -m yum -a 'name=cowsay state=present enablerepo=epel'
172.16.1.5 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"installed": [
"cowsay"
]
},
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror\nLoading mirror
speeds from cached hostfile\n * base: mirrors.aliyun.com\n
* extras: mirrors.aliyun.com\n * updates:
mirrors.aliyun.com\nResolving Dependencies\n--> Running
transaction check\n---> Package cowsay.noarch 0:3.04-4.el7
will be installed\n--> Finished Dependency
Resolution\n\nDependencies
Resolved\n\n==============================================
==================================\n Package Arch
Version Repository
Size\n====================================================
============================\nInstalling:\n cowsay
noarch 3.04-4.el7 epel
42 k\n\nTransaction
Summary\n=================================================
===============================\nInstall 1
Package\n\nTotal download size: 42 k\nInstalled size: 77
k\nDownloading packages:\nRunning transaction
check\nRunning transaction test\nTransaction test
succeeded\nRunning transaction\n Installing : cowsay-
3.04-4.el7.noarch 1/1
\n Verifying : cowsay-3.04-4.el7.noarch
1/1 \n\nInstalled:\n cowsay.noarch
0:3.04-4.el7
\n\nComplete!\n"
]
}#示例三、通过互联网的rpm进行安装
[root@ansible ~]# ansible webserver -m yum -a "name=https://mirrors.tuna.tsinghua.edu.cn/zabbix/zabbix/5.0/rhel/7/x86_64/zabbix-agent-5.0.01.el7.x86_64.rpm state=present" -i hosts#示例四、安装最新版本的Apache软件,如果存在则更新Apache (了解)
[root@ansible ~]# ansible webserver -m yum -a "name=httpd state=latest" -i hosts#示例五、更新所有的软件包,但排除和kernel相关的
[root@ansible ~]# ansible 172.16.1.41 -m yum -a "name=* state=latest exclude=kernel" -i hosts
yum -y update #升级系统所有的软件包 name=* state=latest
#exclude 排除#示例六、删除Apache软件
[root@ansible ~]# ansible webserver -m yum -a "name=httpd state=absent" -i hosts
#安装多个软件包
[root@m01 ~]# ansible web -m yum -a "name=tree,cowsay,lrzsz state=installed" -i hosts

yum安装软件模块

[root@m01 ~]# ansible oldboy -m yum -a "name=httpd state=installed"
name #指定要安装的软件包名称
state #指定使用yum的方法installed,present #安装软件包removed,absent #移除软件包latest #安装最新软件包
list=ansible #列出当前仓库可用的软件包 yum list ansible 查找软件包
enablerepo # 开启某个yum源
disablerepo="epel,zabbix" #安装软件时,不从哪些仓库获取
download_only=true #仅下载软件包,不安装

yum源

yum_repository
yum源的模块
yum源配置文件
name[nginx-stable]
descriptionname=nginx stable repo
baseurl与右边一致baseurl=http://nginx.org/packages/centos/ r e l e a s e v e r / releasever/ releasever/basearch/
enabled=yesenabled=1
gpgcheck=yesgpgcheck=1
gpgkey=与右边一致gpgkey=https://nginx.org/keys/nginx_signing.key
file=nginxnginx.repo
state
yum_repository[root@web01 ~]# cat /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$base
arch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true[root@m01 ~]# cat /etc/yum.repos.d/epel.repo
[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
baseurl=http://mirrors.aliyun.com/epel/7/$basearch
failovermethod=priority
enabled=1
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7#yum源模块
name #yum源的名字
baseurl #???
file #指定yum配置文件的路径和名称 注意不需要以.repo结尾 默认使用 name的内容作为文件名
enabled yes/no #是否开启yum源 默认是 yes 开启
state #absent(删除)/present(配置 安装 这个是默认的)
description #描述信息[php] #yum_repository -a name
baseurl = http://us-east.repo.webtatic.com/yum/el7/x86_64/ #yum_repository -a baseurl
enabled = 0 #yum_repository -a enabled
name = php repo #yum_repository -a description#给 lb负载均衡 设置 php源 状态关闭
[root@m01 ~]# ansible lb -i hosts -m yum_repository -a 'name=php description="php repo" baseurl="http://useast.repo.webtatic.com/yum/el7/x86_64/" enabled=no state=present'
172.16.1.5 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"repo": "php",
"state": "present"
}
172.16.1.6 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"repo": "php",
"state": "present"
}[root@m01 ~]# ansible lb -i hosts -a 'ls -l /etc/yum.repos.d/'
172.16.1.5 | CHANGED | rc=0 >>
total 48
-rw-r--r--. 1 root root 2523 Apr 25 10:49 CentOS-Base.repo
-rw-r--r--. 1 root root 1309 Apr 8 2020 CentOS-CR.repo
-rw-r--r--. 1 root root 649 Apr 8 2020 CentOS-Debuginfo.repo
-rw-r--r--. 1 root root 314 Apr 8 2020 CentOS-fasttrack.repo
-rw-r--r--. 1 root root 630 Apr 8 2020 CentOS-Media.repo
-rw-r--r--. 1 root root 1331 Apr 8 2020 CentOS-Sources.repo
.....
[root@m01 ~]# ansible lb -i hosts -a 'cat /etc/yum.repos.d/php.repo'
172.16.1.5 | CHANGED | rc=0 >>
[php]
baseurl = http://us-east.repo.webtatic.com/yum/el7/x86_64/
enabled = 0
name = php repo
172.16.1.6 | CHANGED | rc=0 >>
[php]
baseurl = http://us-east.repo.webtatic.com/yum/el7/x86_64/
enabled = 0
name = php repo[root@m01 ~]# ansible backup -m yum_repository -a 'file=nginx name=nginx-stable description="nginx yum repo" baseurl="http://nginx.org/packages/centos/$releasever/$basearch/" enabled=yes gpgcheck=no '
172.16.1.41 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"},"changed": true,"repo": "nginx-stable","state": "present"
}
[root@m01 ~]# ansible backup -a 'cat /etc/yum.repos.d/nginx.repo'
172.16.1.41 | CHANGED | rc=0 >>
[nginx-stable]
baseurl = http://nginx.org/packages/centos/$releasever/$basearch/
enabled = 1
gpgcheck = 0
name = nginx yum repo[root@backup ~]# cat /etc/yum.repos.d/nginx.repo
[nginx-stable]
baseurl = http://nginx.org/packages/centos/$releasever/$basearch/
enabled = 1
gpgcheck = 0
name = nginx yum repo[root@m01 ~]# ansible backup -m yum -a 'name=nginx state=present'
172.16.1.41 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"},"changed": true,"changes": {"installed": ["nginx"]},"msg": "","rc": 0,"results": ["Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.aliyun.com\n * extras: mirrors.aliyun.com\n * updates: mirrors.aliyun.com\nResolving Dependencies\n--> Running transaction check\n---> Package nginx.x86_64 1:1.24.0-1.el7.ngx will be installed\n--> Processing Dependency: libpcre2-8.so.0()(64bit) for package: 1:nginx-1.24.0-1.el7.ngx.x86_64\n--> Running transaction check\n---> Package pcre2.x86_64 0:10.23-2.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package      Arch          Version                   Repository           Size\n================================================================================\nInstalling:\n nginx        x86_64        1:1.24.0-1.el7.ngx        nginx-stable        804 k\nInstalling for dependencies:\n pcre2        x86_64        10.23-2.el7               base                201 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package (+1 Dependent package)\n\nTotal download size: 1.0 M\nInstalled size: 3.3 M\nDownloading packages:\n--------------------------------------------------------------------------------\nTotal                                              825 kB/s | 1.0 MB  00:01     \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : pcre2-10.23-2.el7.x86_64                                     1/2 \n  Installing : 1:nginx-1.24.0-1.el7.ngx.x86_64                              2/2 \n----------------------------------------------------------------------\n\nThanks for using nginx!\n\nPlease find the official documentation for nginx here:\n* https://nginx.org/en/docs/\n\nPlease subscribe to nginx-announce mailing list to get\nthe most important news about nginx:\n* https://nginx.org/en/support.html\n\nCommercial subscriptions for nginx are available on:\n* https://nginx.com/products/\n\n----------------------------------------------------------------------\n  Verifying  : pcre2-10.23-2.el7.x86_64                                     1/2 \n  Verifying  : 1:nginx-1.24.0-1.el7.ngx.x86_64                              2/2 \n\nInstalled:\n  nginx.x86_64 1:1.24.0-1.el7.ngx                                               \n\nDependency Installed:\n  pcre2.x86_64 0:10.23-2.el7                                                    \n\nComplete!\n"]
}[root@backup ~]# rpm -qa nginx
nginx-1.24.0-1.el7.ngx.x86_64[root@m01 ~]# ansible backup -a 'rpm -qa nginx'
[WARNING]: Consider using the yum, dnf or zypper module rather than running 'rpm'.  If you need to use
command because yum, dnf or zypper is insufficient you can add 'warn: false' to this command task or set
'command_warnings=False' in ansible.cfg to get rid of this message.
172.16.1.41 | CHANGED | rc=0 >>
nginx-1.24.0-1.el7.ngx.x86_64

软件管理模块

  • yum
    name 软件名字,软件名+版本
    state

    • present installed
    • absent removed
    • latest
  • yum_repository
    file=xxxx /etc/yum.repos.d/xxxx.repo
    name
    description
    baseurl #yum源下载地址
    state=present或absent
    enabled=yes
    gpgcheck=yes
    gpgkey

1.5.3 文件管理模块

ansible文件管理模块,主要涉及copy文件拷贝、file文件创建、get_url文件下载
file文件创建模块 文件,目录 创建,删除

file模块
path路径或文件
statefile模块的state状态,对应不同的功能
directory 创建目录
touch 创建文件
link 创建软连接
absent 删除
onwer
group
mode
recurserecurse=yes 只有 state 为 directory的时候 才能使用.
# 1. 创建目录
[root@m01 ~]# ansible web -m file -a 'path=/code/src/nginx state=directory' -i hosts# 2. 创建文件
ansible web -m file -a 'path=/code/src/nginx/lidaoav.com state=touch' -i hosts
ansible web -m file -a 'path=/code/src/nginx/lidaoav.com state=touch' -i hosts# 3. 递归修改权限 所有者
ansible web -m file -a 'path=/code/src/state=directory owner=nobody mode=600 recurse=yes' -i hosts#1.创建目录
[root@m01 ~]# ansible oldboy -m file -a "path=/tmp/oldboy state=directory"#2.创建文件
[root@m01 ~]# ansible oldboy -m file -a "path=/tmp/tt state=touch mode=555 owner=root group=root"#3.递归授权权限
[root@m01 ~]# ansible oldboy -m file -a "path=/data owner=oldboylinux.cn group=oldboylinux.cn recurse=yes"
path #指定远程主机目录或文件信息
recurse #递归授权
state #状态directory #在远端创建目录touch #在远端创建文件link #link或hard表示创建链接文件absent #表示删除文件或目录mode #设置文件或目录权限owner #设置文件或目录属主信息group #设置文件或目录属组信息# 创建文件
[root@m01 ~]# ansible all -m file -a "path=/tmp/oldboy.txt state=touch"
172.16.1.51 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"},"changed": true,"dest": "/tmp/oldboy.txt","gid": 0,"group": "root","mode": "0644","owner": "root","size": 0,"state": "file","uid": 0
}
.....
[root@m01 ~]# ansible all -a 'ls -l /tmp/oldboy.txt'
172.16.1.41 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 326 09:29 /tmp/oldboy.txt
172.16.1.31 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 326 09:29 /tmp/oldboy.txt
172.16.1.51 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 326 09:29 /tmp/oldboy.txt
172.16.1.7 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 326 09:29 /tmp/oldboy.txt# 创建目录
[root@m01 ~]# ansible all -m file -a "path=/tmp/oldboy/a/b/c/ state=directory"
172.16.1.7 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"},"changed": true,"gid": 0,"group": "root","mode": "0755","owner": "root","path": "/tmp/oldboy/a/b/c/","size": 6,"state": "directory","uid": 0
}
....
[root@m01 ~]# ansible all -a 'tree /tmp/oldboy'
172.16.1.41 | CHANGED | rc=0 >>
/tmp/oldboy
└── a└── b└── c3 directories, 0 files
172.16.1.51 | CHANGED | rc=0 >>
/tmp/oldboy
└── a└── b└── c3 directories, 0 files
172.16.1.31 | CHANGED | rc=0 >>
/tmp/oldboy
└── a└── b└── c3 directories, 0 files
172.16.1.7 | CHANGED | rc=0 >>
/tmp/oldboy
└── a└── b└── c3 directories, 0 files# 创建连接
[root@m01 ~]# ansible all -m file -a "src=/etc/hosts path=/tmp/hosts.soft  state=link"
172.16.1.51 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"},"changed": true,"dest": "/tmp/hosts.soft","gid": 0,"group": "root","mode": "0777","owner": "root","size": 10,"src": "/etc/hosts","state": "link","uid": 0
}
....
[root@m01 ~]# ansible all -a 'ls -l /tmp/hosts.soft'
172.16.1.31 | CHANGED | rc=0 >>
lrwxrwxrwx 1 root root 10 326 09:35 /tmp/hosts.soft -> /etc/hosts
172.16.1.7 | CHANGED | rc=0 >>
lrwxrwxrwx 1 root root 10 326 09:35 /tmp/hosts.soft -> /etc/hosts
172.16.1.51 | CHANGED | rc=0 >>
lrwxrwxrwx 1 root root 10 326 09:35 /tmp/hosts.soft -> /etc/hosts
172.16.1.41 | CHANGED | rc=0 >>
lrwxrwxrwx 1 root root 10 326 09:35 /tmp/hosts.soft -> /etc/hosts#把 web服务器 wordpress 代码修改为www.www 
[root@m01 ~]# ansible web -m file  -a 'path=/data/blog/  owner=www group=www   recurse=yes state=directory  '
172.16.1.7 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"},"changed": false,"gid": 1111,"group": "www","mode": "0755","owner": "www","path": "/data/blog/","size": 4096,"state": "directory","uid": 1111
}

copy文件拷贝模块
远程拷贝

copy模块
src从哪里来 源(ansible本地目录)
dest到哪里去 目标 (目标服务器目录)
backup是否开启备份功能,如果目标存在,覆盖之前进行备份
onwer
group
mode
#1.拷贝文件文件至被控节点
[root@m01 ~]# ansible oldboy -m copy -a "src=/etc/hosts dest=/tmp/test.txt"#2.对远端已有文件进行备份,按照时间信息备份
[root@m01 ~]# ansible oldboy -m copy -a "src=/etc/hosts dest=/tmp/test.txt backup=yes"#3.复制目录 并修改所有者与权限
ansible web -m copy -a 'src=/etc/sysconfig/networkscripts/ dest=/tmp/ owner=nobody group=nobody mode=600' -i hosts#4 content 内容 写入文件内容 重定向 >
ansible web -m copy -a 'content="oldboylinux.cn" dest=/tmp/lidao.txt' -i hosts
ansible web -a 'cat /tmp/lidao.txt' -i hosts#3.向被控端主机写入数据,并且会覆盖远端文件内原有数据信息
[root@m01 ~]# ansible oldboy -m copy -a "content='oldboylinux.cn' dest=/tmp/oldboy"src #推送数据的源文件信息
dest #推送数据的目标路径
backup #对推送传输过去的文件,进行备份
content #直接批量在被管理端文件中添加内容
group #将本地文件推送到远端,指定文件属组信息
owner #将本地文件推送到远端,指定文件属主信息
mode #将本地文件推送到远端,指定文件权限信息# 拷贝
[root@m01 ~]# ansible all -m copy -a 'src=/server/hosts dest=/etc/hosts backup=yes'
172.16.1.7 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"},"backup_file": "/etc/hosts.2076.2024-03-26@09:50:40~","changed": true,"checksum": "f89b205faa913e33da63c81ac0d3c471832caa98","dest": "/etc/hosts","gid": 0,"group": "root","md5sum": "200d60001fc4513cfac46d40b019d706","mode": "0644","owner": "root","size": 389,"src": "/root/.ansible/tmp/ansible-tmp-1711417838.48-26587-101985054098133/source","state": "file","uid": 0
}
....[root@m01 ~]# ansible all -a 'tail -2 /etc/hosts '              
172.16.1.51 | CHANGED | rc=0 >>
172.16.1.61 m01
172.16.1.71 m02 zabbix.etiantian.org
172.16.1.31 | CHANGED | rc=0 >>
172.16.1.61 m01
172.16.1.71 m02 zabbix.etiantian.org
172.16.1.41 | CHANGED | rc=0 >>
172.16.1.61 m01
172.16.1.71 m02 zabbix.etiantian.org
172.16.1.7 | CHANGED | rc=0 >>
172.16.1.61 m01
172.16.1.71 m02 zabbix.etiantian.org
[root@m01 ~]# ansible all -m shell -a 'tail -2 /etc/hosts*~ '
172.16.1.31 | CHANGED | rc=0 >>
172.16.1.51 db01 db01.etiantian.org
172.16.1.61 m01
172.16.1.51 | CHANGED | rc=0 >>
172.16.1.51 db01 db01.etiantian.org
172.16.1.61 m01
172.16.1.7 | CHANGED | rc=0 >>
10.0.0.3 www.etiantian.org
10.0.0.4 blog.etiantian.org
172.16.1.41 | CHANGED | rc=0 >>
172.16.1.51 db01 db01.etiantian.org
172.16.1.61 m01
[root@m01 ~]# ansible all -m shell -a 'head -20 /etc/hosts*~ '
172.16.1.31 | CHANGED | rc=0 >>
127.0.0.1    localhost localhost.localdomain localhost4 localhost4.localdomain4
::1          localhost localhost.localdomain localhost6 localhost6.localdomain6
172.16.1.5 lb01
172.16.1.6 lb02
172.16.1.7 web01
172.16.1.8 web02
172.16.1.9 sweb01
172.16.1.10 sweb02
172.16.1.31 nfs01
172.16.1.41 backup
172.16.1.51 db01 db01.etiantian.org
172.16.1.61 m01
172.16.1.51 | CHANGED | rc=0 >>
127.0.0.1    localhost localhost.localdomain localhost4 localhost4.localdomain4
::1          localhost localhost.localdomain localhost6 localhost6.localdomain6
...# copy模块
[root@m01 ~]# ansible all    -m  copy    -a  'src=/etc/yum.repos.d  dest=/tmp/  '
172.16.1.31 | CHANGED => {"changed": true,"dest": "/tmp/","src": "/etc/yum.repos.d"
}
172.16.1.7 | CHANGED => {"changed": true,"dest": "/tmp/","src": "/etc/yum.repos.d"
}
172.16.1.41 | CHANGED => {"changed": true,"dest": "/tmp/","src": "/etc/yum.repos.d"
}
172.16.1.51 | CHANGED => {"changed": true,"dest": "/tmp/","src": "/etc/yum.repos.d"
}[root@m01 ~]# ansible all  -m shell  -a  'ls -l /tmp/yum.repos.d/'
172.16.1.31 | CHANGED | rc=0 >>
总用量 44
-rw-r--r-- 1 root root 2523 326 09:56 CentOS-Base.repo
-rw-r--r-- 1 root root 1309 326 09:56 CentOS-CR.repo
-rw-r--r-- 1 root root  649 326 09:56 CentOS-Debuginfo.repo
-rw-r--r-- 1 root root  314 326 09:57 CentOS-fasttrack.repo
-rw-r--r-- 1 root root  630 326 09:57 CentOS-Media.repo
-rw-r--r-- 1 root root 1331 326 09:57 CentOS-Sources.repo
-rw-r--r-- 1 root root 8515 326 09:57 CentOS-Vault.repo
-rw-r--r-- 1 root root  616 326 09:57 CentOS-x86_64-kernel.repo
-rw-r--r-- 1 root root  664 326 09:57 epel.repo
....#复制代码的时候 修改代码的所有者 www www 
ansible all    -m  copy    -a  'src=/data/blog/  dest=/tmp/  owner=www  group=www  '

get_url文件下载模块
ansible中的wget命令

#1.通过get_url下载文件或者软件
[root@m01 ~]# ansible webservers -m get_url -a "url=http,https dest=/opt mode=0777" -i ./hosts ansible web -m get_url -a 'url=https://mirrors.tuna.tsinghua.edu.cn/zabbix/zabbix/5.0/rhel/7/x86_64/zabbix-get-5.0.0-1.el7.x86_64.rpmdest=/tmp/ '#2.下载一个文件前先进行md5校验,通过则下载,不通过则失败
ansible webservers -m get_url -a "url=http,https dest=/opt mode=0777 checksum=md5:76eb3af80ffd" -i ./hostsurl #文件在网络上的具体位置
dest #下载到被控端的哪个目录下
checksum #校验(md5 sha256)[root@m01 ~]# ansible  all  -m url_get  -a 'url=https://mirrors.tuna.tsinghua.edu.cn/gnu/gawk/gawk-5.1.0.tar.gz  dest=/tmp/'
172.16.1.51 | FAILED! => {"msg": "The module url_get was not found in configured module paths"
}
172.16.1.31 | FAILED! => {"msg": "The module url_get was not found in configured module paths"
}
172.16.1.41 | FAILED! => {"msg": "The module url_get was not found in configured module paths"
}
172.16.1.7 | FAILED! => {"msg": "The module url_get was not found in configured module paths"
}[root@m01 ~]# ansible-doc -l |grep get
netapp_e_iscsi_target                                         NetApp E-Series manage iSCSI target confi...
gcp_compute_target_http_proxy                                 Creates a GCP TargetHttpProxy
cloudwatchlogs_log_group_info                                 get information about log_group in CloudW...
gcp_compute_target_pool                                       Creates a GCP TargetPool
cloudwatchevent_rule                                          Manage CloudWatch Event rules and targets
shell                                                         Execute shell commands on targets
make                                                          Run targets in a Makefile
open_iscsi                                                    Manage iSCSI targets with Open-iSCSI
ce_snmp_target_host                                           Manages SNMP target host configuration on...
gcp_compute_target_tcp_proxy                                  Creates a GCP TargetTcpProxy
vmware_target_canonical_facts                                 Return canonical (NAA) from an ESXi host ...
elb_target_info                                               Gathers which target groups a target is a...
gcp_compute_target_vpn_gateway                                Creates a GCP TargetVpnGateway
gcp_compute_target_vpn_gateway_info                           Gather info for GCP TargetVpnGateway
gcp_compute_target_https_proxy                                Creates a GCP TargetHttpsProxy
gcp_compute_target_tcp_proxy_info                             Gather info for GCP TargetTcpProxy
gcp_compute_target_pool_info                                  Gather info for GCP TargetPool
vmware_target_canonical_info                                  Return canonical (NAA) from an ESXi host ...
get_url                                                       Downloads files from HTTP, HTTPS, or FTP ...
fortios_report_chart                                          Report chart widget configuration in Fort...
[root@m01 ~]# ansible  all  -m get_url  -a 'url=https://mirrors.tuna.tsinghua.edu.cn/gnu/gawk/gawk-5.1.0.tar.gz  dest=/tmp/'
172.16.1.51 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"},"changed": true,"checksum_dest": null,"checksum_src": "18cea4de8b9c116fcbdbcc0837966f6b21338bed","dest": "/tmp/gawk-5.1.0.tar.gz","elapsed": 2,"gid": 0,"group": "root","md5sum": "f719bc9966df28e67fc6ebc405e7ea03","mode": "0644","msg": "OK (6001060 bytes)","owner": "root","size": 6001060,"src": "/root/.ansible/tmp/ansible-tmp-1711418756.48-32985-232926983241900/tmps7ULow","state": "file","status_code": 200,"uid": 0,"url": "https://mirrors.tuna.tsinghua.edu.cn/gnu/gawk/gawk-5.1.0.tar.gz"
}
......
[root@m01 ~]# ansible all -m shell -a 'ls -l /tmp/gawk*'
172.16.1.41 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 6001060 326 10:05 /tmp/gawk-5.1.0.tar.gz
172.16.1.51 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 6001060 326 10:05 /tmp/gawk-5.1.0.tar.gz
172.16.1.31 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 6001060 326 10:06 /tmp/gawk-5.1.0.tar.gz
172.16.1.7 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 6001060 326 10:06 /tmp/gawk-5.1.0.tar.gz
file ansible all   -m file -a "path=/tmp/oldboy.txt   state=touch"#ansible all   -m file -a "path=/tmp/oldboy.txt   state=touch"ansible all  -a 'ls -l /tmp/oldboy.txt'#ansible all   -m file -a "path=/tmp/oldboy/a/b/c/   state=directory"ansible all   -m file -a "path=/tmp/oldboy/a/b/c/   state=directory"ansible all  -a 'tree /tmp/oldboy'ansible all   -m file -a "path=/tmp/oldboy/lidao/a/b/d/d/oldboy.txt   state=directory"ansible all  -a 'tree /tmp/oldboy'ansible all  -a 'tree -F /tmp/oldboy'ansible all   -m file -a "path=/tmp/old/dao/a/b/d/d/oldboy.txt   state=touch"ansible all   -m file -a "src=/etc/hosts  path=/tmp/hosts.soft   state=link"ansible all  -a 'll /tmp/hosts.soft'ansible all  -a 'ls -l /tmp/hosts.soft'[root@m01 scripts]# #把 web服务器 wordpress 代码修改为www.www 
[root@m01 scripts]# ansible web -m file  -a 'path=/data/blog/  owner=www group=www   recurse=yes state=directory  '
172.16.1.7 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": true, "gid": 1111, "group": "www", "mode": "0755", "owner": "www", "path": "/data/blog/", "size": 4096, "state": "directory", "uid": 1111
}#批量分发 hosts文件 
cp /etc/hosts /server/
ansible all    -m  copy    -a  'src=/server/hosts  dest=/etc/hosts  backup=yes'
ansible all -a 'tail -2  /etc/hosts'
ansible all -a 'head -20  /etc/hosts*'
ansible all -m shell -a 'head -20  /etc/hosts*'
ansible all -m shell -a 'head -20  /etc/hosts*~'
ansible all -m shell -a 'cat    /etc/hosts*~'#批量分发 目录
ansible all    -m  copy    -a  'src=/etc/yum.repos.d  dest=/tmp/  '
ansible all  -a  'ls -l /tmp/'
ansible all  -m shell  -a  'ls -l /tmp/yum.repos.d/'#复制代码的时候 修改代码的所有者 www www 	
ansible all    -m  copy    -a  'src=/data/blog/  dest=/tmp/  owner=www  group=www  '# url_get  
ansible  all  -m url_get  -a 'url=https://mirrors.tuna.tsinghua.edu.cn/gnu/gawk/gawk-5.1.0.tar.gz  dest=/tmp/'

文件相关模块

  • file 创建、删除 文件/目录/软链接
    path= 指定文件、目录 (类似于dest)
    state=
    directory 目录
    touch 文件
    link 软链接
    owner
    group
    mode
    recurse 递归

  • copy 远程拷贝(分发文件、目录)
    src 源
    dest 目标
    backup 如果目标存在则备份
    owner
    group
    mode

    ​ content 写入内容 与dest一起使用

  • get_url
    url
    dest

1.5.4 服务管理模块

  • systemd (systemctl命令)模块
  • service (C5、6、7、8)
[root@m01 ~]# ansible all   -m systemd   -a  'name=crond  state=stopped'
172.16.1.41 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"},"changed": true,"name": "crond","state": "stopped","status": {"ActiveEnterTimestamp": "二 2024-03-26 08:39:40 CST","ActiveEnterTimestampMonotonic": "5014598","ActiveExitTimestampMonotonic": "0","ActiveState": "active","After": "systemd-journald.socket time-sync.target systemd-user-sessions.service auditd.service system.slice basic.target","AllowIsolate": "no","AmbientCapabilities": "0","AssertResult": "yes","AssertTimestamp": "二 2024-03-26 08:39:40 CST","AssertTimestampMonotonic": "5012332","Before": "shutdown.target multi-user.target","BlockIOAccounting": "no","BlockIOWeight": "18446744073709551615","CPUAccounting": "no","CPUQuotaPerSecUSec": "infinity","CPUSchedulingPolicy": "0","CPUSchedulingPriority": "0","CPUSchedulingResetOnFork": "no","CPUShares": "18446744073709551615","CanIsolate": "no","CanReload": "yes","CanStart": "yes","CanStop": "yes","CapabilityBoundingSet": "18446744073709551615","CollectMode": "inactive","ConditionResult": "yes","ConditionTimestamp": "二 2024-03-26 08:39:40 CST","ConditionTimestampMonotonic": "5012332","Conflicts": "shutdown.target","ControlGroup": "/system.slice/crond.service","ControlPID": "0","DefaultDependencies": "yes","Delegate": "no","Description": "Command Scheduler","DevicePolicy": "auto","EnvironmentFile": "/etc/sysconfig/crond (ignore_errors=no)","ExecMainCode": "0","ExecMainExitTimestampMonotonic": "0","ExecMainPID": "721","ExecMainStartTimestamp": "二 2024-03-26 08:39:40 CST","ExecMainStartTimestampMonotonic": "5014524","ExecMainStatus": "0","ExecReload": "{ path=/bin/kill ; argv[]=/bin/kill -HUP $MAINPID ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }","ExecStart": "{ path=/usr/sbin/crond ; argv[]=/usr/sbin/crond -n $CRONDARGS ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }","FailureAction": "none","FileDescriptorStoreMax": "0","FragmentPath": "/usr/lib/systemd/system/crond.service","GuessMainPID": "yes","IOScheduling": "0","Id": "crond.service","IgnoreOnIsolate": "no","IgnoreOnSnapshot": "no","IgnoreSIGPIPE": "yes","InactiveEnterTimestampMonotonic": "0","InactiveExitTimestamp": "二 2024-03-26 08:39:40 CST","InactiveExitTimestampMonotonic": "5014598","JobTimeoutAction": "none","JobTimeoutUSec": "0","KillMode": "process","KillSignal": "15","LimitAS": "18446744073709551615","LimitCORE": "18446744073709551615",
......
[root@m01 ~]# ansible all -m shell -a 'ps -ef|grep crond'
172.16.1.31 | CHANGED | rc=0 >>
root       3664      1  0 10:33 ?        00:00:00 /usr/sbin/crond -n
root       3733   3728  0 10:33 pts/1    00:00:00 /bin/sh -c ps -ef|grep crond
root       3735   3733  0 10:33 pts/1    00:00:00 grep crond
172.16.1.51 | CHANGED | rc=0 >>
root       3828      1  0 10:33 ?        00:00:00 /usr/sbin/crond -n
root       3897   3892  0 10:33 pts/1    00:00:00 /bin/sh -c ps -ef|grep crond
root       3899   3897  0 10:33 pts/1    00:00:00 grep crond
172.16.1.41 | CHANGED | rc=0 >>
root       5184      1  0 10:33 ?        00:00:00 /usr/sbin/crond -n
root       5253   5248  0 10:33 pts/1    00:00:00 /bin/sh -c ps -ef|grep crond
root       5255   5253  0 10:33 pts/1    00:00:00 grep crond
172.16.1.7 | CHANGED | rc=0 >>
root       3613      1  0 10:33 ?        00:00:00 /usr/sbin/crond -n
root       3682   3677  0 10:33 pts/1    00:00:00 /bin/sh -c ps -ef|grep crond
root       3684   3682  0 10:33 pts/1    00:00:00 grep crond#开启或关闭 服务
ansible all   -m systemd   -a  'name=crond  state=stopped'
ansible all   -m systemd   -a  'name=crond  state=started'
ansible all   -m systemd   -a  'name=crond  state=reloaded或restarted'###开机自启动 
ansible all   -m systemd   -a  'name=crond  enabled=yes '###开机自启动并启动服务 
ansible all   -m systemd   -a  'name=crond  enabled=yes state=started'daemon_reload 未来我们修改了 systemctl对应的配置的时候 需要执行

ansible管理服务的启动与停止,使用service
实现服务开启关闭/重启 , 开机自启动

#1.启动crond服务,并加入开机自启
[root@m01 ~]# ansible webservers -m service -a "name=crond state=started enabled=yes"
[root@m01 ~]# ansible all -i hosts -m service -a 'name=crond state=started enabled=yes ' -f 20#2.停止crond服务,并删除开机自启
[root@m01 ~]# ansible webservers -m service -a "name=crond state=stopped enabled=no"
[root@m01 ~]# ansible lb -i hosts -m service -a 'name=crond state=stopped enabled=no ' -f 20#3.重启crond服务
[root@m01 ~]# ansible webservers -m service -a "name=crond state=restarted"#4.重载crond服务 优雅的重启 重新读取配置文件
[root@m01 ~]# ansible webservers -m service -a "name=crond state=reloaded"
name # 定义要启动服务的名称
state # 指定服务状态started #启动服务stopped #停止服务restarted #重启服务reloaded #重载服务
enabled #开机自启
模块对比systemd(7 8 )service(5678)
服务名称namename
状态statestate
是否开机自启动enabledenabled
系统重新读取system配置daemon_reload
指定运行级别runlevel
推荐与建议centos 7 8 rockylinux使用适用于C5 6

1.5.5 用户管理模块

ansible管理用户与组使用user、group模块

group模块
name
gid
statepresent(默认)| absent
user模块
name
uid
shell
create_home
removeFalse/True(userdel -r)
state

1.group组模块

[root@m01 ~]# ansible oldboy -m group -a "name=oldgirl gid=888"
name #指定创建的组名
gid #指定组的gid
stateabsent #移除远端主机的组present #创建远端主机的组(默认)

2.user模块

#1.创建用户指定uid和gid,不创建家目录也不允许登陆
[root@m01 ~]# ansible oldboy -m user -a "name=oldgirl uid=888 group=888 shell=/sbin/nologin create_home=no"#2.删除用户 指定用户名即可
userdel
[root@m01 ~]# ansible webservers -m user -a "name=tmd state=absent" -i ./hosts#3.给新创建的用户生成ssh密钥对
[root@m01 ~]# ansible webservers -m user -a "name=oo uid=6677 group=adm generate_ssh_key=yes ssh_key_bits=2048
ssh_key_file=.ssh/id_rsa" -i ./hosts
generate_ssh_key=yes
ssh_key_bits=2048
ssh_key_file=.ssh/id_rsa #私钥#4.将明文密码进行hash加密,然后进行用户创建
passwd oldboy
1 #明文密码
1 #加密后是fdslkjalkdsjflklkjakfdslafdsakjadsfsfdsafdsafdsafdsa[root@m01 ~]# ansible localhost -m debug -a "msg={{'123456' | password_hash('sha512', 'salt') }}"
localhost | SUCCESS => {
"msg": "$6$salt$MktMKPZJ6t59"
}
[root@m01 ~]# ansible webservers -m user -a 'name=xlw password=$6$salt$MktMKPZJ6t59 create_home=yes shell=/bin/bash' -i ./hosts
uid #指定用户的uid
group #指定用户组名称
groups #指定附加组名称
password #给用户添加密码(记得单引号) -a
"name=oldboy password='加密后的密码'"
shell #指定用户登录shell
create_home #是否创建家目录
state #present /absent
   #01 添加用户rsync,指定他的uid和gid 999 虚拟用户##1)添加用户组  rsync gid 999  groupadd -g  999  rsync ##2)添加用户    rsync uid 999  组是rsync   -s /sbin/nologin -M useradd  -u  999 -g rsync   -s /sbin/nologin -M    rsync  [root@m01 ~]# ansible  db  -m group   -a 'name=rsync2 gid=10086 state=present'
172.16.1.51 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": true, "gid": 10086, "name": "rsync2", "state": "present", "system": false
}
[root@m01 ~]# ansible  db  -m user  -a 'name=rsync2 uid=10086 group=rsync2 shell=/sbin/nologin create_home=no state=present'
172.16.1.51 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": true, "comment": "", "create_home": false, "group": 10086, "home": "/home/rsync2", "name": "rsync2", "shell": "/sbin/nologin", "state": "present", "stderr": "正在创建信箱文件: 文件已存在\n", "stderr_lines": ["正在创建信箱文件: 文件已存在"], "system": false, "uid": 10086
}
[root@m01 ~]# 
[root@m01 ~]# ansible db -a 'id rsync2'
172.16.1.51 | CHANGED | rc=0 >>
uid=10086(rsync2) gid=10086(rsync2)=10086(rsync2)
[root@m01 ~]# ansible db -a 'grep rsync2 /etc/passwd'
172.16.1.51 | CHANGED | rc=0 >>
rsync2:x:10086:10086::/home/rsync2:/sbin/nologin

1.5.6 定时任务模块

crond定时任务模块

cron模块Linux定时任务内容cron模块格式
注释说明#this is backup scripts by lidao996 at 20211111name=“this is backup…”
00minute=00
00hour=00
*day=* (如果是*号可以不写)
*month=*
*weekday=*
指令、脚本sh /sum.sh &>/dev/nulljob=“sh /sum.sh &>/dev/null”
状态state=present(默认)|absent
ansible all  -a   'crontab -l'
ansible all  -m cron  -a 'name="print name to file" minute="*/3" job="echo oldboy &>>/tmp/oldboy.txt" state=present  '
ansible all  -a   'crontab -l'
ansible all  -m cron  -a 'name="print name to file" state=absent  '
ansible all  -a   'crontab -l'[root@m01 ~]# ansible all  -m cron  -a 'name="print name to file" minute="*/3" job="echo oldboy &>>/tmp/oldboy.txt" state=present  '
172.16.1.31 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"},"changed": true,"envs": [],"jobs": ["print name to file"]
}
....
[root@m01 ~]# ansible all  -m cron  -a 'name="print name to file" minute="*/3" job="echo oldboy &>>/tmp/oldboy.txt" disabled=yes '
172.16.1.31 | CHANGED => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"},"changed": true,"envs": [],"jobs": ["print name to file"]
}
....
[root@m01 ~]# ansible all  -a   'crontab -l'
172.16.1.41 | CHANGED | rc=0 >>
#Ansible: print name to file
#*/3 * * * * echo oldboy &>>/tmp/oldboy.txt
172.16.1.31 | CHANGED | rc=0 >>
00 00 * * * /bin/sh /server/scripts/bak.sh &>/dev/null
#Ansible: print name to file
#*/3 * * * * echo oldboy &>>/tmp/oldboy.txt
172.16.1.51 | CHANGED | rc=0 >>
#Ansible: print name to file
#*/3 * * * * echo oldboy &>>/tmp/oldboy.txt
172.16.1.7 | CHANGED | rc=0 >>
#Ansible: print name to file
#*/3 * * * * echo oldboy &>>/tmp/oldboy.txt#注意事项: ##01 一定要指定name##02 不使用的定时任务,可以disabled注释掉。
   #垃圾箱alias  rm='mv -t /tmp/ $*'
cron模块格式
name=“his is backup…”
minute=00
hour=00
day=* (如果是*号可以不写)
month=*
weekday=*
job=“sh /sum.sh &>/dev/null”
state=present(默认)|absent
disabled是否注释,只有state=present才会注释
# 正常使用crond服务(默认没写的时间都算*表示)
[root@m01 ~]# crontab -l
#yum install 脚本
* * * * * /bin/sh /server/scripts/yum.sh &>/dev/null-m cron
-a
name #必须要添加一个
minute hour day month weekday job
state present(添加 默认)/absent(删除)* * * * * /bin/sh
/server/scripts/yum.sh &>/dev/null
minute hour day month weekday job# 使用ansible添加一条定时任务
[root@m01 ~]# ansible webservers -m cron -a "minute=* hour=* day=* month=* weekday=* job='/bin/sh test.sh'"
[root@m01 ~]# ansible webservers -m cron -a "job='/bin/sh test.sh'"# 设置定时任务注释信息,防止重复,name设定
[root@m01 ~]# ansible webservers -m cron -a "name='cron01' job='/bin/sh test.sh'"# 删除相应定时任务
[root@m01 ~]# ansible webservers -m cron -a "name='ansible cron02' minute=0 hour=0 job='/bin/sh test.sh' state=absent"# 注释相应定时任务,使定时任务失效
[root@m01 scripts]# ansible oldboy -m cron -a "name='ansible cron01' minute=0 hour=0 job='/bin/sh test.sh' disabled=yes"
[root@m01 ~]# ansible lb -i hosts -m cron -a 'name="sync02" minute="*/2" job="/sbin/ntpdate ntp1.aliyun.com &>/dev/null" '
172.16.1.6 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"sync time by lidao996 ",
"sync time by lidao996",
"sync02"
]
}
172.16.1.5 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"sync time by lidao996 ",
"sync time by lidao996",
"sync02"
]
}[root@m01 ~]# ansible lb -i hosts -a 'crontab -l'
172.16.1.6 | CHANGED | rc=0 >>
#Ansible: sync time by lidao996
*/2 * * * * /sbin/ntpdate ntp1.aliyun.com &>/dev/null
#Ansible: sync time by lidao996
#*/2 * * * * /sbin/ntpdate ntp1.aliyun.com &>/dev/null
#Ansible: sync02
*/2 * * * * /sbin/ntpdate ntp1.aliyun.com &>/dev/null
172.16.1.5 | CHANGED | rc=0 >>
#Ansible: sync time by lidao996
*/2 * * * * /sbin/ntpdate ntp1.aliyun.com &>/dev/null
#Ansible: sync time by lidao996
#*/2 * * * * /sbin/ntpdate ntp1.aliyun.com &>/dev/null
#Ansible: sync02
*/2 * * * * /sbin/ntpdate ntp1.aliyun.com &>/dev/null
[root@m01 ~]# ansible lb -i hosts -m cron -a 'name="sync02" minute="*/2" job="/sbin/ntpdate ntp1.aliyun.com &>/dev/null" disabled=yes '
[root@m01 ~]# ansible lb -i hosts -m cron -a 'name="sync02" minute="*/2" job="/sbin/ntpdate ntp1.aliyun.com &>/dev/null" disabled=yes '
172.16.1.6 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"sync time by lidao996 ",
"sync time by lidao996",
"sync02"
]
}
172.16.1.5 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"sync time by lidao996 ",
"sync time by lidao996",
"sync02"
]
}[root@m01 ~]# ansible lb -i hosts -a 'crontab -l'
172.16.1.6 | CHANGED | rc=0 >>
#Ansible: sync time by lidao996
*/2 * * * * /sbin/ntpdate ntp1.aliyun.com &>/dev/null
#Ansible: sync time by lidao996
#*/2 * * * * /sbin/ntpdate ntp1.aliyun.com &>/dev/null
#Ansible: sync02
#*/2 * * * * /sbin/ntpdate ntp1.aliyun.com &>/dev/null
172.16.1.5 | CHANGED | rc=0 >>
#Ansible: sync time by lidao996
*/2 * * * * /sbin/ntpdate ntp1.aliyun.com &>/dev/null
#Ansible: sync time by lidao996
#*/2 * * * * /sbin/ntpdate ntp1.aliyun.com &>/dev/null
#Ansible: sync02
#*/2 * * * * /sbin/ntpdate ntp1.aliyun.com &>/dev/null-m cron
-a
name #指定名字
minute
hour
day
month
weekday
state present/absent
disabled # 是否注释

1.5.7 磁盘挂载模块

mount挂载模块
模块:磁盘挂载相关模块

#01 把nfs上面的共享挂载到 /mnt目录下面 
##01)安装nfs 
ansible all  -m yum -a  'name=nfs-utils state=present'
##02)挂载nfs 
ansible all -m mount   -a  'fstype=nfs src=172.16.1.31:/data/zh  path=/mnt/lidao-new-nfs-mount--help/a/b/c/d/f/   state=mounted'#02 注意事项: 
## mount 模块中 state 是present 是只修改/etc/fstab  
## mount 模块中 state 是mounted 是挂载并修改/etc/fstab  
mount模块mount命令mount模块
指定文件系统类型-t nfsfstype=nfs
172.16.1.31:/data/zhsrc=172.16.1.31:/data/zh
目标/mntpath=/mnt/new-lidao-mount
状态state=present|mounted (挂载)
absent|unmounted(卸载)
remounted(重新挂载)
present     # 仅修改配置     开机挂载,仅将挂载配置写入/etc/fstab
mounted     # 挂载+修改配置   挂载设备,并将配置写入/etc/fstabunmounted   # 卸载设备,不会清除/etc/fstab写入的配置
absent      # 卸载设备,会清理/etc/fstab写入的配置remounted   #重新挂载 
#在backup服务器上安装nfs
#配置
#创建目录 修改所有者
#启动服务并开机自启动
#backup上面进行挂载(本地测试)
#web服务器进行挂载#在backup服务器上安装nfs
ansible 172.16.1.41 -i hosts -m yum -a 'name=nfs-utils state=present'##配置
cat /etc/exports
/data-lidao/ 172.16.1.0/24(rw,all_squash) #默认压缩为nfsnobody用户
ansible 172.16.1.41 -i hosts -m copy -a 'content="/data-lidao/ 172.16.1.0/24(rw,all_squash)" dest=/etc/exports backup=yes'#创建目录 修改所有者
[root@m01 ~]# ansible 172.16.1.41 -m file -a 'path=/data-lidao/ owner=nfsnobody group=nfsnobody state=directory ' -i hosts#启动服务并开机自启动
ansible 172.16.1.41 -i hosts -m service -a 'name=rpcbind state=started enabled=yes'
ansible 172.16.1.41 -i hosts -m service -a 'name=nfs state=started enabled=yes'#backup上面进行挂载(本地测试)
ansible 172.16.1.41 -i hosts -m mount -a 'src=172.16.1.41:/data-lidao/ path=/mnt/ fstype=nfs state=mounted'#web服务器进行挂载
挂载到web服务器的 /code/upload/img
[root@m01 ~]# ansible web -i hosts -m mount -a 'src=172.16.1.41:/data-lidao path=/code/upload/img fstype=nfs state=mounted'#10.0.0.7作为nfs服务端,10.0.0.8作为nfs客户端挂载
[root@m01 ~]# ansible web01 -m yum -a 'name=nfs-utils state=present' -i ./hosts
[root@m01 ~]# ansible web01 -m file -a 'path=/data state=directory' -i ./hosts
[root@m01 ~]# ansible web01 -m copy -a 'content="/data 172.16.1.0/24(rw,sync,no_all_squash)" dest=/etc/exports' - i ./hosts
[root@m01 ~]# ansible web01 -m systemd -a "name=nfs state=started enabled=yes" -i ./hosts#配置挂载
[root@m01 ~]# ansible web02 -m mount -a "src=172.16.1.7:/data path=/data fstype=nfs opts=defaults state=present"
[root@m01 ~]# ansible web02 -m mount -a "src=172.16.1.7:/data path=/data fstype=nfs opts=defaults state=mounted"
[root@m01 ~]# ansible web02 -m mount -a "src=172.16.1.7:/data path=/data fstype=nfs opts=defaults state=unmounted"
[root@m01 ~]# ansible web02 -m mount -a "src=172.16.1.7:/data path=/data fstype=nfs opts=defaults state=absent"-m mount
-a
src # 指定源
path # 指定目标 挂载点
fstype # 指定文件系统类型 nfs
state
present # 仅修改配置 开机挂载,仅将挂载配置写入/etc/fstab
mounted # 挂载+修改配置 挂载设备,并将配置写入/etc/fstabunmounted # 卸载设备,不会清除/etc/fstab写入的配置
absent # 卸载设备,会清理/etc/fstab写入的配置remounted #重新挂载

mount模块传送门: https://docs.ansible.com/ansible/latest/collections/ansible/posix/index.html#plugins-in-ansible-posix

1.5.8 防火墙管理模块 主要看iptables

Linux下防火墙主要分为Selinux与Firewalld
1.Selinux防火墙

[root@m01 ~]# ansible webservers -m selinux -a "state=disabled" -i ./hosts

2.firewalld防火墙

[root@m01 ~]# ansible webservers -m systemd -a "name=firewalld state=started" -i ./hosts
[root@m01 ~]# ansible webservers -m firewalld -a "service=http immediate=yes permanent=yes state=enabled" - i ./hosts
[root@m01 ~]# ansible webservers -m firewalld -a "port=8080-8090/tcp immediate=yes permanent=yes state=enabled" -i ./hostsservice #指定开放或关闭的服务名称
port #指定开放或关闭的端口
masquerade #开启地址伪装
immediate #临时生效
permanent #是否添加永久生效
state #开启或是关闭
zone #指定配置某个区域
rich_rule #配置富规则
source #指定来源IP

3.iptables模块

iptables -t filter -I INPUT -s 10.0.0.0/24 -p tcp --dport 3306 -j DROP
iptables模块iptable命令iptables模块
指定表-t filtertable=filter
action=append(默认)或insert
指定链-I INPUTchain=INPUT
源ip-s 10.0.0.0/24source=10.0.0.0/24
目标ip-ddestination
协议-p tcpprotocol=tcp
源端口
目标端口–dport 3306destination_port=3306
策略-j DROPjump=DROP
状态state=absent, present(默认)
iptables -t filter -I INPUT -s 10.0.0.0/24 -p tcp --dport 3306 -j DROP
iptables -t filter -I INPUT -s 10.0.0.0/24 -p tcp --dport 3306 -j DROP -m iptables action=insert -a table=filter chain=INPUT
source=10.0.0.0/24 protocol=tcp destination_port=3306 jump=DROPaction append(默认)/insertansible 172.16.1.51 -i hosts -m iptables -a ' table=filter action=insert chain=INPUT source=10.0.0.0/24 protocol=tcp destination_port=3306 jump=DROP'
ansible 172.16.1.51 -i hosts -m iptables -a ' table=filter action=insert chain=INPUT source=172.16.1.61 protocol=tcp destination_port=3306 jump=DROP'
ansible 172.16.1.51 -i hosts -m iptables -a ' table=filter action=insert chain=INPUT source=172.16.1.61 protocol=tcp destination_port=3306 jump=DROP state=absent'-m iptables
-a
table #-t
action #默认是append追加-A insert插入-I
chain #指定链
source #-s 指定源ip ※※※※※
destination #-d 指定目标ip
protocal #-p 指定协议
source_port #--sport指定源端口
destination_port #--dport指定目标端口 ※※※※
jump #-j DROP/ACCEPT
state #present(默认,添加规则) absent(删除)
#这可以使用nginx db01 backup nfs
#ansible ad-hoc练习案例
# nfs011.安装nginx服务 #yum_repository/yum
2.编写简单网页测试内容 #copy content
3.启动服务不加入开机自启 #systemd/service
4.放行对应的端口 #iptables1.安装nginx服务
#yum_repository
ansible 172.16.1.31 -i hosts -m yum_repository -a 'name=nginx description="nginx repo" baseurl=http://nginx.org/packages/centos/7/x86_64/ enabled=yes gpgcheck=no state=present'#yum
[root@m01 ~]# ansible 172.16.1.31 -i hosts -m yum -a 'name=nginx state=installed'2.编写简单网页测试内容
ansible 172.16.1.31 -i hosts -m copy -a 'content="backup.oldoby.com" dest=/usr/share/nginx/html/index.html '3.启动服务不加入开机自启 #systemd/service
[root@m01 ~]# ansible 172.16.1.31 -i hosts -m systemd -a 'name=nginx state=started enabled=yes'4.放行对应的端口 #iptables
[root@m01 ~]# ansible 172.16.1.31 -i hosts -m iptables -a 'table=filter action=append chain=INPUT protocol=tcp destination_port=80 jump=ACCEPT'
#安装iptables 
ansible web -m yum  -a 'name=iptables-services '
#启动iptables 
ansible web -m systemd   -a 'name=iptables  state=started  enabled=no'#配置使用
#iptables    -t filter  -I INPUT  -s 10.0.0.0/24   -p tcp   --dport 3306    -j DROP 
ansible web -m iptables -a 'table=filter action=insert chain=INPUT source=10.0.0.0/24 protocol=tcp  destination_port=80 jump=DROP state=present'
ansible web -m iptables -a 'table=filter action=insert chain=INPUT source=10.0.0.0/24 protocol=tcp  destination_port=80 jump=DROP state=absent'

模块小结

分类模块名字
命令:commnad , shell , script
文件:file,copy,get_url
软件包:yum,yum_repository
服务:systemd,service
用户user,group
磁盘mount
定时任务cron
防火墙iptables

这篇关于Day02-Ansible Ad-Hoc的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/875342

相关文章

Window Server2016加入AD域的方法步骤

《WindowServer2016加入AD域的方法步骤》:本文主要介绍WindowServer2016加入AD域的方法步骤,包括配置DNS、检测ping通、更改计算机域、输入账号密码、重启服务... 目录一、 准备条件二、配置ServerB加入ServerA的AD域(test.ly)三、查看加入AD域后的变

Window Server2016 AD域的创建的方法步骤

《WindowServer2016AD域的创建的方法步骤》本文主要介绍了WindowServer2016AD域的创建的方法步骤,文中通过图文介绍的非常详细,对大家的学习或者工作具有一定的参考学习价... 目录一、准备条件二、在ServerA服务器中常见AD域管理器:三、创建AD域,域地址为“test.ly”

【Linux 从基础到进阶】Ansible自动化运维工具使用

Ansible自动化运维工具使用 Ansible 是一款开源的自动化运维工具,采用无代理架构(agentless),基于 SSH 连接进行管理,具有简单易用、灵活强大、可扩展性高等特点。它广泛用于服务器管理、应用部署、配置管理等任务。本文将介绍 Ansible 的安装、基本使用方法及一些实际运维场景中的应用,旨在帮助运维人员快速上手并熟练运用 Ansible。 1. Ansible的核心概念

如何使用Ansible实现CI/CD流水线的自动化

如何使用Ansible实现CI/CD流水线的自动化 持续集成(CI)和持续交付(CD)是现代软件开发过程中的核心实践,它们帮助团队更快地交付高质量的软件。Ansible,作为一个强大的自动化工具,可以在CI/CD流水线中发挥关键作用。本文将详细介绍如何使用Ansible实现CI/CD流水线的自动化,包括设计流水线的结构、配置管理、自动化测试、部署、以及集成Ansible与CI/CD工具(如Jen

ansible资料

ansible系列教程-强烈推荐看完ansible官方编写的例子ansible_uiJenkins配置ansiblegalaxy官方文档中文教程1中文教程2playbook进阶YAML语法fabric编写的自动化部署

使用Ansible进行多云环境的自动化部署与管理

使用Ansible进行多云环境的自动化部署与管理 引言 随着云计算技术的飞速发展,多云环境已经成为现代企业IT架构的主流选择。多云环境不仅提供了更高的灵活性和可用性,还能有效降低供应商锁定的风险。然而,多云环境的管理和部署复杂性也随之增加,传统的手动操作已经无法满足需求。Ansible作为一种简单而强大的自动化工具,可以帮助企业在多云环境中实现自动化部署和管理,显著提高效率并减少人为错误。

物联网——DMA+AD多通道

DMA简介 存储器映像 某些数据在运行时不会发生变化,则设置为常量,存在Flash存储器中,节省运行内存的空间 DMA结构图 DMA访问权限高于cpu 结构要素 软件触发源:存储器到存储器传输完成后,计数器清零 硬件触发源:ADC、定时器、串口 重写计数器时,需关闭DMA DMA请求 数据宽度与对齐 目标宽度小于传输带宽:高位补零,反之,舍弃高位 数据转运与D

javaweb-day02-2(00:40:06 XML 解析 - Dom4j解析开发包)

导入dom4j开发包:dom4j-1.6.1.jar   在工程下建一个文件夹lib,将dom4j-1.6.1.jar拷到里边。右键add to build path。  dom4j-1.6.1\lib文件夹下还有一些jar包,是开发过程中dom4j所需要依赖的jar包,如开发过程中报错,则需导入。   用dom4j怎么做呢? 只要是开源jar包提供给你的时候,它会在开源包里面提供

javaweb-day02-2(XML 解析 - Jaxp的sax方式解析)

Jaxp解析开发包 Sax解析方式只能做查询: Sax解析方式和DOM解析方式的区别:     在使用 DOM 解析 XML 文档时,需要读取整个 XML文档,在内存中构架代表整个DOM 树的Doucment对象,从而再对XML文档进行操作。此种情况下,如果XML 文档特别大,就会消耗计算机的大量内存,并且容易导致内存溢出。  SAX解析允许在读取文档的时候,即对文档进行处

替换Windows AD时,网络准入场景如何迁移对接国产身份域管?

Windows AD是迄今为止身份管理和访问控制领域的最佳实践,全球约90%的中大型企业采用AD作为底层数字身份基础设施,管理组织、用户、应用、网络、终端等IT资源。但随着信创建设在党政机关、金融、央国企、电力等各行各业铺开,对Windows AD域的替换成为企业信息安全建设中不可避免的议题之一。 鉴于AD在企业中的应用程度不同,可将企业分为轻度、中度及深度三类Windows&nbsp;AD