muffinsk
muffinsk

Reputation: 1

Conditional statement for variables in Ansible 2.0

Is there a way to have a conditional statement for variables in Ansible 2.0?

There will be common variables (e.g. location, timezone, domain, lang, language, paper, time, etc.) in the $ROLES_PATH/vars/main.yml and will probably be called/used in the playbooks and/or Jinja2 templates as follows:

However, the values of the target_* variables will change automatically when the target machine's IP address belongs to one of the subnets stated in the if/else statement. Or maybe, the condition can be constructed with when the target machine belongs to the group (by location) from the inventory file.

Pseudocode of variables inside $ROLES_PATH/vars/main.yml

---
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

Is there a way to achieve the above objective in Ansible 2.0 as per best practices?

Upvotes: 0

Views: 395

Answers (1)

udondan
udondan

Reputation: 60059

I think best practice would be to simply use group vars for this.

Your question reads like you already have groups for regions. So let's assume you have a group europe, then you'd simply add a file group_vars/europe which contains all the vars:

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"

Upvotes: 1

Related Questions