在线教育网站建设公司网站建设价格低
news/
2025/10/6 15:16:15/
文章来源:
在线教育网站建设,公司网站建设价格低,行业协会网站建设的方案,图书馆门户网站建设方案目录
ansible 环境安装部署
管理端安装 ansible
ansible 目录结构
配置主机清单
配置密钥对验证
ansible 命令行模块
1#xff0e;command 模块
2#xff0e;shell 模块
3#xff0e;cron 模块
4#xff0e;user 模块
5#xff0e;group 模块
6#xff0e;co…目录
ansible 环境安装部署
管理端安装 ansible
ansible 目录结构
配置主机清单
配置密钥对验证
ansible 命令行模块
1command 模块
2shell 模块
3cron 模块
4user 模块
5group 模块
6copy 模块
7file 模块
8hostname 模块
9ping 模块
10yum 模块
11service/systemd 模块
12script 模块
13. mount 模块
14. archive 模块
15. unarchive 模块
16. replace 模块
17setup 模块
inventory 主机清单
inventory 中的变量
1.主机变量
2.组变量
3.组嵌套 Ansible是一个基于Python开发的配置管理和应用部署工具现在也在自动化管理领域大放异彩。它融合了众多老牌运维工具的优点Pubbet和Saltstack能实现的功能Ansible基本上都可以实现。
Ansible能批量配置、部署、管理上千台主机。比如以前需要切换到每个主机上执行的一或多个操作使用Ansible只需在固定的一台Ansible控制节点上去完成所有主机的操作。
Ansible是基于模块工作的它只是提供了一种运行框架它本身没有完成任务的能力真正执行操作的是Ansible的模块 比如copy模块用于拷贝文件到远程主机上service模块用于管理服务的启动、停止、重启等。
Ansible其中一个比较鲜明的特性是Agentless即无Agent的存在它就像普通命令一样并非C/S软件也只需在某个作为控制节点的主机上安装一次Ansible即可通常它基于ssh连接来控制远程主机远程主机上不需要安装Ansible或其它额外的服务。
使用者在使用时在服务器终端输入命令或者playbooks会通过预定好的规则将playbook拆解为play再组织成ansible可以识别的任务调用模块和插件根据主机清单通过SSH将临时文件发给远程的客户端执行并返回结果执行结束后自动删除
Ansible的另一个比较鲜明的特性是它的绝大多数模块都具备幂等性(idempotence)。所谓幂等性指的是无论执行多少次同样的运算结果都是相同的即一条命令任意多次执行所产生的影响均与一次执行的影响相同。比如执行 systemctl stop xxx 命令来停止服务当发现要停止的目标服务已经处于停止状态它什么也不会做 所以多次停止的结果仍然是停止不会改变结果它是幂等的而 systemctl restart xxx 是非幂等的。
Ansible的很多模块在执行时都会先判断目标节点是否要执行任务所以可以放心大胆地让Ansible去执行任务重复执行某个任务绝大多数时候不会产生任何副作用。 ansible 环境安装部署
管理端 192.168.110.100 ansible 被管理端192.168.110.90 被管理端192.168.110.70
管理端安装 ansible
yum install -y epel-release //先安装 epel 源
yum install -y ansible
ansible 目录结构
/etc/ansible/ ├── ansible.cfg #ansible的配置文件一般无需修改 ├── hosts #ansible的主机清单用于存储需要管理的远程主机的相关信息 └── roles/ #公共角色目录
配置主机清单
cd /etc/ansible
vim hosts
[webservers] #配置组名
192.168.110.90 #组里包含的被管理的主机IP地址或主机名主机名需要先修改/etc/hosts文件[dbservers]
192.168.110.70
配置密钥对验证
ssh-keygen -t rsayum install -y sshpassvim /etc/ssh/ssh_config
StrictHostKeyChecking no #把注释取消把yes改为nosshpass -p zxr123 ssh-copy-id [-o StrictHostKeyCheckingno] root192.168.110.100
sshpass -p zxr123 ssh-copy-id [-o StrictHostKeyCheckingno] root192.168.110.70
ansible 命令行模块 命令格式ansible 组名 -m 模块 -a 参数列表 ansible-doc -l #列出所有已安装的模块按q退出 1command 模块
在远程主机执行命令不支持管道重定向等shell的特性。
ansible-doc -s command #-s 列出指定模块的描述信息和操作动作
ansible 192.168.110.90 -m command -a date #指定 ip 执行 date192.168.110.90 | CHANGED | rc0
2023年 07月 27日 星期四 18:16:41 CST
ansible webservers -m command -a date #指定组执行 date192.168.110.90 | CHANGED | rc0
2023年 07月 27日 星期四 18:18:14 CST
ansible dbservers -m command -a date 192.168.110.70 | CHANGED | rc0
2023年 07月 27日 星期四 18:18:41 CST
ansible all -m command -a date #all 代表所有 hosts 主机192.168.110.70 | CHANGED | rc0
2023年 07月 27日 星期四 18:19:08 CST
192.168.110.90 | CHANGED | rc0
2023年 07月 27日 星期四 18:19:08 CST
ansible all -a ls / #如省略 -m 模块则默认运行 command 模块192.168.110.70 | CHANGED | rc0
bin
boot
dev
etc
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
192.168.110.90 | CHANGED | rc0
bin
boot
data
dev
etc
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var常用的参数 chdir在远程主机上运行命令前提前进入目录 creates判断指定文件是否存在如果存在不执行后面的操作 removes判断指定文件是否存在如果存在执行后面的操作 192.168.110.90 | CHANGED | rc0
anaconda-ks.cfg
initial-setup-ks.cfg
公共
模板
视频
图片
文档
下载
音乐
桌面
192.168.110.70 | CHANGED | rc0
anaconda-ks.cfg
initial-setup-ks.cfg
公共
模板
视频
图片
文档
下载
音乐
桌面2shell 模块
在远程主机执行命令相当于调用远程主机的shell进程然后在该shell下打开一个子shell运行命令支持管道符号等功能
ansible-doc -s shell
ansible dbservers -m shell -a echo 123456 | passwd --stdin test
ansible dbservers -m shell -a echo $(ifconfig ens32 | awk NR2 {print $2}) | cut -d -f2192.168.110.70 | CHANGED | rc0
192.168.110.70
ansible dbservers -m shell -a echo $(ifconfig ens32 | awk NR2 {print \$2})192.168.110.70 | CHANGED | rc0
192.168.110.70
3cron 模块
在远程主机定义任务计划。其中有两种状态statepresent表示添加可以省略absent表示移除。
ansible-doc -s cron #按 q 退出 常用的参数minute/hour/day/month/weekday分/时/日/月/周job任务计划要执行的命令name任务计划的名称user指定计划任务属于哪个用户默认是root用户 ansible webservers -m cron -a minute*/1 job/bin/echo helloworld nametest crontab192.168.110.90 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,envs: [],jobs: [test crontab]
}ansible webservers -a crontab -l192.168.110.90 | CHANGED | rc0
#Ansible: test crontab
*/1 * * * * /bin/echo helloworld
ansible webservers -m cron -a nametest crontab stateabsent192.168.110.90 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,envs: [],jobs: []
}4user 模块
用户管理的模块
ansible-doc -s user 常用的参数name用户名必选参数statepresent|absent创建账号或者删除账号present表示创建absent表示删除systemyes|no是否为系统账号uid用户uidgroup用户基本组groups: 用户所属附加组shell默认使用的shellcreate_homeyse|no: 是否创建家目录password用户的密码建议使用加密后的字符串removeyes|no当stateabsent时是否删除用户的家目录 ansible dbservers -m user -a nametest01 #创建用户test01192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,comment: ,create_home: true,group: 1001,home: /home/test01,name: test01,shell: /bin/bash,state: present,system: false,uid: 1001
}ansible dbservers -m command -a tail /etc/passwd192.168.110.70 | CHANGED | rc0
gdm:x:42:42::/var/lib/gdm:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
nfsnobody:x:65534:65534:Anonymous NFS User:/var/lib/nfs:/sbin/nologin
gnome-initial-setup:x:988:982::/run/gnome-initial-setup/:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
zxr:x:1000:1000:zxr:/home/zxr:/bin/bash
test01:x:1001:1001::/home/test01:/bin/bash
ansible dbservers -m user -a nametest01 stateabsent #删除用户test01192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,force: false,name: test01,remove: false,state: absent
}5group 模块
用户组管理的模块
ansible-doc -s group
ansible dbservers -m group -a namemysql gid306 systemyes #创建mysql组192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,gid: 306,name: mysql,state: present,system: true
}ansible dbservers -a tail /etc/group192.168.110.70 | CHANGED | rc0
nfsnobody:x:65534:
gnome-initial-setup:x:982:
sshd:x:74:
slocate:x:21:
avahi:x:70:
postdrop:x:90:
postfix:x:89:
tcpdump:x:72:
zxr:x:1000:zxr
mysql:x:306:
ansible dbservers -m user -a nametest01 uid306 systemyes groupmysql #将test01用户添加到mysql组中192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,comment: ,create_home: true,group: 306,home: /home/test01,name: test01,shell: /bin/bash,state: present,stderr: useradd警告此主目录已经存在。\n不从 skel 目录里向其中复制任何文件。\n,stderr_lines: [useradd警告此主目录已经存在。,不从 skel 目录里向其中复制任何文件。],system: true,uid: 306
}
ansible dbservers -a tail /etc/passwd192.168.110.70 | CHANGED | rc0
gdm:x:42:42::/var/lib/gdm:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
nfsnobody:x:65534:65534:Anonymous NFS User:/var/lib/nfs:/sbin/nologin
gnome-initial-setup:x:988:982::/run/gnome-initial-setup/:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
zxr:x:1000:1000:zxr:/home/zxr:/bin/bash
test01:x:306:306::/home/test01:/bin/bash
ansible dbservers -a id test01 192.168.110.70 | CHANGED | rc0
uid306(test01) gid306(mysql) 组306(mysql)
6copy 模块
用于复制指定主机文件到远程主机的
ansible-doc -s copy 常用的参数dest:指出复制文件的目标及位置使用绝对路径如果源是目录指目标也要是目录如果目标文件已经存在会覆盖原有的内容src:指出源文件的路径可以使用相对路径或绝对路径支持直接指定目录如果源是目录则目标也要是目录mode:指出复制时目标文件的权限 owner:指出复制时目标文件的属主group:指出复制时目标文件的属组content:指出复制到目标主机上的内容不能与src一起使用 ansible dbservers -m copy -a src/etc/fstab dest/opt/fstab.bak ownerroot mode640192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,checksum: a93e3b96865a2a3fa4d88221db3b2cafbdaee9ac,dest: /opt/fstab.bak,gid: 0,group: root,md5sum: 878d3b777c97cc833cc5fb5bbb261349,mode: 0640,owner: root,secontext: system_u:object_r:usr_t:s0,size: 465,src: /root/.ansible/tmp/ansible-tmp-1690454394.34-7438-50460992613640/source,state: file,uid: 0
}
ansible dbservers -a ls -l /opt192.168.110.70 | CHANGED | rc0
总用量 4
-rw-r-----. 1 root root 465 7月 27 18:39 fstab.bak
drwxr-xr-x. 2 root root 6 10月 31 2018 rh
ansible dbservers -a cat /opt/fstab.bak192.168.110.70 | CHANGED | rc0 #
# /etc/fstab
# Created by anaconda on Fri Jun 2 16:56:02 2023
#
# Accessible filesystems, by reference, are maintained under /dev/disk
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root / xfs defaults 0 0
UUID5cef2918-6cbd-4fab-a032-6459274e4141 /boot xfs defaults 0 0
/dev/mapper/centos-swap swap swap defaults 0 0ansible dbservers -m copy -a contenthelloworld dest/opt/hello.txt #将helloworld写入/opt/hello.txt文件中192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,checksum: 6adfb183a4a2c94a2f92dab5ade762a47889a5a1,dest: /opt/hello.txt,gid: 0,group: root,md5sum: fc5e038d38a57032085441e7fe7010b0,mode: 0644,owner: root,secontext: system_u:object_r:usr_t:s0,size: 10,src: /root/.ansible/tmp/ansible-tmp-1690454577.74-7857-13428756128512/source,state: file,uid: 0
}ansible dbservers -a cat /opt/hello.txt 192.168.110.70 | CHANGED | rc0
helloworld
7file 模块
设置文件属性
ansible-doc -s file
ansible dbservers -m file -a ownertest01 groupmysql mode644 path/opt/fstab.bak #修改文件的属主属组权限等192.168.110.70 | SUCCESS {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: false,gid: 306,group: mysql,mode: 0644,owner: test01,path: /opt/fstab.bak,secontext: system_u:object_r:usr_t:s0,size: 465,state: file,uid: 306
}ansible dbservers -m file -a path/opt/fstab.link src/opt/fstab.bak statelink #设置/opt/fstab.link为/opt/fstab.bak的链接文件192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,dest: /opt/fstab.link,gid: 0,group: root,mode: 0777,owner: root,secontext: unconfined_u:object_r:usr_t:s0,size: 14,src: /opt/fstab.bak,state: link,uid: 0
}ansible dbservers -m file -a path/opt/abc.txt statetouch #创建一个文件192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,dest: /opt/abc.txt,gid: 0,group: root,mode: 0644,owner: root,secontext: unconfined_u:object_r:usr_t:s0,size: 0,state: file,uid: 0
}ansible dbservers -m file -a path/opt/abc.txt stateabsent #删除一个文件192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,path: /opt/abc.txt,state: absent
}8hostname 模块
用于管理远程主机上的主机名
ansible dbservers -m hostname -a namemysql01192.168.110.70 | CHANGED {ansible_facts: {ansible_domain: ,ansible_fqdn: mysql01,ansible_hostname: mysql01,ansible_nodename: mysql01,discovered_interpreter_python: /usr/bin/python},changed: true,name: mysql01
}9ping 模块
检测远程主机的连通性
ansible all -m ping192.168.110.90 | SUCCESS {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: false,ping: pong
}
192.168.110.70 | SUCCESS {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: false,ping: pong
}10yum 模块
在远程主机上安装与卸载软件包
ansible-doc -s yum ansible webservers -m yum -a namehttpd #安装服务192.168.110.90 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,changes: {installed: [httpd]},msg: file:///mnt/repodata/repomd.xml: [Errno 14] curl#37 - \Couldnt open file /mnt/repodata/repomd.xml\\nTrying other mirror.\n,rc: 0,results: [Loaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\n * base: mirrors.ustc.edu.cn\n * extras: mirrors.ustc.edu.cn\n * updates: mirrors.aliyun.com\nResolving Dependencies\n-- Running transaction check\n--- Package httpd.x86_64 0:2.4.6-99.el7.centos.1 will be installed\n-- Processing Dependency: httpd-tools 2.4.6-99.el7.centos.1 for package: httpd-2.4.6-99.el7.centos.1.x86_64\n-- Processing Dependency: /etc/mime.types for package: httpd-2.4.6-99.el7.centos.1.x86_64\n-- Running transaction check\n--- Package httpd-tools.x86_64 0:2.4.6-99.el7.centos.1 will be installed\n--- Package mailcap.noarch 0:2.1.41-2.el7 will be installed\n-- Finished Dependency Resolution\n\nDependencies Resolved\n\n\n Package Arch Version Repository Size\n\nInstalling:\n httpd x86_64 2.4.6-99.el7.centos.1 updates 2.7 M\nInstalling for dependencies:\n httpd-tools x86_64 2.4.6-99.el7.centos.1 updates 94 k\n mailcap noarch 2.1.41-2.el7 base 31 k\n\nTransaction Summary\n\nInstall 1 Package (2 Dependent packages)\n\nTotal download size: 2.8 M\nInstalled size: 9.6 M\nDownloading packages:\n--------------------------------------------------------------------------------\nTotal 3.8 MB/s | 2.8 MB 00:00 \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : httpd-tools-2.4.6-99.el7.centos.1.x86_64 1/3 \n Installing : mailcap-2.1.41-2.el7.noarch 2/3 \n Installing : httpd-2.4.6-99.el7.centos.1.x86_64 3/3 \n Verifying : httpd-2.4.6-99.el7.centos.1.x86_64 1/3 \n Verifying : mailcap-2.1.41-2.el7.noarch 2/3 \n Verifying : httpd-tools-2.4.6-99.el7.centos.1.x86_64 3/3 \n\nInstalled:\n httpd.x86_64 0:2.4.6-99.el7.centos.1 \n\nDependency Installed:\n httpd-tools.x86_64 0:2.4.6-99.el7.centos.1 mailcap.noarch 0:2.1.41-2.el7 \n\nComplete!\n]
}
ansible webservers -m yum -a namehttpd stateabsent #卸载服务192.168.110.90 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,changes: {removed: [httpd]},msg: file:///mnt/repodata/repomd.xml: [Errno 14] curl#37 - \Couldnt ope n file /mnt/repodata/repomd.xml\\n正在尝试其它镜像。\n,rc: 0,results: [已加载插件fastestmirror, langpacks\n正在解决依赖关系\n-- 正在检查事 务\n--- 软件包 httpd.x86_64.0.2.4.6-99.el7.centos.1 将被 删除\n-- 解决依赖关系 完成\n\n依赖关系解决\n\n \n Package 架构 版本 源 大小\n \n正在删除:\n httpd x86_64 2.4.6-99.el7 .centos.1 updates 9.4 M\n\n事务概要\n \n移除 1 软件包\n\n安装大 小9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n 正在删除 : httpd-2. 4.6-99.el7.centos.1.x86_64 1/1 \n 验证中 : httpd- 2.4.6-99.el7.centos.1.x86_64 1/1 \n\n删除:\n httpd.x86 _64 0:2.4.6-99.el7.centos.1 \n\n完毕\ n]
}
11service/systemd 模块
用于管理远程主机上的管理服务的运行状态
ansible-doc -s service 常用的参数name被管理的服务名称statestarted|stopped|restarted动作包含启动关闭或者重启enabledyes|no表示是否设置该服务开机自启runlevel如果设定了enabled开机自启去则要定义在哪些运行目标下自启动 ansible webservers -a systemctl status httpd #查看web服务器httpd运行状态192.168.110.90 | CHANGED | rc0
● httpd.service - The Apache HTTP ServerLoaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)Active: active (running) since 四 2023-07-27 19:02:18 CST; 16s agoDocs: man:httpd(8)man:apachectl(8)Main PID: 4775 (httpd)Status: Total requests: 0; Current requests/sec: 0; Current traffic: 0 B/secTasks: 6CGroup: /system.slice/httpd.service├─4775 /usr/sbin/httpd -DFOREGROUND├─4778 /usr/sbin/httpd -DFOREGROUND├─4779 /usr/sbin/httpd -DFOREGROUND├─4780 /usr/sbin/httpd -DFOREGROUND├─4781 /usr/sbin/httpd -DFOREGROUND└─4782 /usr/sbin/httpd -DFOREGROUND7月 27 19:02:18 localhost.localdomain systemd[1]: Starting The Apache HTTP Server...
7月 27 19:02:18 localhost.localdomain httpd[4775]: AH00558: httpd: Could not reliably determine the servers fully qualified domain name, using localhost.localdomain. Set the ServerName directive globally to suppress this message
7月 27 19:02:18 localhost.localdomain systemd[1]: Started The Apache HTTP Server. ansible webservers -m service -a enabledtrue namehttpd statestarted #启动httpd服务192.168.110.90 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,enabled: true,name: httpd,state: started,status: {ActiveEnterTimestamp: 四 2023-07-27 19:02:18 CST,ActiveEnterTimestampMonotonic: 3754857708,ActiveExitTimestampMonotonic: 0,ActiveState: active,After: -.mount tmp.mount remote-fs.target systemd-journald.socket network.target nss-lookup.target basic.target system.slice,AllowIsolate: no,AmbientCapabilities: 0,AssertResult: yes,AssertTimestamp: 四 2023-07-27 19:02:18 CST,AssertTimestampMonotonic: 3754788195,Before: shutdown.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: 四 2023-07-27 19:02:18 CST,ConditionTimestampMonotonic: 3754788194,Conflicts: shutdown.target,ControlGroup: /system.slice/httpd.service,ControlPID: 0,DefaultDependencies: yes,Delegate: no,Description: The Apache HTTP Server,DevicePolicy: auto,Documentation: man:httpd(8) man:apachectl(8),EnvironmentFile: /etc/sysconfig/httpd (ignore_errorsno),ExecMainCode: 0,ExecMainExitTimestampMonotonic: 0,ExecMainPID: 4775,ExecMainStartTimestamp: 四 2023-07-27 19:02:18 CST,ExecMainStartTimestampMonotonic: 3754789462,ExecMainStatus: 0,ExecReload: { path/usr/sbin/httpd ; argv[]/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errorsno ; start_time[n/a] ; stop_time[n/a] ; pid0 ; code(null) ; status0/0 },ExecStart: { path/usr/sbin/httpd ; argv[]/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errorsno ; start_time[四 2023-07-27 19:02:18 CST] ; stop_time[n/a] ; pid4775 ; code(null) ; status0/0 },ExecStop: { path/bin/kill ; argv[]/bin/kill -WINCH ${MAINPID} ; ignore_errorsno ; start_time[n/a] ; stop_time[n/a] ; pid0 ; code(null) ; status0/0 },FailureAction: none,FileDescriptorStoreMax: 0,FragmentPath: /usr/lib/systemd/system/httpd.service,GuessMainPID: yes,IOScheduling: 0,Id: httpd.service,IgnoreOnIsolate: no,IgnoreOnSnapshot: no,IgnoreSIGPIPE: yes,InactiveEnterTimestampMonotonic: 0,InactiveExitTimestamp: 四 2023-07-27 19:02:18 CST,InactiveExitTimestampMonotonic: 3754789494,JobTimeoutAction: none,JobTimeoutUSec: 0,KillMode: control-group,KillSignal: 18,LimitAS: 18446744073709551615,LimitCORE: 18446744073709551615,LimitCPU: 18446744073709551615,LimitDATA: 18446744073709551615,LimitFSIZE: 18446744073709551615,LimitLOCKS: 18446744073709551615,LimitMEMLOCK: 65536,LimitMSGQUEUE: 819200,LimitNICE: 0,LimitNOFILE: 4096,LimitNPROC: 15594,LimitRSS: 18446744073709551615,LimitRTPRIO: 0,LimitRTTIME: 18446744073709551615,LimitSIGPENDING: 15594,LimitSTACK: 18446744073709551615,LoadState: loaded,MainPID: 4775,MemoryAccounting: no,MemoryCurrent: 18446744073709551615,MemoryLimit: 18446744073709551615,MountFlags: 0,Names: httpd.service,NeedDaemonReload: no,Nice: 0,NoNewPrivileges: no,NonBlocking: no,NotifyAccess: main,OOMScoreAdjust: 0,OnFailureJobMode: replace,PermissionsStartOnly: no,PrivateDevices: no,PrivateNetwork: no,PrivateTmp: yes,ProtectHome: no,ProtectSystem: no,RefuseManualStart: no,RefuseManualStop: no,RemainAfterExit: no,Requires: basic.target system.slice -.mount,RequiresMountsFor: /var/tmp,Restart: no,RestartUSec: 100ms,Result: success,RootDirectoryStartOnly: no,RuntimeDirectoryMode: 0755,SameProcessGroup: no,SecureBits: 0,SendSIGHUP: no,SendSIGKILL: yes,Slice: system.slice,StandardError: inherit,StandardInput: null,StandardOutput: journal,StartLimitAction: none,StartLimitBurst: 5,StartLimitInterval: 10000000,StartupBlockIOWeight: 18446744073709551615,StartupCPUShares: 18446744073709551615,StatusErrno: 0,StatusText: Total requests: 0; Current requests/sec: 0; Current traffic: 0 B/sec,StopWhenUnneeded: no,SubState: running,SyslogLevelPrefix: yes,SyslogPriority: 30,SystemCallErrorNumber: 0,TTYReset: no,TTYVHangup: no,TTYVTDisallocate: no,TasksAccounting: no,TasksCurrent: 6,TasksMax: 18446744073709551615,TimeoutStartUSec: 1min 30s,TimeoutStopUSec: 1min 30s,TimerSlackNSec: 50000,Transient: no,Type: notify,UMask: 0022,UnitFilePreset: disabled,UnitFileState: disabled,WatchdogTimestamp: 四 2023-07-27 19:02:18 CST,WatchdogTimestampMonotonic: 3754857677,WatchdogUSec: 0}
}12script 模块
实现远程批量运行本地的 shell 脚本
ansible-doc -s script
vim test.sh
#!/bin/bash
echo hello ansible from script /opt/script.txtchmod x test.sh
ansible webservers -m script -a test.sh192.168.110.90 | CHANGED {changed: true,rc: 0,stderr: Shared connection to 192.168.110.90 closed.\r\n,stderr_lines: [Shared connection to 192.168.110.90 closed.],stdout: ,stdout_lines: []
}ansible webservers -a cat /opt/script.txt192.168.110.90 | CHANGED | rc0
hello ansible from script
vim test.sh
#!/bin/bash
echo $1 /opt/test.txt
echo s2 /opt/test .txtansible dbservers -m script -a test.sh abc 123!
13. mount 模块
挂载文件系统
ansible-doc -s mount 常用的参数src定义挂载设备的路径path定义挂载到哪个目录必须指定fstype指定挂载文件的系统类型必须指定xfs、iso9660、nfs...opts定义挂载的参数defaults、rw、ro...state定义挂载的状态mounted进行挂载修改/etc/fstab信息、absent永久性卸载并修改 /etc/fstab信息、unmounted临时卸载不修改/etc/fstab信息 ansible dbservers -m mount -a src/dev/sr0 path/mnt statemounted fstypeiso9660192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,dump: 0,fstab: /etc/fstab,fstype: iso9660,name: /mnt,opts: defaults,passno: 0,src: /dev/sr0
}[rootlocalhost opt]# df -hT
文件系统 类型 容量 已用 可用 已用% 挂载点
devtmpfs devtmpfs 2.0G 0 2.0G 0% /dev
tmpfs tmpfs 2.0G 0 2.0G 0% /dev/shm
tmpfs tmpfs 2.0G 13M 2.0G 1% /run
tmpfs tmpfs 2.0G 0 2.0G 0% /sys/fs/cgroup
/dev/mapper/centos-root xfs 36G 4.4G 31G 13% /
/dev/sda1 xfs 1014M 172M 843M 17% /boot
tmpfs tmpfs 394M 12K 394M 1% /run/user/42
tmpfs tmpfs 394M 0 394M 0% /run/user/0
/dev/sr0 iso9660 4.4G 4.4G 0 100% /mnt
14. archive 模块
打包压缩
ansible-doc -s archive 常用的参数path: 必须参数远程主机上需要被打包压缩的源文件/目录dest: 打包压缩后的包文件路径(包文件的父目录必须存在);如果包文件已存在则会被覆盖format: 指定压缩类型包括: bz2、gz默认、tar、xz、zipremoveyes|no: 是否删除源文件 ansible dbservers -m archive -a path/etc/yum.repos.d/ dest/opt/repo.zip formatzip192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},archived: [/etc/yum.repos.d/local.repo,/etc/yum.repos.d/repo.bak/CentOS-Base.repo,/etc/yum.repos.d/repo.bak/CentOS-CR.repo,/etc/yum.repos.d/repo.bak/CentOS-Debuginfo.repo,/etc/yum.repos.d/repo.bak/CentOS-fasttrack.repo,/etc/yum.repos.d/repo.bak/CentOS-Media.repo,/etc/yum.repos.d/repo.bak/CentOS-Sources.repo,/etc/yum.repos.d/repo.bak/CentOS-Vault.repo,/etc/yum.repos.d/repo.bak/CentOS-x86_64-kernel.repo],arcroot: /etc/yum.repos.d/,changed: true,dest: /opt/repo.zip,expanded_exclude_paths: [],expanded_paths: [/etc/yum.repos.d/],gid: 0,group: root,missing: [],mode: 0644,owner: root,secontext: unconfined_u:object_r:usr_t:s0,size: 4934,state: file,uid: 0
}
在192.168.110.70主机进行查看确实生成了repo.zip文件
[rootlocalhost opt]# ls
fstab.bak fstab.link hello.txt repo.zip rhansible dbservers -m archive -a path/opt/abc.txt,/opt/123.txt dest/opt/abc123.tar.gz formatgz removeyes192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},archived: [],arcroot: /opt/,changed: true,dest: /opt/abc123.tar.gz,expanded_exclude_paths: [],expanded_paths: [/opt/abc.txt,/opt/123.txt],gid: 0,group: root,missing: [/opt/abc.txt,/opt/123.txt],mode: 0644,owner: root,secontext: unconfined_u:object_r:usr_t:s0,size: 61,state: file,uid: 0
}15. unarchive 模块
解包解压缩
ansible-doc -s unarchive 常用的参数copy默认为 copyyes 拷贝的文件从 ansible 主机复制到远程主机copyno 表示在远程主机上寻找源文件解压srctar包源路径可以是 ansible 主机上的路径也可以是远程主机上的路径如果是远程主机上的路径则需设置 copynodest解压后文件的目标绝对路径remote_src: 和 copy 功能一样且互斥设置 remote_srcyes 表示文件在远程主机上设置为 remote_srcno 表示文件在 ansible 主机上 ansible dbservers -m unarchive -a src/opt/nginx-1.24.0.tar.gz dest/root copyyes #将 ansible 主机的压缩文件拷贝到到远程主机并解压修改文件所属组和用户192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,dest: /root,extract_results: {cmd: [/usr/bin/gtar,--extract,-C,/root,-z,-f,/root/.ansible/tmp/ansible-tmp-1690457088.96-12391-121726958971989/source],err: ,out: ,rc: 0},gid: 0,group: root,handler: TgzArchive,mode: 0550,owner: root,secontext: system_u:object_r:admin_home_t:s0,size: 4096,src: /root/.ansible/tmp/ansible-tmp-1690457088.96-12391-121726958971989/source,state: directory,uid: 0
}或者
ansible dbservers -m unarchive -a src/opt/abc.tar.gz dest/root remote_srcno
在192.168.110.70查看root目录
[rootlocalhost opt]# ls /root
anaconda-ks.cfg nginx-1.24.0 模板 图片 下载 桌面
initial-setup-ks.cfg 公共 视频 文档 音乐ansible dbservers -m unarchive -a src/opt/123.tar.gz dest/root copyno #在远程主机解包192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,dest: /root,extract_results: {cmd: [/usr/bin/gtar,--extract,-C,/root,-z,-f,/opt/yxc.tar.gz],err: ,out: ,rc: 0},gid: 0,group: root,handler: TgzArchive,mode: 0550,owner: root,secontext: system_u:object_r:admin_home_t:s0,size: 4096,src: /opt/yxc.tar.gz,state: directory,uid: 0
}或者
ansible dbservers -m unarchive -a src/opt/123.tar.gz dest/root remote_srcyes
16. replace 模块
类似于sed命令主要也是基于正则进行匹配和替换
ansible-doc -s replace 常用的参数:path必须参数指定要修改的文件regexp必须参数指定一个正则表达式replace替换regexp参数匹配到的字符串backupyes|no: 修改源文件前创建一个包含时间戳信息的备份文件before如果指定则仅替换/删除此匹配之前的内容可以和after参数结合使用after如果指定则仅替换/删除此匹配之后的内容可以和before参数结合使用owner修改文件用户名group修改文件组名mode修改文件权限 vim /opt/test.txt
11 22 33 44 55 66
aa bb cc dd ee ff
1a 2b 3c 4d 5e 6f
ansible dbservers -m replace -a path/opt/test.txt regexp33 replacecc #匹配 333 并修改为 ccc192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,msg: 1 replacements made
}11 22 cc 44 55 66
aa bb cc dd ee ff
1a 2b 3c 4d 5e 6fansible dbservers -m replace -a path/opt/test.txt regexp^(.*) replace#\1 #匹配到任意一个或多个开头的行增加注释192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,msg: 4 replacements made
}#11 22 cc 44 55 66
#aa bb cc dd ee ff
#1a 2b 3c 4d 5e 6f
ansible dbservers -m replace -a path/opt/test.txt regexp^#(.*) replace\1 #取消注释192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,msg: 3 replacements made
}11 22 cc 44 55 66
aa bb cc dd ee ff
1a 2b 3c 4d 5e 6fansible dbservers -m replace -a path/opt/test.txt regexp^(a.*) replace#\1 #匹配以 a 开头的后面有一个或者多个字符的行并在前面添加 # 注释192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,msg: 1 replacements made
}11 22 cc threethree 55 66
#aa bb cc dd ee ff
1a 2b 3c 4d 5e 6fansible dbservers -m replace -a path/opt/test.txt regexp3 replacethree beforecc192.168.110.70 | CHANGED {ansible_facts: {discovered_interpreter_python: /usr/bin/python},changed: true,msg: 2 replacements made
}11 22 cc threethree 55 66
aa bb cc dd ee ff
1a 2b 3c 4d 5e 6f17setup 模块
facts 组件是用来收集被管理节点信息的使用 setup 模块可以获取这些信息
ansible-doc -s setup
ansible webservers -m setup #获取mysql组主机的facts信息192.168.110.90 | SUCCESS {ansible_facts: {ansible_all_ipv4_addresses: [192.168.110.90,192.168.122.1],ansible_all_ipv6_addresses: [fe80::992:7f22:e337:709a],ansible_apparmor: {status: disabled},ansible_architecture: x86_64,ansible_bios_date: 11/12/2020,ansible_bios_version: 6.00,ansible_cmdline: {BOOT_IMAGE: /vmlinuz-3.10.0-1160.el7.x86_64,LANG: zh_CN.UTF-8,quiet: true,rd.lvm.lv: centos/swap,rhgb: true,ro: true,root: /dev/mapper/centos-root},ansible_date_time: {date: 2023-07-27,day: 27,epoch: 1690458049,hour: 19,iso8601: 2023-07-27T11:40:49Z,iso8601_basic: 20230727T194049404100,iso8601_basic_short: 20230727T194049,iso8601_micro: 2023-07-27T11:40:49.404100Z,minute: 40,month: 07,second: 49,time: 19:40:49,tz: CST,tz_offset: 0800,weekday: 星期四,weekday_number: 4,weeknumber: 30,year: 2023},ansible_default_ipv4: {address: 192.168.110.90,alias: ens32,broadcast: 192.168.110.255,gateway: 192.168.110.2,interface: ens32,macaddress: 00:0c:29:34:c3:f1,mtu: 1500,netmask: 255.255.255.0,network: 192.168.110.0,type: ether},ansible_default_ipv6: {},ansible_device_links: {ids: {dm-0: [dm-name-centos-root,dm-uuid-LVM-hJTgeZV0N9q7nfGK5E9QDe1ew7OgUq1G0RnC6vjsObSPV2CKdBd2Dl6svlTDCPio],dm-1: [dm-name-centos-swap,dm-uuid-LVM-hJTgeZV0N9q7nfGK5E9QDe1ew7OgUq1GYOKsNtYiiM4F5QX5efYDdzOAwaSEsdzP],sda2: [lvm-pv-uuid-ATgT9o-q7Ts-R0Ib-4Zsz-gFfh-gwuY-6mlQQt],sr0: [ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001]},labels: {sr0: [CentOS\\x207\\x20x86_64]},masters: {sda2: [dm-0,dm-1]},uuids: {dm-0: [512e053e-94d9-400f-b4a5-990703560011],dm-1: [f1d08392-df6a-4310-a002-b48ca037974c],sda1: [6266bc55-79d5-402f-91a7-c28ebc8d36cb],sr0: [2020-11-04-11-36-43-00]}},ansible_devices: {dm-0: {holders: [],host: ,links: {ids: [dm-name-centos-root,dm-uuid-LVM-hJTgeZV0N9q7nfGK5E9QDe1ew7OgUq1G0RnC6vjsObSPV2CKdBd2Dl6svlTDCPio],labels: [],masters: [],uuids: [512e053e-94d9-400f-b4a5-990703560011]},model: null,partitions: {},removable: 0,rotational: 1,sas_address: null,sas_device_handle: null,scheduler_mode: ,sectors: 73646080,sectorsize: 512,size: 35.12 GB,support_discard: 0,vendor: null,virtual: 1},dm-1: {holders: [],host: ,links: {ids: [dm-name-centos-swap,dm-uuid-LVM-hJTgeZV0N9q7nfGK5E9QDe1ew7OgUq1GYOKsNtYiiM4F5QX5efYDdzOAwaSEsdzP],labels: [],masters: [],uuids: [f1d08392-df6a-4310-a002-b48ca037974c]},model: null,partitions: {},removable: 0,rotational: 1,sas_address: null,sas_device_handle: null,scheduler_mode: ,sectors: 8126464,sectorsize: 512,size: 3.88 GB,support_discard: 0,vendor: null,virtual: 1},sda: {holders: [],host: SCSI storage controller: Broadcom / LSI 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01),links: {ids: [],labels: [],masters: [],uuids: []},model: VMware Virtual S,partitions: {sda1: {holders: [],links: {ids: [],labels: [],masters: [],uuids: [6266bc55-79d5-402f-91a7-c28ebc8d36cb]},sectors: 2097152,sectorsize: 512,size: 1.00 GB,start: 2048,uuid: 6266bc55-79d5-402f-91a7-c28ebc8d36cb},sda2: {holders: [centos-root,centos-swap],links: {ids: [lvm-pv-uuid-ATgT9o-q7Ts-R0Ib-4Zsz-gFfh-gwuY-6mlQQt],labels: [],masters: [dm-0,dm-1],uuids: []},sectors: 81786880,sectorsize: 512,size: 39.00 GB,start: 2099200,uuid: null}},removable: 0,rotational: 1,sas_address: null,sas_device_handle: null,scheduler_mode: deadline,sectors: 83886080,sectorsize: 512,size: 40.00 GB,support_discard: 0,vendor: VMware,,virtual: 1},sr0: {holders: [],host: IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01),links: {ids: [ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001],labels: [CentOS\\x207\\x20x86_64],masters: [],uuids: [2020-11-04-11-36-43-00]},model: VMware IDE CDR10,partitions: {},removable: 1,rotational: 1,sas_address: null,sas_device_handle: null,scheduler_mode: deadline,sectors: 9203712,sectorsize: 2048,size: 4.39 GB,support_discard: 0,vendor: NECVMWar,virtual: 1}},ansible_distribution: CentOS,ansible_distribution_file_parsed: true,ansible_distribution_file_path: /etc/redhat-release,ansible_distribution_file_variety: RedHat,ansible_distribution_major_version: 7,ansible_distribution_release: Core,ansible_distribution_version: 7.9,ansible_dns: {nameservers: [192.168.110.2]},ansible_domain: localdomain,ansible_effective_group_id: 0,ansible_effective_user_id: 0,ansible_ens32: {active: true,device: ens32,features: {busy_poll: off [fixed],fcoe_mtu: off [fixed],generic_receive_offload: on,generic_segmentation_offload: on,highdma: off [fixed],hw_tc_offload: off [fixed],l2_fwd_offload: off [fixed],large_receive_offload: off [fixed],loopback: off [fixed],netns_local: off [fixed],ntuple_filters: off [fixed],receive_hashing: off [fixed],rx_all: off,rx_checksumming: off,rx_fcs: off,rx_gro_hw: off [fixed],rx_udp_tunnel_port_offload: off [fixed],rx_vlan_filter: on [fixed],rx_vlan_offload: on,rx_vlan_stag_filter: off [fixed],rx_vlan_stag_hw_parse: off [fixed],scatter_gather: on,tcp_segmentation_offload: on,tx_checksum_fcoe_crc: off [fixed],tx_checksum_ip_generic: on,tx_checksum_ipv4: off [fixed],tx_checksum_ipv6: off [fixed],tx_checksum_sctp: off [fixed],tx_checksumming: on,tx_fcoe_segmentation: off [fixed],tx_gre_csum_segmentation: off [fixed],tx_gre_segmentation: off [fixed],tx_gso_partial: off [fixed],tx_gso_robust: off [fixed],tx_ipip_segmentation: off [fixed],tx_lockless: off [fixed],tx_nocache_copy: off,tx_scatter_gather: on,tx_scatter_gather_fraglist: off [fixed],tx_sctp_segmentation: off [fixed],tx_sit_segmentation: off [fixed],tx_tcp6_segmentation: off [fixed],tx_tcp_ecn_segmentation: off [fixed],tx_tcp_mangleid_segmentation: off,tx_tcp_segmentation: on,tx_udp_tnl_csum_segmentation: off [fixed],tx_udp_tnl_segmentation: off [fixed],tx_vlan_offload: on [fixed],tx_vlan_stag_hw_insert: off [fixed],udp_fragmentation_offload: off [fixed],vlan_challenged: off [fixed]},hw_timestamp_filters: [],ipv4: {address: 192.168.110.90,broadcast: 192.168.110.255,netmask: 255.255.255.0,network: 192.168.110.0},ipv6: [{address: fe80::992:7f22:e337:709a,prefix: 64,scope: link}],macaddress: 00:0c:29:34:c3:f1,module: e1000,mtu: 1500,pciid: 0000:02:00.0,promisc: false,speed: 1000,timestamping: [tx_software,rx_software,software],type: ether},ansible_env: {HOME: /root,LANG: C,LC_ALL: C,LC_NUMERIC: C,LESSOPEN: ||/usr/bin/lesspipe.sh %s,LOGNAME: root,LS_COLORS: rs0:di01;34:ln01;36:mh00:pi40;33:so01;35:do01;35:bd40;33;01:cd40;33;01:or40;31;01:mi01;05;37;41:su37;41:sg30;43:ca30;41:tw30;42:ow34;42:st37;44:ex01;32:*.tar01;31:*.tgz01;31:*.arc01;31:*.arj01;31:*.taz01;31:*.lha01;31:*.lz401;31:*.lzh01;31:*.lzma01;31:*.tlz01;31:*.txz01;31:*.tzo01;31:*.t7z01;31:*.zip01;31:*.z01;31:*.Z01;31:*.dz01;31:*.gz01;31:*.lrz01;31:*.lz01;31:*.lzo01;31:*.xz01;31:*.bz201;31:*.bz01;31:*.tbz01;31:*.tbz201;31:*.tz01;31:*.deb01;31:*.rpm01;31:*.jar01;31:*.war01;31:*.ear01;31:*.sar01;31:*.rar01;31:*.alz01;31:*.ace01;31:*.zoo01;31:*.cpio01;31:*.7z01;31:*.rz01;31:*.cab01;31:*.jpg01;35:*.jpeg01;35:*.gif01;35:*.bmp01;35:*.pbm01;35:*.pgm01;35:*.ppm01;35:*.tga01;35:*.xbm01;35:*.xpm01;35:*.tif01;35:*.tiff01;35:*.png01;35:*.svg01;35:*.svgz01;35:*.mng01;35:*.pcx01;35:*.mov01;35:*.mpg01;35:*.mpeg01;35:*.m2v01;35:*.mkv01;35:*.webm01;35:*.ogm01;35:*.mp401;35:*.m4v01;35:*.mp4v01;35:*.vob01;35:*.qt01;35:*.nuv01;35:*.wmv01;35:*.asf01;35:*.rm01;35:*.rmvb01;35:*.flc01;35:*.avi01;35:*.fli01;35:*.flv01;35:*.gl01;35:*.dl01;35:*.xcf01;35:*.xwd01;35:*.yuv01;35:*.cgm01;35:*.emf01;35:*.axv01;35:*.anx01;35:*.ogv01;35:*.ogx01;35:*.aac01;36:*.au01;36:*.flac01;36:*.mid01;36:*.midi01;36:*.mka01;36:*.mp301;36:*.mpc01;36:*.ogg01;36:*.ra01;36:*.wav01;36:*.axa01;36:*.oga01;36:*.spx01;36:*.xspf01;36:,MAIL: /var/mail/root,PATH: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin,PWD: /root,SELINUX_LEVEL_REQUESTED: ,SELINUX_ROLE_REQUESTED: ,SELINUX_USE_CURRENT_RANGE: ,SHELL: /bin/bash,SHLVL: 2,SSH_CLIENT: 192.168.110.100 34118 22,SSH_CONNECTION: 192.168.110.100 34118 192.168.110.90 22,SSH_TTY: /dev/pts/1,TERM: xterm,USER: root,XDG_DATA_DIRS: /root/.local/share/flatpak/exports/share:/var/lib/flatpak/exports/share:/usr/local/share:/usr/share,XDG_RUNTIME_DIR: /run/user/0,XDG_SESSION_ID: 32,_: /usr/bin/python},ansible_fibre_channel_wwn: [],ansible_fips: false,ansible_form_factor: Other,ansible_fqdn: localhost.localdomain,ansible_hostname: localhost,ansible_hostnqn: ,ansible_interfaces: [lo,ens32,virbr0-nic,virbr0],ansible_is_chroot: false,ansible_iscsi_iqn: iqn.1994-05.com.redhat:d61bd50d66d,ansible_kernel: 3.10.0-1160.el7.x86_64,ansible_kernel_version: #1 SMP Mon Oct 19 16:18:59 UTC 2020,ansible_lo: {active: true,device: lo,features: {busy_poll: off [fixed],fcoe_mtu: off [fixed],generic_receive_offload: on,generic_segmentation_offload: on,highdma: on [fixed],hw_tc_offload: off [fixed],l2_fwd_offload: off [fixed],large_receive_offload: off [fixed],loopback: on [fixed],netns_local: on [fixed],ntuple_filters: off [fixed],receive_hashing: off [fixed],rx_all: off [fixed],rx_checksumming: on [fixed],rx_fcs: off [fixed],rx_gro_hw: off [fixed],rx_udp_tunnel_port_offload: off [fixed],rx_vlan_filter: off [fixed],rx_vlan_offload: off [fixed],rx_vlan_stag_filter: off [fixed],rx_vlan_stag_hw_parse: off [fixed],scatter_gather: on,tcp_segmentation_offload: on,tx_checksum_fcoe_crc: off [fixed],tx_checksum_ip_generic: on [fixed],tx_checksum_ipv4: off [fixed],tx_checksum_ipv6: off [fixed],tx_checksum_sctp: on [fixed],tx_checksumming: on,tx_fcoe_segmentation: off [fixed],tx_gre_csum_segmentation: off [fixed],tx_gre_segmentation: off [fixed],tx_gso_partial: off [fixed],tx_gso_robust: off [fixed],tx_ipip_segmentation: off [fixed],tx_lockless: on [fixed],tx_nocache_copy: off [fixed],tx_scatter_gather: on [fixed],tx_scatter_gather_fraglist: on [fixed],tx_sctp_segmentation: on,tx_sit_segmentation: off [fixed],tx_tcp6_segmentation: on,tx_tcp_ecn_segmentation: on,tx_tcp_mangleid_segmentation: on,tx_tcp_segmentation: on,tx_udp_tnl_csum_segmentation: off [fixed],tx_udp_tnl_segmentation: off [fixed],tx_vlan_offload: off [fixed],tx_vlan_stag_hw_insert: off [fixed],udp_fragmentation_offload: on,vlan_challenged: on [fixed]},hw_timestamp_filters: [],ipv4: {address: 127.0.0.1,broadcast: ,netmask: 255.0.0.0,network: 127.0.0.0},ipv6: [{address: ::1,prefix: 128,scope: host}],mtu: 65536,promisc: false,timestamping: [rx_software,software],type: loopback},ansible_local: {},ansible_lsb: {},ansible_lvm: {lvs: {root: {size_g: 35.12,vg: centos},swap: {size_g: 3.88,vg: centos}},pvs: {/dev/sda2: {free_g: 0.00,size_g: 39.00,vg: centos}},vgs: {centos: {free_g: 0.00,num_lvs: 2,num_pvs: 1,size_g: 39.00}}},ansible_machine: x86_64,ansible_machine_id: 56c56608bff34ef8a0c395066eb191f4,ansible_memfree_mb: 2770,ansible_memory_mb: {nocache: {free: 3306,used: 625},real: {free: 2770,total: 3931,used: 1161},swap: {cached: 0,free: 3967,total: 3967,used: 0}},ansible_memtotal_mb: 3931,ansible_mounts: [{block_available: 215704,block_size: 4096,block_total: 259584,block_used: 43880,device: /dev/sda1,fstype: xfs,inode_available: 523948,inode_total: 524288,inode_used: 340,mount: /boot,options: rw,seclabel,relatime,attr2,inode64,noquota,size_available: 883523584,size_total: 1063256064,uuid: 6266bc55-79d5-402f-91a7-c28ebc8d36cb},{block_available: 1587537,block_size: 4096,block_total: 9201265,block_used: 7613728,device: /dev/mapper/centos-root,fstype: xfs,inode_available: 12700455,inode_total: 13101192,inode_used: 400737,mount: /,options: rw,seclabel,relatime,attr2,inode64,noquota,size_available: 6502551552,size_total: 37688381440,uuid: 512e053e-94d9-400f-b4a5-990703560011}],ansible_nodename: localhost.localdomain,ansible_os_family: RedHat,ansible_pkg_mgr: yum,ansible_proc_cmdline: {BOOT_IMAGE: /vmlinuz-3.10.0-1160.el7.x86_64,LANG: zh_CN.UTF-8,quiet: true,rd.lvm.lv: [centos/root,centos/swap],rhgb: true,ro: true,root: /dev/mapper/centos-root},ansible_processor: [0,GenuineIntel,11th Gen Intel(R) Core(TM) i5-1135G7 2.40GHz,1,GenuineIntel,11th Gen Intel(R) Core(TM) i5-1135G7 2.40GHz],ansible_processor_cores: 1,ansible_processor_count: 2,ansible_processor_threads_per_core: 1,ansible_processor_vcpus: 2,ansible_product_name: VMware Virtual Platform,ansible_product_serial: VMware-56 4d 51 84 c4 5b 84 cc-2c 9e 67 5c 89 34 c3 f1,ansible_product_uuid: 84514D56-5BC4-CC84-2C9E-675C8934C3F1,ansible_product_version: None,ansible_python: {executable: /usr/bin/python,has_sslcontext: true,type: CPython,version: {major: 2,micro: 5,minor: 7,releaselevel: final,serial: 0},version_info: [2,7,5,final,0]},ansible_python_version: 2.7.5,ansible_real_group_id: 0,ansible_real_user_id: 0,ansible_selinux: {config_mode: enforcing,mode: enforcing,policyvers: 31,status: enabled,type: targeted},ansible_selinux_python_present: true,ansible_service_mgr: systemd,ansible_ssh_host_key_ecdsa_public: AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBNzyuLM4qzFFelYr5QIDKGI80S4WUIHiZEZBKC6e3UwwIc1rCWpYXhaLfcjc3XCRLhYMUCKJLIFZEcHccB3bTTU,ansible_ssh_host_key_ed25519_public: AAAAC3NzaC1lZDI1NTE5AAAAIEcN4TTRNEO2wevqbqWEuL3U23N9V7GBmiNm7m94bcU,ansible_ssh_host_key_rsa_public: AAAAB3NzaC1yc2EAAAADAQABAAABAQCcM56Mx4Mh08z3da0jycoZtgEd/kOls9niGAK4iLJrAFCtZbN0naBL0yn4V2KtpTh/acDdwvVVypMFHsg3M4JXpr8HBEiqHRhqLRUftT/8jmdaLE5pTttr7djuI2HTtmh40BwYUiWZTRT8j9huvl3p0BraIzUhkQDvwkkWyLlz8j6rPJnjLvWFyDhNRwpop0StL3OBoMfvFEQioU91YrgImwuizYcrnEvNdBxHLqNu13cgCiIq53UoUDFcTAg1lu51bg8MS1qsUT7bABgijXmOmtqB4NRpX4eKNC55p7CcNyEsklVxow1M6YG80ox4I18hDJlIeti042mJsJv,ansible_swapfree_mb: 3967,ansible_swaptotal_mb: 3967,ansible_system: Linux,ansible_system_capabilities: [cap_chown,cap_dac_override,cap_dac_read_search,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_linux_immutable,cap_net_bind_service,cap_net_broadcast,cap_net_admin,cap_net_raw,cap_ipc_lock,cap_ipc_owner,cap_sys_module,cap_sys_rawio,cap_sys_chroot,cap_sys_ptrace,cap_sys_pacct,cap_sys_admin,cap_sys_boot,cap_sys_nice,cap_sys_resource,cap_sys_time,cap_sys_tty_config,cap_mknod,cap_lease,cap_audit_write,cap_audit_control,cap_setfcap,cap_mac_override,cap_mac_admin,cap_syslog,35,36ep],ansible_system_capabilities_enforced: True,ansible_system_vendor: VMware, Inc.,ansible_uptime_seconds: 6065,ansible_user_dir: /root,ansible_user_gecos: root,ansible_user_gid: 0,ansible_user_id: root,ansible_user_shell: /bin/bash,ansible_user_uid: 0,ansible_userspace_architecture: x86_64,ansible_userspace_bits: 64,ansible_virbr0: {active: false,device: virbr0,features: {busy_poll: off [fixed],fcoe_mtu: off [fixed],generic_receive_offload: on,generic_segmentation_offload: on,highdma: off [requested on],hw_tc_offload: off [fixed],l2_fwd_offload: off [fixed],large_receive_offload: off [fixed],loopback: off [fixed],netns_local: on [fixed],ntuple_filters: off [fixed],receive_hashing: off [fixed],rx_all: off [fixed],rx_checksumming: off [fixed],rx_fcs: off [fixed],rx_gro_hw: off [fixed],rx_udp_tunnel_port_offload: off [fixed],rx_vlan_filter: off [fixed],rx_vlan_offload: off [fixed],rx_vlan_stag_filter: off [fixed],rx_vlan_stag_hw_parse: off [fixed],scatter_gather: on,tcp_segmentation_offload: on,tx_checksum_fcoe_crc: off [fixed],tx_checksum_ip_generic: on,tx_checksum_ipv4: off [fixed],tx_checksum_ipv6: off [fixed],tx_checksum_sctp: off [fixed],tx_checksumming: on,tx_fcoe_segmentation: off [requested on],tx_gre_csum_segmentation: on,tx_gre_segmentation: on,tx_gso_partial: on,tx_gso_robust: off [requested on],tx_ipip_segmentation: on,tx_lockless: on [fixed],tx_nocache_copy: off,tx_scatter_gather: on,tx_scatter_gather_fraglist: on,tx_sctp_segmentation: off [requested on],tx_sit_segmentation: on,tx_tcp6_segmentation: on,tx_tcp_ecn_segmentation: on,tx_tcp_mangleid_segmentation: on,tx_tcp_segmentation: on,tx_udp_tnl_csum_segmentation: on,tx_udp_tnl_segmentation: on,tx_vlan_offload: on,tx_vlan_stag_hw_insert: on,udp_fragmentation_offload: off [requested on],vlan_challenged: off [fixed]},hw_timestamp_filters: [],id: 8000.525400fc1bcc,interfaces: [virbr0-nic],ipv4: {address: 192.168.122.1,broadcast: 192.168.122.255,netmask: 255.255.255.0,network: 192.168.122.0},macaddress: 52:54:00:fc:1b:cc,mtu: 1500,promisc: false,stp: true,timestamping: [rx_software,software],type: bridge},ansible_virbr0_nic: {active: false,device: virbr0-nic,features: {busy_poll: off [fixed],fcoe_mtu: off [fixed],generic_receive_offload: on,generic_segmentation_offload: on,highdma: off [fixed],hw_tc_offload: off [fixed],l2_fwd_offload: off [fixed],large_receive_offload: off [fixed],loopback: off [fixed],netns_local: off [fixed],ntuple_filters: off [fixed],receive_hashing: off [fixed],rx_all: off [fixed],rx_checksumming: off [fixed],rx_fcs: off [fixed],rx_gro_hw: off [fixed],rx_udp_tunnel_port_offload: off [fixed],rx_vlan_filter: off [fixed],rx_vlan_offload: off [fixed],rx_vlan_stag_filter: off [fixed],rx_vlan_stag_hw_parse: off [fixed],scatter_gather: on,tcp_segmentation_offload: off,tx_checksum_fcoe_crc: off [fixed],tx_checksum_ip_generic: off [requested on],tx_checksum_ipv4: off [fixed],tx_checksum_ipv6: off [fixed],tx_checksum_sctp: off [fixed],tx_checksumming: off,tx_fcoe_segmentation: off [fixed],tx_gre_csum_segmentation: off [fixed],tx_gre_segmentation: off [fixed],tx_gso_partial: off [fixed],tx_gso_robust: off [fixed],tx_ipip_segmentation: off [fixed],tx_lockless: on [fixed],tx_nocache_copy: off,tx_scatter_gather: on,tx_scatter_gather_fraglist: on,tx_sctp_segmentation: off [fixed],tx_sit_segmentation: off [fixed],tx_tcp6_segmentation: off [requested on],tx_tcp_ecn_segmentation: off [requested on],tx_tcp_mangleid_segmentation: off,tx_tcp_segmentation: off [requested on],tx_udp_tnl_csum_segmentation: off [fixed],tx_udp_tnl_segmentation: off [fixed],tx_vlan_offload: on,tx_vlan_stag_hw_insert: on,udp_fragmentation_offload: off [requested on],vlan_challenged: off [fixed]},hw_timestamp_filters: [],macaddress: 52:54:00:fc:1b:cc,mtu: 1500,promisc: true,timestamping: [rx_software,software],type: ether},ansible_virtualization_role: guest,ansible_virtualization_type: VMware,discovered_interpreter_python: /usr/bin/python,gather_subset: [all],module_setup: true},changed: false
}ansible dbservers -m setup -a filter*ipv4 #使用filter可以筛选指定的facts信息192.168.110.70 | SUCCESS {ansible_facts: {ansible_default_ipv4: {address: 192.168.110.70,alias: ens32,broadcast: 192.168.110.255,gateway: 192.168.110.2,interface: ens32,macaddress: 00:0c:29:e4:96:c1,mtu: 1500,netmask: 255.255.255.0,network: 192.168.110.0,type: ether},discovered_interpreter_python: /usr/bin/python},changed: false
}inventory 主机清单
Inventory支持对主机进行分组每个组内可以定义多个主机每个主机都可以定义在任何一个或多个主机组内。
如果是名称类似的主机可以使用列表的方式标识各个主机。
vim /etc/ansible/hosts
[webservers]
192.168.80.11:2222 #冒号后定义远程连接端口默认是 ssh 的 22 端口
192.168.80.1[2:5][dbservers]
db-[a:f].example.org #支持匹配 a~f
随便输出一个命令就会显示为下面这样连接一个地址之后就会连接地址池中其他地址当然其他地址就会报错
192.168.110.70 | SUCCESS {ansible_facts: {ansible_default_ipv4: {address: 192.168.110.70,alias: ens32,broadcast: 192.168.110.255,gateway: 192.168.110.2,interface: ens32,macaddress: 00:0c:29:e4:96:c1,mtu: 1500,netmask: 255.255.255.0,network: 192.168.110.0,type: ether},discovered_interpreter_python: /usr/bin/python},changed: false
}
192.168.110.71 | UNREACHABLE! {changed: false,msg: Failed to connect to the host via ssh: ssh: connect to host 192.168.110.71 port 22: No route to host,unreachable: true
}
192.168.110.74 | UNREACHABLE! {changed: false,msg: Failed to connect to the host via ssh: ssh: connect to host 192.168.110.74 port 22: No route to host,unreachable: true
}
192.168.110.72 | UNREACHABLE! {changed: false,msg: Failed to connect to the host via ssh: ssh: connect to host 192.168.110.72 port 22: No route to host,unreachable: true
}
192.168.110.73 | UNREACHABLE! {changed: false,msg: Failed to connect to the host via ssh: ssh: connect to host 192.168.110.73 port 22: No route to host,unreachable: true
}
192.168.110.75 | UNREACHABLE! {changed: false,msg: Failed to connect to the host via ssh: ssh: connect to host 192.168.110.75 port 22: No route to host,unreachable: true
}而连接192.168.110.90时就会因为端口不对而无法连接
192.168.110.90 | UNREACHABLE! {changed: false,msg: Failed to connect to the host via ssh: ssh: connect to host 192.168.110.90 port 2222: No route to host,unreachable: true
}inventory 中的变量
Inventory变量名含义ansible_hostansible连接节点时的IP地址ansible_port 连接对方的端口号ssh连接时默认为22ansible_user 连接对方主机时使用的用户名。不指定时将使用执行ansible或ansible-playbook命令的用户ansible_password 连接时的用户的ssh密码仅在未使用密钥对验证的情况下有效ansible_ssh_private_key_file指定密钥认证ssh连接时的私钥文件ansible_ssh_common_args提供给ssh、sftp、scp命令的额外参数ansible_become_method指定提升权限的方式例如可使用sudo/su/runas等方式ansible_become_user 提升为哪个用户的权限默认提升为rootansible_become_password 提升为指定用户权限时的密码
1.主机变量
vim /etc/ansible/hosts[webservers]
192.168.110.90 ansible_port22 ansible_userroot ansible_passwordzxr123
随便输出一个命令然后把192.168.110.90主机的用户切换到zxr并且把登录密码也输入正确
192.168.110.90 | SUCCESS {ansible_facts: {ansible_default_ipv4: {address: 192.168.110.90,alias: ens32,broadcast: 192.168.110.255,gateway: 192.168.110.2,interface: ens32,macaddress: 00:0c:29:34:c3:f1,mtu: 1500,netmask: 255.255.255.0,network: 192.168.110.0,type: ether},discovered_interpreter_python: /usr/bin/python},changed: false
}2.组变量
vim /etc/ansible/hosts
[webservers:vars] #表示为 webservers 组内所有主机定义变量
ansible_userroot
ansible_passwordabc1234
[webservers]
192.168.110.90[webservers:vars]
ansible_userzxr
ansible_passwordzxr123
## alpha.example.org
## beta.example.org
## 192.168.1.100
## 192.168.1.110# If you have multiple hosts following a pattern you can specify192.168.110.90 | SUCCESS {ansible_facts: {ansible_default_ipv4: {address: 192.168.110.90,alias: ens32,broadcast: 192.168.110.255,gateway: 192.168.110.2,interface: ens32,macaddress: 00:0c:29:34:c3:f1,mtu: 1500,netmask: 255.255.255.0,network: 192.168.110.0,type: ether},discovered_interpreter_python: /usr/bin/python},changed: false
}vim /etc/ansible/hosts
[all:vars] #表示为所有组内的所有主机定义变量
ansible_port22
3.组嵌套
[nginx]
192.168.80.20
192.168.80.21
192.168.80.22
[apache]
192.168.80.3[0:3][webs:children] #表示为 webs 主机组中包含了 nginx 组和 apache 组内的所有主机
nginx
apache
[webservers]
192.168.110.90## alpha.example.org
## beta.example.org
## 192.168.1.100
## 192.168.1.110# If you have multiple hosts following a pattern you can specify
# them like this:## www[001:006].example.com# Ex 3: A collection of database servers in the dbservers group[dbservers]
192.168.110.70
##
## db01.intranet.mydomain.net
## db02.intranet.mydomain.net
## 10.25.1.56
## 10.25.1.57
[webs:children]
webservers
dbservers
ansible webs:children -m setup -a filter*ipv4[WARNING]: Could not match supplied host pattern, ignoring: children
192.168.110.90 | SUCCESS {ansible_facts: {ansible_default_ipv4: {address: 192.168.110.90,alias: ens32,broadcast: 192.168.110.255,gateway: 192.168.110.2,interface: ens32,macaddress: 00:0c:29:34:c3:f1,mtu: 1500,netmask: 255.255.255.0,network: 192.168.110.0,type: ether},discovered_interpreter_python: /usr/bin/python},changed: false
}
192.168.110.70 | SUCCESS {ansible_facts: {ansible_default_ipv4: {address: 192.168.110.70,alias: ens32,broadcast: 192.168.110.255,gateway: 192.168.110.2,interface: ens32,macaddress: 00:0c:29:e4:96:c1,mtu: 1500,netmask: 255.255.255.0,network: 192.168.110.0,type: ether},discovered_interpreter_python: /usr/bin/python},changed: false
}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/929439.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!