Retrieving a file name from a URL with ansible

Ansible has several extremely powerful modules for interacting with web resources. The get_url module allows you to retrieve resources, uri allows you to interact with web services and the templating and filtering capabilities provided by Jinja2 allow you to slice and dice the results in a variety of ways. One pattern that I find useful is applying the basename filter to the URL to grab a file name:

- hosts:
  connection: local
    url: ""
    file_name: "{{ url | basename }}"
  gather_facts: false
     - name: "Grab the file name from {{ url }}"
         msg: "Base name is {{ file_name }}"

After the filter is applied file_name will contain the last component in the “/” separated URL:

$ ansible-playbook get-basename.yml

PLAY [] **************************************************************************************************

TASK [Grab the file name from] ***********************************************
ok: [] => {
    "msg": "Base name is filename.tar.gz"

PLAY RECAP ********************************************************************************************************                  : ok=1    changed=0    unreachable=0    failed=0

I’ll share some valid uses for this in a future blog post.

This article was posted by Matty on 2017-08-27 09:54:00 -0400 EDT