'How to use githooks via ansible
All Git hooks are ordinary scripts that Git executes when certain events occur in the repository.
Can I use these client-side hooks, when i update my repository with the builtin git-module from ansible?
The following Demo-Playbook creates a repository and a clone in the /tmp folder.
The post-merge-script adds a line to a file.
The ansible-module ignores this script, but the shell-command git pull creates the new line.
$ cat git-demo.yml
---
- name: git pull demo
hosts: localhost
tasks:
- name: create directory
file:
dest: /tmp/demo
state: directory
- name: init repo
shell: git -C /tmp/demo init
- name: create first commit
shell: date >> /tmp/demo/test.txt;git -C /tmp/demo add .;git -C /tmp/demo commit -m1
- name: clone demo
ansible.builtin.git:
repo: /tmp/demo
dest: /tmp/test
- name: create hook-script
copy:
dest: /tmp/test/.git/hooks/post-merge
content: |
#!/bin/sh
date +"%F %T Demonstrating git-hook" >> /tmp/demo/test.txt
mode: 0755
- name: create second commit
shell: date >> /tmp/demo/test.txt;git -C /tmp/demo commit -am2
- name: git pull without hook
ansible.builtin.git:
repo: /tmp/demo
dest: /tmp/test
- name: create third commit
shell: date >> /tmp/demo/test.txt;git -C /tmp/demo commit -am3
- name: git pull with hook-script
shell: git -C /tmp/test pull
Only the shell-module invoked the hook-script:
$ ansible-playbook git-demo.yml
$ cat /tmp/demo/test.txt
Thu 24 Mar 2022 02:13:06 AM CET
Thu 24 Mar 2022 02:13:08 AM CET
Thu 24 Mar 2022 02:13:08 AM CET
2022-03-24 02:13:09 Demonstrating git-hook
I have used git version 2.25.1 and ansible version 2.10.17.
Solution 1:[1]
As mentioned in the comment, there is no pull or merge happening.
If you want that script to run every time ansible clones/checks out the repository, try the post-checkout hook.
But as you are already automating it, I would suggest to use ansible to trigger the script instead of a hook.
You could register a variable (e.g. git_result) on your git module and then decide what to do based on git_result.changed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | toydarian |
