Ansible: clone just one file from git repo

Viewed 1221

Is there any possibility to clone just a file from git with git ansible module? As I read looks like the git archive from ansible is working only from local cloned repo.

For the moment I use this:

  - name: Bring file from git
     shell:  git archive --remote=git://git.example.com/project.git HEAD:{{ test }} filename | tar -x -C folder1 -s /filename/filename_{{ test }}/
     delegate_to: localhost

test variable is define in inventory file under each group with other value:

[group1:vars]
test=abc

[group1]
host1
host2

[group2:vars]
test=xyz

[group2]
host5
host6

Is there any possibility to make the shell module to be idempotent in order that if the file was already downloaded and exist to not run again same task for the same value of test variable over the hosts from the same hostgroup.

As example:

If I run the task from above for group1, the task will run over the first host under the group 1 and will bring the file from git, then will go over second host under group1 and will again bring the same file from git.

What I want to do is that if the task brings the file from git for first host under the group1 to not bring again the same file from git for host2 from group1.

Thanks

1 Answers

Q: "If the task brings the file from git for the first host under the group1 to not bring again the same file from git for host2 from group1."

A: It's possible to run_once the task. For example.

- name: Bring file from git
  shell:  git ...
  run_once: true

Q: "Playbook starts with: - hosts: all. I want that for each first host under each group to run the shell: git ...."

A: It's possible to put the tasks into separate plays. Create a group of the first hosts from all groups in the first play. Use the created group to download files from git in the second play. Once the data is prepared run the third play for all hosts. For example

- name: Create group of hosts my_git_group
  hosts: localhost
  gather_facts: false
  tasks:
    - add_host:
        name: "{{ groups[item]|first }}"
        groups: 'my_git_group'
      loop: "{{ groups.keys()|difference(['ungrouped', 'all']) }}"

- name: Download files from git
  hosts: my_git_group
  gather_facts: false
  tasks:
    - debug:
        msg: "{{ inventory_hostname }} shell git"

- name: Proceed
  hosts: all
  gather_facts: false
  tasks:
    - debug:
        msg: Proceed
      run_once: true
Related