Search code examples
gitdeploymenttagsansible

How to check out most recent git tag using Ansible?


Is there an easy way to have Ansible check out the most recent tag on a particular git branch, without having to specify or pass in the tag? That is, can Ansible detect or derive the most recent tag on a branch or is that something that needs to be done separately using the shell module or something?


Solution

  • Ansible doesn't have checking out of the latest tag as a built in feature. It does have the update parameter for its git module which will ensure a particular repo is fully up to date with the HEAD of its remote.

    ---
    - git:
    repo=git@github.com:username/reponame.git
    dest={{ path }}
    update=yes
    force=no
    

    Force will checkout the latest version of the repository overwriting uncommitted changes or fail if set to false and uncommitted changes exist.

    See http://docs.ansible.com/git_module.html for more options on this module.

    You could do two things at this point:

    1) Have a separate branch with your tags on it, and just stay up to that using the update parameter.

    2) You could also use the shell module and implement something similar to: Git Checkout Latest Tag

    ---
    - name: get new tags from remote
      shell: "git fetch --tags"
      args:
        chdir: "{{ path }}"
    
    - name: get latest tag name
      shell: "git describe --tags `git rev-list --tags --max-count=1`"
      args:
        chdir: "{{ path }}"
      register: latest_tag
    

    And then use that result as a refspec with the git module

    - git:
    repo=git@github.com:username/reponame.git
    dest={{ path }}
    version: latest_tag.stdout