使用ansible和regex_replace过滤器提取字符串的最后一个字符



在剧本中,我尝试提取变量"ansible_hostname"的最后一个字符。

我尝试使用regex_replace过滤器来做到这一点,但没有任何效果。

我用这个临时命令简化了我的脚本:

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

我想提取最后一个字符:"1"。

我正在使用 Ansible 2.0。

Python 可以

节省时间,并且在此用途中是可以接受的。

只需在字符串或变量的末尾添加一个 [-1],即可获取字符串中的最后一个字符。

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

以下内容将为您工作。

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

解释:

^(.+) : 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