Ansible 命令讲解Ansible 命令集# 以下所有命令均可使用`-h`参数获取帮助信息ansible# Define and run a single task 'playbook' against a set of hosts# 常用命令ansible-config# View ansible configuration.ansible-console# REPL console for executing Ansible tasks.# 交互式工具,相当linux中的shell,不常用ansible-doc# plugin documentation tool# 查询模块的文档说明,类似linux中的man,常用命令ansible-galaxy# Perform various Role and Collection related operations.ansible-inventory# Show Ansible inventory information, by default it uses the inventory script JSON formatansible-playbook# Runs Ansible playbooks, executing the defined tasks on the targeted hosts.# 执行系列任务,类似linux中的sh,常用命令ansible-pull# pulls playbooks from a VCS repo and executes them for the local hostansible-vault# encryption/decryption utility for Ansible data files
Ansible 常用命令集# 常用命令集ansible# Ansible指令的核心部分,主要用于执行ad-hoc命令,也就是单条命令# 默认使用command模块,默认的使用模块可以在ansible.cfg中进行定义ansible-doc# 用于查看模块信息,# 参数 -l 列出可用的插件# 参数 -s 用于查看指定模块的用法,例如“ansible-doc -s shell”ansible-playbook# 读取playbook文件内容并执行定义的任务# 对于固化的需求通常采用playbook方式定义和实现ansible-vault# 主要应用于包含敏感信息的场景,可以加密和解密敏感信息# 经过加密后的playbook,编辑时需要输入事先设定的密码才能打开# 使用 --ask-vault-pass 参数执行加密后的playbook文件ansible-config# 查看ansible的配置# 参数 list 打印所有配置参数,参数 view 查看配置文件# 结合 grep 使用可以获取具体配置信息,例如“ansible-config view |grep -v "#" |grep host_key_checking”
Ansible ad-hoc命令# ansible <host-pattern> [-f forks] [-m module_name] [-a args]# <host-pattern>命令生效的主机: <inventory_group_name>/<inventory_host_ip>/all # 常用选项通过 ansible -h 命令获取详细信息-v# 输出详细执行过程信息verbose mode (-vvv for more, -vvvv to enable connection debugging)-i inventory_file# 指定inventory文件,默认为/etc/ansible/hosts-f forks# 指定并发线程数(一次处理多少个主机),默认5个线程-m module_name# 指定执行使用的模块-M directory# 指定模块存放路径,默认为/usr/share/ansible-a args# 指定模块参数-l hosts_ip# 限定主机(只在限定主机上执行任务)--become-method BECOME_METHOD# 提权方法,默认为sudo,一般为su--become-user BECOME_USER# 切换用户,默认为root-K, --ask-become-pass# 请求提权密码--list-hosts# 列出此次的主机列表,但不做任何改变--syntax-check# 语法检查-C, --check# 检验可能的错误,但不做任何改变# 主机名文件保留- "-t"或"--tree"选项可以将ansible的执行结果按主机名保存在指定目录下的文件中- 使用"-t"选项可以将第一次执行的结果按主机名保存在文件中,此后即使不使用"-t"选项也能提升执行速度# 命令示例ansible 192.168.56.3 -a 'hostname'# 默认使用command模块(不支持变量、管道等)ansible 192.168.56.3 -m command -a 'hostname'ansible Test --list# 列出Test组所有的主机列表ansible Test:Test2 -m ping# 通过ping模块检查Test组和Test2组的主机是否存活ansible Test:!Test2 -m ping# 在Test组但不在Test2组的主机ansible Test:&Test2 -m ping# 同时存在Test组和Test2组的主机ansible Tes* -m ping# 组名开头为Tes的主机ansible all -m shell -a 'hostname && date'# 通过shell模块在所有主机试行shell命令ansible all -f 10 -m shell -a 'hostname && date;cat /etc/system-release'# shell模块支持变量、管道、if判断等复杂命令
部分参数如果不指定,将采用ansible.cfg中的设置值,或者采用原始默认值 。

经验总结扩展阅读
- 自动化专业有必要转计算机吗 未来就业前景好吗
- 机械自动化属于自动化类吗 就业方向及前景怎么样
- 自动化类和计算机类哪个好 发展前景怎么样
- 自动化专业属于计算机大类吗 都学什么课程
- 自动化专业是哪个大类 都学什么课程
- 自动化专业和计算机专业区别 哪个专业前景好
- 小样本利器4. 正则化+数据增强 Mixup Family代码实现
- 从0搭建vue3组件库:自动化发布、管理版本号、生成 changelog、tag
- ansible使用临时命令通过模块来执行任务
- Ansible 批处理实战