This role is used to deploy scripts held in a git repository without the target needing direct access to the repository or even having a git client installed. It uses git archive with the Ansible control node acting as an intermediary. Parameters passed to the role specify the repository and a tag or branch and the destination.

Manual Process

Create a tar archive from the repository. Copy the archive to the target and then extract it.

Ansible Role: gitdeploy

This was created for another playbook and is also used in Building an additional Samba 4 Domain Controller 2, dnsmasq-samba and a few others.

File Structure

This is a standard Ansible role with as single tasks .yaml file, a meta to keep Ansible happy and a README.md for my own notes.

gitdeploy  

  meta

    main.yaml

  tasks     

    main.yaml  

  README.md

tasks/main.yaml

--- # Ansible Role Tasks

# Deploy files from a git repo to the target host directory

# ansible.builtin.tempfile to create work area

# git archive --format tar --remote ssh://rachael:/srv/git/scripts/bacula.git u2404os-dev > /tmp/bacul-script.tar

# vars:
# git_repo: ssh://mygit.example.com:/srv/git/scripts/bacula.git
# # use branch, book says also tag or commit
# git_version: u2404os-dev
# destination: /opt/bostoncube/baculatest

- name: Create working directory
  delegate_to: localhost
  ansible.builtin.tempfile:
    state: directory
    prefix: archive-
  register: archive_temp

We need a local temporary directory on the Ansible controller (hence delegate_to: localhost)  to create the archive in. The tempfile module creates on with a random name to avoid collisions if we have several playbooks running at once

# ansible.builtin.git needs to clone the repo to extract an archive

- name: Create git archive
  delegate_to: localhost
  ansible.builtin.shell:
    cmd: git archive --format tar --remote {{ git_repo }} {{ git_version }} > {{ archive_temp.path }}/git-archive.tar

Git should already be installed on the Ansible Controller. It will also create a clone of the repo before creating the archive.

- name: create destination directory
  become: true
  ansible.builtin.file:
    path: "{{ destination }}"
    state: directory
    owner: root
    group: root
    mode: '0755'

- name: Upload and extract archive
  become: true
  ansible.builtin.unarchive:
    src: "{{ archive_temp.path }}/git-archive.tar"
    dest: "{{ destination }}"
    owner: root
    group: root

We need to create the destination directory if it doesn't already exist and then use the unarchive module to extract the archive into the destination directory. File permissions will be whatever was created from the original git clone so could be anything, you'll need to fix that up after the role has completed especially if it's anything complex.

- name: Remove working directory
  delegate_to: localhost
  ansible.builtin.file:
    path: "{{ archive_temp.path }}"
    state: absent

Finaly remove the temporary directory and its contents.

...