有没有办法在Ansible 2.0中为变量设置条件语句?
会有常见变量(例如位置,时区,域, lang ,语言 $ROLES_PATH/vars/main.yml
中, paper ,时间等),可能会在剧本中调用/使用和/或Jinja2模板如下:
'{{ target_location }}'
'{{ target_timezone }}'
'{{ target_domain }}'
'{{ target_lang }}'
'{{ target_language }}'
'{{ target_paper }}'
'{{ target_time }}'
但是,当目标机器的IP地址属于if / else语句中声明的子网之一时,target_*
变量的值将自动更改。或者,当目标计算机属于清单文件中的组(按位置)时,可以使用构建条件。
---
target_location: '{{ location }}'
target_timezone: '{{ timezone }}'
target_domain: '{{ domain }}'
target_lang: '{{ lang }}'
target_language: '{{ language }}'
target_paper: '{{ paper }}'
target_time: '{{ time }}'
if {{ ansible_eth0.ipv4.address }} belongs to 192.168.1.0/24 or 172.16.1.0/24 or 10.10.1.0/24 then
location: "London"
timezone: "Europe/London"
domain: "uk.example.com"
lang: "en_GB.UTF-8"
language: "en_GB:en"
paper: "en_GB.UTF-8"
time: "en_GB.UTF-8"
elif {{ ansible_eth0.ipv4.address }} belongs to 192.168.2.0/24 or 172.16.2.0/24 or 10.10.2.0/24 then
location: "Tokyo"
timezone: "Asia/Tokyo"
domain: "jp.example.com"
lang: "ja_JP.UTF-8"
language: "ja_JP"
paper: "ja_JP.UTF-8"
time: "ja_JP.UTF-8"
elif {{ ansible_eth0.ipv4.address }} belongs to 192.168.3.0/24 or 172.16.3.0/24 or 10.10.3.0/24 then
location: "Sydney"
timezone: "Australia/Sydney"
domain: "au.example.com"
lang: "en_AU.UTF-8"
language: "en_AU:en"
paper: "en_AU.UTF-8"
time: "en_AU.UTF-8"
else
location: "Los Angeles"
timezone: "America/Los_Angeles"
domain: "example.com"
lang: "en_US.UTF-8"
language: "en_US:en"
paper: "en_US.UTF-8"
time: "en_US.UTF-8"
fi
根据最佳实践,有没有办法在Ansible 2.0中实现上述目标?
答案 0 :(得分:1)
我认为最佳做法是简单地使用群变量。
您的问题就像您已经拥有地区群组一样。因此,假设您有一个组europe
,那么您只需添加一个包含所有变量的文件group_vars/europe
:
target_location: "London"
target_timezone: "Europe/London"
target_domain: "uk.example.com"
target_lang: "en_GB.UTF-8"
target_language: "en_GB:en"
target_paper: "en_GB.UTF-8"
target_time: "en_GB.UTF-8"