2016-04-12 12 views
1

奇妙であっても、偶数であれば、Ansibleプレイブックのホスト名に基づいて別のサーバーを割り当てる必要があります。たとえば、サーバーが奇数の場合、:inventory_hostnameの最後の3文字が奇数であるか偶数であるかを検出

host: myhost-001.example.com server: myserver-003.example.com 

それが奇数でない場合は、それもなければならないので、私は別のサーバーを割り当てます:

host: myhost-002.example.com server: myserver-002.example.com 

任意のアイデア?

答えて

2

興味深い問題です。あなたは神社フィルタを使用してこれを行うことができます。

{{ 'myhost-002.example.com'|regex_replace('(myhost-)(?P<id>\d\d\d)(\.example\.com)', '\\g<id>')|int is divisibleby 2 }} 

のビットを説明するために、これを打破してみましょう:

'myhost-002.example.com' 

まず、私はホスト変数は、上記の形であると仮定します。

|regex_replace('(myhost-)(?P<id>\d\d\d)(\.example\.com)', '\\g<id>') 

私は上記の例では、私は3つの数字\d\d\dであることを前提とだけidパラメータを保ち、名前付きパラメータで正規表現を交換します。これは'002'を返します。

|int is divisibleby 2 

次に、上記の整数が2で割り切れて奇数か偶数かを調べます。

テスト:

ansible localhost -m debug -a "msg={{ 'myhost-002.example.com'|regex_replace('(myhost-)(?P<id>\d\d\d)(\.example\.com)', '\\g<id>')|int is divisibleby 2 }}" 

localhost | SUCCESS => { 
    "msg": true 
} 

便利なリンク:Ansible Jinja2 filters

関連する問題