How to Checkout a Specific Commit Using Ansible?

Managing code versions effectively is crucial in automation workflows. With Ansible’s ansible.builtin.git module, you can checkout a specific commit from a Git repository, ensuring your infrastructure or deployments use the exact version you need.

I'm Luca Berton, and in this tutorial, I’ll guide you through checking out a specific commit of a Git repository using Ansible.

ansible.builtin.git

  • Part of ansible-core
  • Manages Git checkouts
  • Supports branches, tags, and commit hashes

The ansible.builtin.git module enables automated repository management in Ansible playbooks. You can use it to clone repositories, checkout branches, pull changes, and, importantly, checkout a specific commit by using its SHA-1 hash.

Links

  • [Ansible Git Module Documentation](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/git_module.html)

Playbook

I’ll show you how to checkout a specific commit from a Git repository using an Ansible playbook.

Execution

``bash

$ ansible-playbook git_checkout_commit.yml

`

Playbook Code

`yaml

  • name: Checkout a specific commit from a Git repository

hosts: localhost

tasks:

- name: Clone the repo and checkout a specific commit

ansible.builtin.git:

repo: "https://github.com/example/repo.git"

dest: "/path/to/clone"

version: "abc123def4567890" # Replace with your commit hash

`

Explanation:

  • repo: Defines the Git repository URL.
  • dest: Specifies where to clone the repository.
  • version: Points to the exact commit hash to checkout.

Additional Options

Force Checkout a Specific Commit

If the repository is already cloned, but you want to force-checkout a commit:

`yaml

  • name: Force checkout a specific commit

ansible.builtin.git:

repo: "https://github.com/example/repo.git"

dest: "/path/to/clone"

version: "abc123def4567890"

force: yes # Discards any local changes

`

Checkout a Commit Not Part of a Branch

If the commit isn't part of any branch or tag, you might need to specify refspec:

`yaml

  • name: Checkout a commit not part of a branch

ansible.builtin.git:

repo: "https://github.com/example/repo.git"

dest: "/path/to/clone"

version: "abc123def4567890"

refspec: "+refs/heads/:refs/remotes/origin/"

`

Before Execution

`bash

$ ls /path/to/clone

(no repository exists)

`

After Execution

`bash

$ git log --oneline

abc123d (HEAD) Fix critical bug in deployment

456789a Add feature X

7890bcd Initial commit

`

Handling Detached HEAD State

Since checking out a commit directly places Git in a detached HEAD state, you may want to switch back to a branch after checking out:

`yaml

- name: Checkout a branch after commit

command: git checkout -b feature-branch

args:

chdir: "/path/to/clone"

``

Conclusion

Now you know how to checkout a specific commit of a Git repository usi