《Puppet实战手册》——1.10 利用Git钩子自动进行语法检查

    xiaoxiao2024-05-27  117

    本节书摘来自异步社区《Puppet实战手册》一书中的第1章,第1.10节,作者:【英】John Arundel著,更多章节内容可以访问云栖社区“异步社区”公众号查看

    1.10 利用Git钩子自动进行语法检查

    如果能够在交付配置清单之前发现配置清单中的语法错误,那么将是一件非常好的事。可以使用puppet parser validate命令检查配置清单中的语法问题。

    ubuntu@cookbook:~/puppet$ puppet parser validate manifests/nodes.pp Error: Could not parse for environment production: Syntax error at end of file; expected '}' at /home/ubuntu/puppet/manifests/nodes.pp:3 Error: Try 'puppet help parser validate' for usage

    这是非常有用的。如果清单中的任何一个位置存在语法错误,那么都会停止Puppet在所有节点上运行,即使节点中没有使用那部分有错误的配置清单。因此,检查配置清单中的错误,直到问题被发现,可能引起一段时间内Puppet在生产环境中无法应用变更,这可能会带来严重的后果。要避免这种情况的发生,最好的方法就是在版本控制系统中使用预提交的钩子自动进行语法检查。

    操作步骤具体步骤如下。

    1. 在Puppet仓库目录创建一个新的hooks目录。

    ubuntu@cookbook:~/puppet$ mkdir hooks2. 参考下面的内容,创建hooks/check_syntax.sh文件(基于由Puppet Labs提供的脚本)。

    #!/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 parser validate > $error_msg ;;        *.erb )           # Check ERB template syntax           git cat-file blob :0:$indexfile |            erb -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

    3. 使用下面的命令给钩子脚本设置执行权限:

    ubuntu@cookbook:~/puppet$ chmod a+x .hooks/check_syntax.sh4. 将下面的任务添加到Rakefile文件中:

    desc "Add syntax check hook to your git repo" task :add_check do   here = File.dirname(__FILE__)  sh "ln -s #{here}/hooks/check_syntax.sh   #{here}/.git/hooks/pre-commit"  puts "Puppet syntax check hook added" end

    5. 运行下面的命令:

    ubuntu@cookbook:~/puppet$ rake add_check ln -s /home/ubuntu/puppet/hooks/check_syntax.sh  /home/ubuntu/puppet/.git/hooks/pre-commit

    Puppet语法检查的钩子已添加完成。

    工作原理该check_syntax.sh脚本会阻止用户提交任何带有语法错误的文件。

    ubuntu@cookbook:~/puppet$ git commit -m "test commit" Error: Could not parse for environment production: Syntax error at '}' at line 3 Error: Try 'puppet help parser validate' for usage manifests/nodes.pp: Error: 1 syntax errors found, aborting commit.

    如果将hooks目录添加到Git仓库中,任何检出了副本的人都可以运行rake add_check任务,检查配置清单中的语法。

    相关资源:敏捷开发V1.0.pptx
    最新回复(0)