LoginSignup
2
4

More than 5 years have passed since last update.

ansible playbook開発時にgitにコミットする前にSyntax Errorをチェックする

Last updated at Posted at 2017-02-20

概要

ansibleのplaybookを書いてリポジトリにcommit、pushしてさあ動かすぞって思ったらにSyntax Errorになってしまい、泣く泣く恥ずかしい修正を追加でコミットした経験はありませんか?

「yamlのSyntax Error修正」とか「fix typo」みたいなコミットが溢れかえるのは嫌ですよね。
そこで、gitのpre-commitを使って事前にチェックしてしまいましょう。

Makefile

自分はタスクランナー代わりにMakefileを良く使っています。
site.ymlと同じディレクトリに以下のようなMakefileを作成します。

Makefile
all: test

INVENTORY_PATH = inventories
INVENTORIES    = $(shell git ls-files "$(INVENTORY_PATH)/*")

syntax:
    $(foreach inventory,$(INVENTORIES),ansible-playbook --syntax-check -i $(inventory) site.yml;)

test: syntax

pre-commit

pre-commitは、git commitが実行される際に呼ばれるファイルです。
.git/hooks/ に以下のようなpre-commitを作成します。

pre-commit
#!/bin/bash
if git rev-parse --verify HEAD >/dev/null 2>&1
then
    against=HEAD
else
    # Initial commit: diff against an empty tree object
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# Redirect output to stderr.
exec 1>&2

IS_ERROR=0
if ! make syntax; then
  echo "Syntax Error"
  IS_ERROR=1
fi
exit $IS_ERROR

make syntax の結果がエラーの場合、commitをしないようになってます。
実行権限を忘れずにつけておきましょう。

$ chmod +x .git/hooks/pre-commit

まとめ

ためしにsyntax errorがある状態でコミットしてみると...

$ git commit -m "test commit"
ansible-playbook --syntax-check -i inventories/production.yml site.yml;
ERROR! A malformed role declaration was encountered.
Syntax Error

という具合にコミット前にチェックすることができました。
事前にチェックするする仕組みがあると安心して開発ができますね。
便利なので試してみてください。

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4