When I checked whether Jinja2 filters could handle regular expressions for variable values dynamically acquired by Ansible without using replace, template module, sed in command module, etc., regex_replace
was prepared. ..
The following uses the variable kb_msu "Windows8.1-KB3140735-x64.msu" with regex_replace Example 1) Replace the extension ** and define it as another variable Example 2) Extract only the middle number ** and define it as another variable Sample playbook output by debug module
regex_raplace.yml
---
- hosts: localhost
connection: local
gather_facts: no
vars:
kb_msu: "Windows8.1-KB3140735-x64.msu"
#Example 1) kb_msu extension.from msu.Replace with xml
kb_xml: "{{ kb_msu | regex_replace('.msu','.xml') }}"
#Example 2) kb_msu'-KB'When'-'Whenの間の数字を抽出
kb_no: "{{ kb_msu | regex_replace('^.*-KB(\\d*)-.*msu$','\\1') }}"
tasks:
- debug: msg="kb_msu={{ kb_msu }} , kb_xml={{ kb_xml }} , kb_no={{ kb_no }}"
# ansible-playbook regex_raplace.yml
PLAY [localhost] ***************************************************************
TASK [debug] *******************************************************************
ok: [localhost] => {
"msg": "kb_msu=Windows8.1-KB3140735-x64.msu, kb_xml=Windows8.1-KB3140735-x64.xml , kb_no=3140735"
}
PLAY RECAP *********************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0
Click here for how to use Jinja2 filters on the official website (http://docs.ansible.com/ansible/playbooks_filters.html). Various other useful filters (such as those related to Windows and those that escape regular expressions) Is added / updated? Since it was done, it may be good to take a peek regularly.
In addition, at the moment (2016/07/04), it is not listed on the official website,
It seems that regex_search
and regex_findall
can also be used for regular expressions.
From Version 2.2.0? Is not it? (ansible 2.2.0 (devel 394430a61e) last updated 2016/06/28 13:25:07 (GMT +900) was usable)
Below is a portion of the code for Ansible-Webinar https://github.com/privateip/Ansible-Webinar-Mar2016/blob/master/roles/network_facts/tasks/ios.yaml
Recommended Posts