需求
- 實現python的字符串分割
- 實現re的正則表達式分割
Filter 類
class FilterModule(object):
''' A filter to split a string into a list. '''
def filters(self):
return {
'filter_name' : filter_function,
}
所有的filter類都是上訴構造
-
filter_name
是 Ansible Jinja2 filter的name。 -
filter_function(string)
是處理字符的方法, 如{{ 'test' | filter_name }}, test字符串會傳遞給string。
實現代碼
cat filter_plugins/split.py
import re
def split_string(string, seperator=None, maxsplit=-1):
try:
return string.split(seperator, maxsplit)
except:
return list(string)
def split_regex(string, seperator_pattern):
try:
return re.split(seperator_pattern, string)
except:
return list(string)
class FilterModule(object):
''' A filter to split a string into a list. '''
def filters(self):
return {
'split' : split_string,
'split_regex' : split_regex,
}
Playbook
- hosts: localhost
gather_facts: no
tasks:
- debug: msg={{ 'a b c' | split }}
- debug: msg={{ '1c2c3' | split('c') }}
- debug: msg={{ 'dev.example.com' | split_regex('\.') }}
主機清單
localhost ansible_connection=local
運行playbook
image.png