regexansibleansible-ad-hoc

Extract last character of string with ansible and regex_replace filter


In a playbook, I try to extract the last character of variable "ansible_hostname".

I try to use regex_replace filter to do that, but nothing works.

I simplified my piece of script with this ad-hoc command :

ansible localhost -m debug -a "msg= {{ 'devserver01' | regex_replace('[0-9]{1}$', '\1') }}"

I want to extract the last character : '1'.

I'm using Ansible 2.0.


Solution

  • Python can save the day, and is acceptable in this use.

    Just add a [-1] to the end of the string or variable, which gets the last character in a string.

    ansible localhost -m debug -a "msg={{ 'devserver01'[-1] }}"