Ansible 自动化运维工具、常用模块
一、Ansible 简介
1、Ansible 概述
Ansible 是一个基于 Python 开发的配置管理和应用部署工具,现在也在自动化管理领域大放异彩。它融合了众多老牌运维工具的优点,Pubbet 和 Saltstack 能实现的功能,Ansible 基本上都可以实现。
2、Ansible 作用
Ansible 能批量配置、部署、管理上千台主机。比如以前需要切换到每个主机上执行的一或多个操作,使用Ansible只需在固定的一台Ansible 控制节点上去完成所有主机的操作。
3、Ansible 的工作模块
Ansible是基于模块工作的,它只是提供了一种运行框架,它本身没有完成任务的能力,真正执行操作的是Ansible的模块, 比如copy模块用于拷贝文件到远程主机上,service模块用于管理服务的启动、停止、重启等。
4、常用的自动化运维工具及区别
工具 | 语言 | 架构 | 协议 |
Puppet | Ruby | C/S | HTTP |
Chef | Ruby | C/S | HTTP |
Ansible | Python | 无Client | SSH |
Saltstack | Python | C/S(可无Client) | SSH/ZMQ/RAET |
5、Ansible的主要特点
Ansible 其中一个比较鲜明的特性是Agentless,即无Agent的存在,它就像普通命令一样,并非C/S软件,也只需在某个作为控制节点的主机上安装一次Ansible即可,通常它基于ssh连接来控制远程主机,远程主机上不需要安装Ansible或其它额外的服务。
使用者在使用时,在服务器终端输入命令或者playbooks,会通过预定好的规则将playbook拆解为play,再组织成ansible可以识别的任务,调用模块和插件,根据主机清单通过SSH将临时文件发给远程的客户端执行并返回结果,执行结束后自动删除。
Ansible 的另一个比较鲜明的特性是它的绝大多数模块都具备幂等性(idempotence)。所谓幂等性,指的是多次操作或多次执行对系统资源的影响是一致的。比如执行
systemctl stop xxx 命令来停止服务,当发现要停止的目标服务已经处于停止状态,
它什么也不会做,所以多次停止的结果仍然是停止,不会改变结果,它是幂等的,而 systemctl restart xxx 是非幂等的。
Ansible的很多模块在执行时都会先判断目标节点是否要执行任务,所以,可以放心大胆地让Ansible去执行任务,重复执行某个任务绝大多数时候不会产生任何副作用。
6、Ansible的工作机制
使用者在使用时,在服务器终端输入命令或者playbooks,会通过预定好的规则将playbook拆解为play,再组织成ansible可以识别的任务,调用模块和插件,根据主机清单通过SSH将临时文件发给远程的客户端执行并返回结果,执行结束后自动删除
二、Ansible 部署
--- Ansible环境安装部署 ---
服务器 | IP 地址 | 主机名 |
管理端 | 20.0.0.6 | ansible |
被管理端 | 20.0.0.11 | - |
被管理端 | 20.0.0.12 | - |
1、Ansible 的安装
//管理端安装 epel 扩展源并安装 ansible
yum -y install epel-release
yum -y install ansible
//ansible 目录结构
[root@ansible ~]# yum -y install tree [root@ansible ~]# tree /etc/ansible /etc/ansible ├── ansible.cfg #ansible的配置文件,一般无需修改 ├── hosts #ansible的主机清单,用于存储需要管理的远程主机的相关信息 └── roles #公共角色目录 1 directory, 2 files
//配置主机清单
[root@ansible ~]# cd /etc/ansible/ [root@ansible ansible]# ls ansible.cfg hosts roles [root@ansible ansible]# vim hosts ##配置组名 [webservers] 20.0.0.11 #组里面包含的被管理的主机IP地址或主机名 #主机名需要先修改/etc/hosts文件,更新ip映射 [dbservers] 20.0.0.12
//配置密钥对验证
ssh-keygen -t rsa #一路回车,使用免密登录 sshpass -p '123456' ssh-copy-id root@20.0.0.11 sshpass -P '123456' ssh-copy-id root@20.0.0.12 或 ssh-copy-id root@20.0.0.11 ssh-copy-id root@20.0.0.12
//也可以这样验证,在被管理端 20.0.0.11 验证
三、ansible 命令行模块
命令格式:ansible <组名> -m <模块> -a <参数列表>
ansible-doc -l #列出所有已安装的模块,按 q 退出
fortios_router_community_list Configure community list... azure_rm_devtestlab_info Get Azure DevTest Lab fa... ecs_taskdefinition register a task definiti... avi_alertscriptconfig Module for setup of Aler... tower_receive Receive assets from Ansi... netapp_e_iscsi_target NetApp E-Series manage i... azure_rm_acs Manage an Azure Containe... fortios_log_syslogd2_filter Filters for remote syste... junos_rpc Runs an arbitrary RPC ov... na_elementsw_vlan NetApp Element Software ... pn_ospf CLI command to add/remov... pn_snmp_vacm CLI command to create/mo... cp_mgmt_service_sctp Manages service-sctp obj... onyx_ospf Manage OSPF protocol on ... icx_command Run arbitrary commands o... cs_snapshot_policy Manages volume snapshot ... nxos_install_os Set boot options like bo... cnos_static_route Manage static IP routes ... win_eventlog Manage Windows event log... vmware_category Manage VMware categories vmware_host_feature_info Gathers info about an ES... avi_cluster Module for setup of Clus... na_ontap_user NetApp ONTAP user config... aci_l3out Manage Layer 3 Outside (... memset_server_info Retrieve server informat... gcp_compute_subnetwork_info Gather info for GCP Subn... azure_rm_virtualmachinescalesetextension Manage Azure Virtual Mac... fortios_report_dataset Report dataset configura... avi_api_session Avi API Module avi_networkprofile Module for setup of Netw... :
1、command 模块
//在远程主机执行命令,不支持管道,重定向等shell的特性。
command : 常见的命令都可以使用,但命令的执行不是通过shell来执行的,所以< > | and & z这些操作都不可以,不支持管道,没法批量执行命令
[root@ansible ansible]# ansible-doc -s command - name: Execute commands on targets command: argv: # Passes the command as a list rather than a string. Use `argv' to avoid quoting values that would otherwise be interpreted incorrectly (for example "user name"). Only the string or the list form can be provided, not both. One or the other must be provided. chdir: # Change into this directory before running the command. cmd: # The command to run. creates: # A filename or (since 2.0) glob pattern. If it already exists, this step *won't* be run. free_form: # The command module takes a free form command to run. There is no actual parameter named 'free form'. removes: # A filename or (since 2.0) glob pattern. If it already exists, this step *will* be run. stdin: # Set the stdin of the command directly to the specified value. stdin_add_newline: # If set to `yes', append a newline to stdin data. strip_empty_ends: # Strip empty lines from the end of stdout/stderr in result. warn: # Enable or disable task warnings.
[root@ansible ansible]# ansible 20.0.0.11 -m command -a 'date' #指定 ip 执行 date;-m 20.0.0.11 | CHANGED | rc=0 >> 2021年 11月 04日 星期四 19:01:53 CST [root@ansible ansible]# ansible webservers -m command -a 'date' #指定webserver组执行 date 20.0.0.11 | CHANGED | rc=0 >> 2021年 11月 04日 星期四 19:02:03 CST [root@ansible ansible]# ansible dbservers -m command -a 'date' #指定dbserver组 20.0.0.12 | CHANGED | rc=0 >> 2021年 11月 04日 星期四 19:02:11 CST [root@ansible ansible]# ansible all -m command -a 'date' #all 代表所有 host 主机 20.0.0.12 | CHANGED | rc=0 >> 2021年 11月 04日 星期四 19:02:21 CST 20.0.0.11 | CHANGED | rc=0 >> 2021年 11月 04日 星期四 19:02:21 CST [root@ansible ansible]# ansible all -a 'ls /' #如省略 -m 模块,则默认运行command 模块 20.0.0.11 | CHANGED | rc=0 >> bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var 20.0.0.12 | CHANGED | rc=0 >> bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var
//常用的参数:
chdir:在远程主机上运行命令前提前进入目录
creates:判断指定文件是否存在,如果存在,不执行后面的操作
removes:判断指定文件是否存在,如果存在,执行后面的操作
[root@ansible ansible]# ansible all -m command -a "chdir=/home ls ./" 20.0.0.12 | CHANGED | rc=0 >> allen 20.0.0.11 | CHANGED | rc=0 >> allen
ansible webservers -a "creates=/opt/abc.txt cat /opt/abc.txt" #creates 判断文件是否存在,存在则不执行后面的操作 ansible webservers -a "creates=/opt/123.txt cat /opt/123.txt" ansible webservers -a "removes=/opt/abc.txt cat /opt/abc.txt" #remove 版的文件是否存在,不存在则执行后面的操作 ansible webservers -a "removes=/opt/123.txt cat /opt/123.txt"
2、shell模块
在远程主机执行命令,相当于调用远程主机的 shell 进程,然后在该 shell 下打开有一个子shell运行命令(支持管段符号等功能)
[root@ansible ansible]# ansible-doc -s shell - name: Execute shell commands on targets shell: chdir: # Change into this directory before running the command. cmd: # The command to run followed by optional arguments. creates: # A filename, when it already exists, this step will *not* be run. executable: # Change the shell used to execute the command. This expects an absolute path to the executable. free_form: # The shell module takes a free form command to run, as a string. There is no actual parameter named 'free form'. See the examples on how to use this module. removes: # A filename, when it does not exist, this step will *not* be run. stdin: # Set the stdin of the command directly to the specified value. stdin_add_newline: # Whether to append a newline to stdin data. warn: # Whether to enable task warnings.
//创建用户、更改密码
[root@ansible ansible]# ansible webservers -m shell -a 'useradd test' 20.0.0.11 | CHANGED | rc=0 >> [root@ansible ansible]# ansible webservers -m shell -a 'echo 123456 | passwd --stdin test' 20.0.0.11 | CHANGED | rc=0 >> 更改用户 test 的密码 。 passwd:所有的身份验证令牌已经成功更新。
//查看 IP
[root@ansible ansible]# ansible webservers -m shell -a 'ifconfig ens33 | awk "NR==2 {print \$2}"' 20.0.0.11 | CHANGED | rc=0 >> 20.0.0.11 [root@ansible ansible]# ansible webservers -m shell -a "ifconfig ens33 | awk 'NR==2 {print \$2}'" 20.0.0.11 | CHANGED | rc=0 >> 20.0.0.11 [root@ansible ansible]# ansible webservers -m shell -a 'echo $(ifconfig ens33 | awk "NR==2 {print}") | cut -d " " -f 2' 20.0.0.11 | CHANGED | rc=0 >> 20.0.0.11
3、cron 模块
//在远程主机定义任务计划。其中有两种状态(state):present表示添加(可以省略),absent表示移除。
[root@ansible ansible]# ansible-doc -s cron #按 q 退出 - name: Manage cron.d and crontab entries cron: backup: # If set, create a backup of the crontab before it is modified. The location of the backup is returned in the `backup_file' variable by this module. cron_file: # If specified, uses this file instead of an individual user's crontab. If this is a relative path, it is interpreted with respect to `/etc/cron.d'. If it is absolute, it will typically be `/etc/crontab'. Many linux distros expect (and some require) the filename portion to consist solely of upper- and lower-case letters, digits, underscores, and hyphens. To use the `cron_file' parameter you must specify the `user' as well. day: # Day of the month the job should run ( 1-31, *, */2, etc ) disabled: # If the job should be disabled (commented out) in the crontab. Only has effect if `state=present'. env: # If set, manages a crontab's environment variable. New variables are added on top of crontab. `name' and :
//常用的参数:
minute/hour/day/month/weekday:分/时/日/月/周
job:任务计划要执行的命令
name:任务计划的名称
[root@ansible ansible]# ansible webservers -m cron -a 'minute="*/1" job="/bin/echo helloworld" name="test crontab"'
20.0.0.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"test crontab"
]
}
[root@ansible ansible]# ansible webservers -a 'crontab -l'
20.0.0.11 | CHANGED | rc=0 >>
#Ansible: test crontab
*/1 * * * * /bin/echo helloworld
[root@ansible ansible]# ansible webservers -m cron -a 'name="test crontab" state=absent' #移除计划任务,假如该计划任务没有取名字,name=None即可
20.0.0.11 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": []
}
4、user 模块
//用户管理的模块
[root@ansible ansible]# ansible-doc -s user - name: Manage user accounts user: append: # If `yes', add the user to the groups specified in `groups'. If `no', user will only be added to the groups specified in `groups', removing them from all other groups. Mutually exclusive with `local' authorization: # Sets the authorization of the user. Does nothing when used with other platforms. Can . . .
//常用的参数:
常用参数 | 说明 |
name | 用户名,必选参数 |
state=present/absent | 创建账号或者删除账号,present表示创建,absent表示删除 |
system=yes/no | 是否为系统账号 |
uid | 用户uid |
group | 用户基本组 |
shell | 默认使用的shell |
move_home=yse/no | 如果设置的家目录已经存在,是否将已经存在的家目录进行移动 |
password | 用户的密码,建议使用加密后的字符串 |
comment | 用户的注释信息 |
remove=yes/no | 当state=absent时,是否删除用户的家目录 |
[root@ansible ansible]# ansible dbservers -m user -a 'name="test01"' #创建用户test01
20.0.0.12 | 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
}
[root@ansible ansible]# ansible dbservers -m command -a 'tail /etc/passwd' #查看是否创建成功
20.0.0.12 | CHANGED | rc=0 >>
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:991:986::/run/gnome-initial-setup/:/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
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
allen:x:1000:1000:allen:/home/allen:/bin/bash
test01:x:1001:1001::/home/test01:/bin/bash
[root@ansible ansible]# ansible dbservers -m user -a 'name="test01" state=absent' #删除用户
20.0.0.12 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"force": false,
"name": "test01",
"remove": false,
"state": "absent"
}
5、group 模块
//用户组管理的模块
[root@ansible ~]# ansible-doc -s group - name: Add or remove groups group: gid: # Optional `GID' to set for the group. local: # Forces the use of "local" command alternatives on platforms that implement it. This is useful in environments that use centralized authentication when you want ........
ansible dbservers -m group -a 'name=mysql gid=306 system=yes' #创建mysql组 ansible dbservers -a 'tail /etc/group' ansible dbservers -m user -a 'name=test01 uid=306 system=yes group=mysql' #将test01用户添加到mysql组中 ansible dbservers -a 'tail /etc/passwd' ansible dbservers -a 'id test01'
6、copy
//用于复制指定主机文件到远程主机的
[root@ansible ~]# ansible-doc -s copy - name: Copy files to remote locations copy: attributes: # The attributes the resulting file or directory should have. To get supported flags look at the man page for `chattr' on the target system. This string should contain the attributes in the same order as the one displayed by `lsattr'. The `=' operator is assumed as default, otherwise `+' or `-' operators need to be included in the string. backup: # Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. checksum: # SHA1 checksum of the file being transferred. Used to . . .
常用参数 | 说明 |
dest | 指出复制文件的目标及位置,使用绝对路径,如果是源目录,指目标也要是目录,如果目标文件已经存在会覆盖原有的内容 |
src | 指出源文件的路径,可以使用相对路径或绝对路径,支持直接指定目录,如果源是目录则目标也要是目录 |
mode | 指出复制时,目标文件的权限 |
owner | 指出复制时,目标文件的属主 |
group | 指出复制时,目标文件的属组 |
content | 指出复制到目标主机上的内容,不能与src一起使用 |
//复制管理
[root@ansible ~]# ansible dbservers -m copy -a 'src=/etc/fstab dest=/opt/fstab.bak owner=root mode=640' #复制文件到远程主机 20.0.0.12 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "checksum": "a1b453b16704734098850e661f68b35213b14dca", "dest": "/opt/fstab.bak", "gid": 0, "group": "root", "md5sum": "61bc5e1fc5f703298b696600146e18c9", "mode": "0640", "owner": "root", "secontext": "system_u:object_r:usr_t:s0", "size": 501, "src": "/root/.ansible/tmp/ansible-tmp-1636031991.93-57717-50793898875721/source", "state": "file", "uid": 0 } [root@ansible ~]# ansible dbservers -a 'ls -l /opt' #查看文件是否复制成功 20.0.0.12 | CHANGED | rc=0 >> 总用量 4 drwx--x--x. 4 root root 28 10月 14 17:19 containerd -rw-r-----. 1 root root 501 11月 4 21:20 fstab.bak drwxr-xr-x. 2 root root 6 3月 26 2015 rh [root@ansible ~]# ansible dbservers -a 'cat /opt/fstab.bak' #查看复制后文件内容 20.0.0.12 | CHANGED | rc=0 >> # # /etc/fstab # Created by anaconda on Thu Jul 29 09:12:56 2021 # # 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 # UUID=fa885b78-b27d-4c72-9ac5-4e3780e2b3e2 / xfs defaults 0 0 UUID=61379692-1f1e-4403-b494-b043d5cf8e8d /boot xfs defaults 0 0 UUID=c149563f-dd83-452c-9d1a-b3ec81f13b5d swap swap defaults 0 0
//将helloworld写入/opt/hello.txt文件中
[root@ansible ~]# ansible dbservers -m copy -a 'content="helloworld" dest=/opt/hello.txt' 20.0.0.12 | 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-1636032664.68-57894-112721691695623/source", "state": "file", "uid": 0 } [root@ansible ~]# ansible dbservers -a 'cat /opt/hello.txt' 20.0.0.12 | CHANGED | rc=0 >> helloworld
7、file 模块
//设置文件属性
[root@ansible ~]# ansible-doc -s file - name: Manage files and file properties file: access_time: # This parameter indicates the time the file's access time should be set to. Should be `preserve' when no modification is required, `YYYYMMDDHHMM.SS' when using default time format, or `now'. Default is `None' meaning that `preserve' is the default for `state=[file ,directory,link,hard]' and `now' is default for `state=touch'. access_time_format: # When used with `access_time', indicates the time format that must be used. Based on . . .
//文件属性管理
[root@ansible ~]# ansible dbservers -m file -a 'owner=test01 group=mysql mode=644 path=/opt/fstab.bak' #修改文件的属主属组权限等 20.0.0.12 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "gid": 3306, "group": "mysql", "mode": "0644", "owner": "test01", "path": "/opt/fstab.bak", "secontext": "system_u:object_r:usr_t:s0", "size": 501, "state": "file", "uid": 306 }
//设置/opt/fstab.link为/opt/fstab.bak的链接文件
[root@ansible ~]# ansible dbservers -m file -a 'owner=test01 group=mysql mode=644 path=/opt/fstab.bak' 20.0.0.12 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "gid": 3306, "group": "mysql", "mode": "0644", "owner": "test01", "path": "/opt/fstab.bak", "secontext": "system_u:object_r:usr_t:s0", "size": 501, "state": "file", "uid": 306 }
//设置/opt/fstab.link为/opt/fstab.bak的链接文件
[root@ansible ~]# ansible dbservers -m file -a 'path=/opt/fstab.link src=/opt/fstab.bak state=link' 20.0.0.12 | 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 }
//创建一个文件
[root@ansible ~]# ansible dbservers -m file -a "path=/opt/abc.txt state=touch" 20.0.0.12 | 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 }
//删除一个文件
[root@ansible ~]# ansible dbservers -m file -a "path=/opt/abc.txt state=absent" 20.0.0.12 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "path": "/opt/abc.txt", "state": "absent" }
8、hostname 模块
//用于管理远程主机上的主机名
[root@ansible ~]# ansible dbservers -m hostname -a "name=mysql01" 20.0.0.12 | CHANGED => { "ansible_facts": { "ansible_domain": "", "ansible_fqdn": "mysql01", "ansible_hostname": "mysql01", "ansible_nodename": "mysql01", "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "name": "mysql01" }
9、ping 模块
//检测远程主机的连通性
[root@ansible ~]# ansible all -m ping 20.0.0.12 | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "ping": "pong" } 20.0.0.11 | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "ping": "pong" }
10、yum 模块
//在远程主机上安装与卸载软件包
[root@ansible ~]# ansible-doc -s yum - name: Manages packages with the `yum' package manager yum: allow_downgrade: # Specify if the named package and version is allowed to downgrade a maybe already installed higher version of that package. Note that setting allow_downgrade=True can make this module behave in a non-idempotent way. The task could end up with a set of packages that does not match the complete list of specified packages to install (because dependencies between the . . .
#安装服务
[root@ansible ~]# ansible webservers -m yum -a 'name=httpd' 20.0.0.11 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, ...... ...... d:\n httpd.x86_64 0:2.4.6-97.el7.centos.1 \n\nDependency Installed:\n httpd-tools.x86_64 0:2.4.6-97.el7.centos.1 mailcap.noarch 0:2.1.41-2.el7 \n\nComplete!\n" ] }
#卸载服务
[root@ansible ~]# ansible webservers -m yum -a 'name=httpd state=absent' 20.0.0.11 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "changes": { "removed": [ "httpd" ] }, "msg": "", "rc": 0, "results": [ "已加载插件:fastestmirror, langpacks\n正在解决依赖关系\n--> 正在检查事务\n---> 软件包 httpd.x86_64.0.2.4.6-97.el7.centos.1 将被 删除\n--> 解决依赖关系完成\n\n依赖关系解决\n\n================================================================================\n Package 架构 版本 源 大小\n================================================================================\n正在删除:\n httpd x86_64 2.4.6-97.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-97.el7.centos.1.x86_64 1/1 \n 验证中 : httpd-2.4.6-97.el7.centos.1.x86_64 1/1 \n\n删除:\n httpd.x86_64 0:2.4.6-97.el7.centos.1 \n\n完毕!\n" ] }
11、service/systemd 模块
//用于管理远程主机上的管理服务的运行状态
[root@ansible ~]# ansible-doc -s service - name: Manage services service: arguments: # Additional arguments provided on the command line. enabled: # Whether the service should start on boot. *At least one of state and enabled are required.* name: # (required) Name of the service. ...... ......
//常用的参数:
常用参数 | 说明 |
name | 被管理的服务名称 |
state=started\stopped\restarted | 动作包含启动关闭或者重启 |
enabled=yes\no | 表示是否设置该服务开机自启 |
runlevel | 如果设定了enabled开机自启去,则要定义在哪些运行目标下自启动 |
//安装httpd服务,查看web服务器httpd运行状态
[root@ansible ~]# ansible webservers -m yum -a 'name=httpd' #安装httpd服务 [root@ansible ~]# ansible webservers -a 'systemctl status httpd' 20.0.0.11 | FAILED | rc=3 >> ● httpd.service - The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled) Active: inactive (dead) Docs: man:httpd(8) man:apachectl(8)non-zero return code
//启动httpd服务
[root@ansible ~]# ansible webservers -m service -a 'enabled=true name=httpd state=started' 20.0.0.11 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "enabled": true, "name": "httpd", "state": "started", "status": { ...... ......
12、script 模块
//实现远程批量运行本地的 shell 脚本
[root@ansible ~]# ansible-doc -s script - name: Runs a local script on a remote node after transferring it script: chdir: # Change into this directory on the remote node before running the script. cmd: # Path to the local script to run followed by optional arguments. creates: # A filename on the remote node, when it already exists, this step will *not* be run. decrypt: # This option controls the autodecryption of source files using vault. executable: # Name or path of a executable to invoke the script with. free_form: # Path to the local script file followed by optional arguments. removes: # A filename on the remote node, when it does not exist, this step will *not* be run.
//编写脚本
[root@ansible ~]# vim test.sh #!/bin/bash echo "hello ansible from script" > /opt/script.txt
//赋权、script 执行脚本
[root@ansible ~]# chmod +x test.sh [root@ansible ~]# ansible webservers -m script -a 'test.sh' 20.0.0.11 | CHANGED => { "changed": true, "rc": 0, "stderr": "Shared connection to 20.0.0.11 closed.\r\n", "stderr_lines": [ "Shared connection to 20.0.0.11 closed." ], "stdout": "", "stdout_lines": [] } [root@ansible ~]# ansible webservers -a 'cat /opt/script.txt' 20.0.0.11 | CHANGED | rc=0 >> hello ansible from script
13、setup 模块
//facts 组件是用来收集被管理节点信息的,使用 setup 模块可以获取这些信息
[root@ansible ~]# ansible-doc -s setup - name: Gathers facts about remote hosts setup: fact_path: # Path used for local ansible facts (`*.fact') - files in this dir will be run (if executable) and their results be added to `ansible_local' facts if a ......
#获取mysql组主机的facts信息
[root@ansible ~]# ansible webservers -m setup 20.0.0.11 | SUCCESS => { "ansible_facts": { "ansible_all_ipv4_addresses": [ "192.168.122.1", "20.0.0.11", "172.17.0.1" ], "ansible_all_ipv6_addresses": [ .......
#使用filter可以筛选指定的facts信息
[root@ansible ~]# ansible dbservers -m setup -a 'filter=*ipv4' 20.0.0.12 | SUCCESS => { "ansible_facts": { "ansible_default_ipv4": { "address": "20.0.0.12", "alias": "ens33", "broadcast": "20.0.0.255", "gateway": "20.0.0.2", "interface": "ens33", "macaddress": "00:0c:29:2f:e9:bd", "mtu": 1500, "netmask": "255.255.255.0", "network": "20.0.0.0", "type": "ether" }, "discovered_interpreter_python": "/usr/bin/python" }, "changed": false }
四、inventory 主机清单
Inventory支持对主机进行分组,每个组内可以定义多个主机,每个主机都可以定义在任何一个或多个主机组内。
//如果是名称类似的主机,可以使用列表的方式标识各个主机
vim /etc/ansible/hosts 20 [webservers] 21 20.0.0.11:2222 22 20.0.0.1[2:5] 35 [dbservers] 36 db-[a:f].example.org
//inventory 中的变量
Inventory 变量名 | 含义 |
ansible_host | ansible连接节点时的IP地址 |
ansible_port | 连接对方的端口号,ssh连接时默认为22 |
ansible_user | 连接对方主机时使用的主机名。不指定时,将使用执行ansible或ansible-playbook命令的用户 |
ansible_password | 连接时的用户的ssh密码,仅在未使用密钥对验证的情况下有效 |
ansible_ssh_private_key_file | 指定密钥认证ssh连接时的私钥文件 |
ansible_ssh_common_args | 提供给ssh、sftp、scp命令的额外参数 |
ansible_become | 允许进行权限提升 |
ansible_become_method | 指定提升权限的方式,例如可使用sudo/su/runas等方式 |
ansible_become_user | 提升为哪个用户的权限,默认提升为root |
ansible_become_password | 提升为指定用户权限时的密码 |
(1)主机变量
[root@ansible ~]# vim /etc/ansible/hosts [webservers] 20.0.0.11 ansible_port=22 ansible_user=root ansible_password=123456
(2)组变量
[webservers:vars] #表示为 webservers 组内所有主机定义变量 ansible_user=root ansible_password=123456
[all:vars] #表示为所有组内的所有主机定义变量
ansible_port=22
(3)组嵌套
[nginx] 20.0.0.6 20.0.0.11 20.0.0.12 [apache] 20.0.0.3[0:3] [webs:children] #表示为 webs 主机组中包含了 nginx 组和 apache 组内的所有主机 nginx apache
感谢您的阅读,如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮。本文欢迎各位转载,但是转载文章之后必须在文章页面中给出作者和原文连接。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现