'Ansible archive file for few path earlier

Below is the folder structure

playbook
  |-groups_Vars
  |-host
  |-roles
    |-archive-artifact
      |-task
        |-main.yml
  |-archive-playbook.yml
myfile

In my main.yml, I need to archive the playbook in playbook.tar.gz.

- archive:
    path: "<earlier path>/playbook/*"
    dest: "<earlier path>/playbook.tar.gz"
    format: gz


Solution 1:[1]

The folder that holds a playbooks is accessible in the special variable playbook_dir.
Getting the parent directory of a file or directory in Ansible is possible via the filter dirname.

And, as pointed in the documentation, path can be either a single element or a list of elements, so you could also have myfile included in that list.

So, to archive the playbook directory in the parent folder of the playbook directory, one could do:

- archive:
    path: 
      - "{{ playbook_dir }}/*"
      - "{{ playbook_dir | dirname }}/myfile"
    dest: "{{ playbook_dir | dirname }}/playbook.tar.gz"
    format: gz

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1