1、语法检查的作用
在shell脚本中可以使用-n
来检查语法是否正确,通过语法检查可以大大的降低了脚本开发时间,那么作为一款热门的自动化工具,ansible
也支持语法检查,下面一起来了解一下。
2、如何进行语法检查
在ansible
中,我们可以通过剧本
去实现脚本
的一个功能,可以把剧本
理解为我们的Shell
脚本,大家都知道,写脚本难免会出现一些Bug之类的,而写剧本也同样会遇到这种情况,那么这时候通过语法检查就可以快速解决问题了。
语法如下:
ansible-playbook --syntax-check <ansible.yaml>
然后我们对下面这个剧本进行检查:
2.1、正确语法
- hosts: hello #使用的主机列表
connection: ssh #连接方式
remote_user: root #使用的远程用户
tasks:
- name: install git <name>
yum: name=git,net-tools state=installed #安装git、net-tools
- name: Unstaller mariadb <name>
yum: name=mariadb-server state=installed #卸载mariadb-server
如果检查没问题,那么就会输出被检查的文件名,下面看一下错误语法
2.2、错误语法
- hosts: hello #使用的主机列表
connection: ssh #连接方式
remote_user: root #使用的远程用户
tasks:
- name: install git <name>
yum: name=git,net-tools state=installed #安装git、net-tools
- name: Unstaller mariadb <name>
yu: name=mariadb-server state=installed #卸载mariadb-server
此时就会提示:
ERROR! no action detected in task. This often indicates a misspelled
module name, or incorrect
大致意思就是:
错误!在任务中未检测到操作。这通常表示模块名称拼写错误或不正确
然后提示是在第七行,也就是 - name: Unstaller mariadb <name>
出错了,我们仔细看就可以看到,我在第八行的模块写的是yu
,正确的应该是yum
,所以报错了,然后修改,继续检查
- hosts: hello #使用的主机列表
connection: ssh #连接方式
remote_user: root #使用的远程用户
tasks:
- name: install git <name>
yum: name=git,net-tools state=installed
- name: Unstaller mariadb <name>
yum: name=mariadb-server state=installed
然后就成功了
3、执行剧本
执行剧本有两种方式,如下:
名称 | 作用 |
---|---|
伪执行ansible-playbook -C <file.yaml> | 模拟执行,主要用于排错,不会产生实际影响 |
执行ansible-playbook <file.yaml> | 直接执行 |
3.1、伪执行
ansible-playbook -C yum.yaml
执行效果
3.2、执行
ansible-playbook yum.yaml
执行效果
相关文章:
ansible从入门到入土:教你如何编写ansible剧本实现yum安装软件