How to register archive file name as variable in Ansible?

FYI: This is Ansible 2.7

I’m archiving a directory, and I need to grab the file name I create and register it as a variable for further use in the playbook.

- name: Compress directory /etc/apache2/ into /tmp
  archive:
    path: /etc/apache2
    dest: /tmp/{{ ansible_hostname }}-apache2-{{ ansible_date_time.date }}.tar.gz
  register: archive_name

This gives me a file /tmp/hostname-apache2-09-01-2022.tar.gz, but I do not know how to register that as a variable. Is this possible?

I specifically need just the file name, not the full path.

I tried:

- debug:
    var: archive_name.arcroot

However, all it gives me back is:

ok: [hostname] => {
    "archive_name.arcroot": "/etc/"
}

I also don’t see anything else as an option in the documentation.

>Solution :

You could first save the desired path or just the filename into a variable and then use it in all your required tasks.

- name: Define archive_name
  set_fact:
    my_archive_name: "{{ ansible_hostname }}-apache2-{{ ansible_date_time.date }}.tar.gz"

- name: Compress directory /etc/apache2/ into /tmp
  archive:
    path: /etc/apache2
    dest: "/tmp/{{ my_archive_name }}"

Note that Jinja expressions should always be enclosed in quotes.


You can also store the whole path in the variable, including the /tmp/ prefix.

If you need only the filename elsewhere, you can extract it with the basename filter.

Example: {{ "/tmp/hostname-apache2-09-01-2022.tar.gz" | basename }}
Returns: hostname-apache2-09-01-2022.tar.gz

Leave a Reply