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: 127.0.0.1
  connection: local
  vars:
    url: "http://foo.com/a/b/c/filename.tar.gz"
    file_name: "{{ url | basename }}"
  gather_facts: false
  tasks:
     - name: "Grab the file name from {{ url }}"
       debug:
         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 [127.0.0.1] **************************************************************************************************

TASK [Grab the file name from http://foo.com/a/b/c/filename.tar.gz] ***********************************************
ok: [127.0.0.1] => {
    "msg": "Base name is filename.tar.gz"
}

PLAY RECAP ********************************************************************************************************
127.0.0.1                  : 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 -0400