Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading