9

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.

techraf
  • 64,883
  • 27
  • 193
  • 198
Antoine
  • 4,456
  • 4
  • 44
  • 51

2 Answers2

24

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] }}"
Theo
  • 1,303
  • 12
  • 11
-1

The following will work for you.

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

Explanation:

^(.+) : it will take one or more group of characters from start
([0-9]{1})$ : removes one digit from end of string

\\1 : is a back reference to the first group
Amol Damodar
  • 359
  • 2
  • 4