I’m currently working on an Ansible role to deploy an application to OpenShift. My application template uses a BuildConfig with a dockerStrategy, so when a build is run it runs against a remote git repo and branch.

I wanted my role to ensure that the current deployed application is up to date with the git branch, so we can push changes to that branch and whenever ansible runs it will know to reprocess the template, triggering a new build and deployment. (alternatively here we could use webhooks to trigger the build for us I suspect)

OpenShift nicely records the git ref used for a build:

oc get builds -o yaml

[SNIP]

    revision:
      git:
        author:
          email: dgoodwin@redhat.com
          name: Devan Goodwin
        commit: d43bb3d672d69788b926b1c21e96a64145c42fb7
        committer:
          email: dgoodwin@redhat.com
          name: Devan Goodwin
      type: Git
[SNIP]

So if we can determine what the latest git reference is for a branch with Ansible, we could easily compare these two values and see if a rebuild/redeploy is needed.

I wanted to do this without doing a full git clone as our repo in this case is quite large. As it turns out, this is quite easy with Ansible:

---
- name: fetch latest commit hash from git ref
  git:
    repo: "https://github.com/dgoodwin/tito.git"
    version: "master"
    clone: no
    accept_hostkey: true
  register: git_sha1_results

- debug: var=git_sha1_results

The result looks like this:

TASK [myrole : debug] **********************************************************************************************************************************************************************************************************
Thursday 08 June 2017  11:22:49 -0300 (0:00:01.099)       0:00:05.450 *********
ok: [ec2host.amazonaws.com] => {
    "changed": false,
    "git_sha1_results": {
        "after": "895890a7a2ee775dde91fa95adc6502ef33fd337",
        "before": null,
        "changed": true
    }
}