多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
### 使用提交钩子 如果我们在提交配置清单之前能够发现其中的语法错误将会是个好消息。 检查 Puppet 配置清单的语法可以使用 puppet parser validate 命令: ``` # puppet parser validate /etc/puppet/manifests/site.pp err: Could not parse for environment production: Syntax error at end of file at /etc/puppet/manifests/site.pp:3 ``` 这种语法检查是特别有用的,因为配置清单中的任何一个错误将使运行 Puppet 的节点停止工作, 甚至不会应用配置清单中错误代码的节点也会停止工作。 因此,导入(check in)一个有错误的配置清单,将导致 Puppet 应用这些更新到生产环境使其停止运行, 直到问题被发现,这可能会产生严重的后果。 避免错误发生的最好方法是在你的版本控制仓库中使用 **pre-commit hook** 自动执行语法检查。 #### 操作步骤 如果你使用的是 Git 版本控制系统,可以添加一个脚本 .git/hooks/pre-commit 用于为你提交的所有配置清单文件执行语法检查。 下面的脚本示例来自 Puppet Labs wiki: [http://projects.puppetlabs.com/projects/puppet/wiki/](http://projects.puppetlabs.com/projects/puppet/wiki/) 。 ``` #!/bin/sh syntax_errors=0 error_msg=$(mktemp /tmp/error_msg.XXXXXX) if git rev-parse --quiet --verify HEAD > /dev/null then against=HEAD else # Initial commit: diff against an empty tree object against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 fi # Get list of new/modified manifest and template files to check (in git index) for indexfile in `git diff-index --diff-filter=AM --name-only --cached \ $against | egrep '\.(pp|erb)'` do # Don't check empty files if [ `git cat-file -s :0:$indexfile` -gt 0 ] then case $indexfile in *.pp ) # Check puppet manifest syntax #git cat-file blob :0:$indexfile | puppet \ # --color=false --parseonly --ignoreimport > $error_msg # Updated for 2.7.x puppet parser validate $indexfile > $error_msg ;; *.erb ) # Check ERB template syntax # -P : ignore lines which start with "%" git cat-file blob :0:$indexfile | erb -P -x -T - |\ ruby -c 2> $error_msg > /dev/null ;; esac if [ "$?" -ne 0 ] then echo -n "$indexfile: " cat $error_msg syntax_errors=`expr $syntax_errors + 1` fi fi done rm -f $error_msg if [ "$syntax_errors" -ne 0 ] then echo "Error: $syntax_errors syntax errors found, aborting commit." exit 1 fi ``` #### 工作原理 这个提交钩子脚本 .git/hooks/pre-commit 会防止你提交任何有语法错误的配置清单文件: ``` # git commit -m "spot the deliberate mistake" manifests/site.pp err: Could not parse for environment production: Syntax error at end of file; expected '}' at /etc/puppet/manifests/site.pp:3 manifests/site.pp: Error: 1 syntax errors found, aborting commit. ``` #### 更多用法 你可以在 Puppet Labs wiki: [http://projects.puppetlabs.com/projects/1/wiki/Puppet_Version_Control](http://projects.puppetlabs.com/projects/1/wiki/Puppet_Version_Control) 上找到有关这个脚本的更多详细信息。 你也可以使用类似的 update 钩子防止有语法错误的配置清单推送到 Puppetmaster: 查看同样的 wiki 页面也可以获得使用 update 钩子的详细信息。 #### 参见本书 * 本章的 [使用版本控制](#ch01sec01) 一节