puppetのmanifestを書いていて、我ながらtypo、構文ミスとかヘボいミスが多すぎるので、 vimとgit hooks(pre-commit)とで2重でsyntax checkをするようにした。
具体的なsyntax checkの方法
- vimからはsyntasticを利用してsyntax check
- git hooks(pre-commit)から
puppet parser validate
を利用して、commitのタイミングでsyntax check。問題がある場合はcommitが出来ないようにする
puppetとpuppet-lintの導入
manifestを書いているマシンにpuppetが入っていないとSyntax Checkが出来ないので導入。
またsyntasticがpuppet-lint
を利用するので併せて導入。
私は、最近はmac上でmanifestを書いているのでgemで導入
1 2 |
|
RHEL系でyumの場合は下記のような感じ。
1
|
|
syntasticの導入
私はneobundleを利用しているので、下記を.vimrc
に書いて:NeoBundleInstall
1
|
|
puppetのmanifestを編集して、保存したタイミングでsyntaxのcheckが走る。
エラー部分は:Errors
で表示。
構文がおかしい場合は、下記のように表示される。
これでvimからsyntax checkが出来る。
git pre-commitを用意
Vimだけでも良いんですが、puppetのファイルは全てgitで管理しているので、 git hooksでもcheckが走るようにする。
.git/hooks/pre-commit
に下記のようなファイルを用意
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
puppetのversionが2.7以下の場合は、puppet parser validate
というコマンドが無いので、下記コマンドを利用するように変更してください。
1
|
|
するとcommitしようとしたタイミングにsyntax checkが走るので、エラーがある場合は下記のようにcommit出来ない。
これでヘボいミスも減って、commit履歴を汚さずに済むはず。