Ansible snippets - splitting variables

Ansible snippets - splitting variables

A useful Ansible snippet - splitting a variable value in Ansible.

the stuffs - splitting a variable using .split

Let’s paint a picture. Say there’s an application that needs upgraded. It’s distributed via a tarball. There is a service setup using a symlink - software -> software-1.2.3. The workflow would be something like…

  • Untar a file.
  • Change the symlink to point to the new folder (software -> software-2.0.0).
  • There’s already a variable for the tar file name.

Instead of creating another variable for the symlink, Ansible piggy backs the tarball name.

---
# tasks file for localhost.split
# software_tar_file == 'software-2.0.0.tar'
# desired symlink = software
- name: Untar
  unarchive:
    src: "{{ software_tar_file }}"
    dest: "{{ software_tar_file_location }}"

- name: Move the symbolic link.
  file:
    dest: "{{ software_tar_file.split('-')[0] }}"
    src: "{{ software_tar_file.split('.tar')[0] }}/"
    state: link

In this case, split is used in two ways. The first is to get the future symlink name - software. Split simply drops the second half with the [0] list item. The second example, split is just removing the .tar extension, which gives the extracted folder. Split can use any delimiter. There’s also an easy way to do this if you don’t have a complicated filename, like “software-1.2.3.tar”. If you just have “software.tar”, you can split it with:

# software_tar_file == 'software.tar'
{{ software_tar_file | splitext }}

Might help a fellow Ansible user out there. More info on this and other Jinja2 filters can be found in the Ansible documentation here. - http://docs.ansible.com/ansible/playbooks_filters.html

Example Ansible snippet playbook and role:

-b