Search code examples
variablesansibleconditional-statementscase

Defining multiple cases for an Ansible variable based on multiple conditions


I have this variable here, set in a .yaml variables file

patch_plan: 'foo-{{ patch_plan_week_and_day }}-bar'

I want my patch_plan_week_and_day variable to be set dynamically, based on role and environment which are 2 other variables set elsewhere (doesn't matter now) outside this variables file.

For instance, I will explain 3 cases:

  • If role = 'master' and environment = 'srvb' then patch_plan_week_and_day = 'Week1_Monday' and thus the end result of patch_plan = 'foo-Week1_Monday-bar'.
  • If role != 'master' and environment = 'srvb' then patch_plan_week_and_day = 'Week1_Tuesday' and thus the end result of patch_plan = 'foo-Week1_Tuesday-bar'
  • If role = 'slave' and environment = 'pro' then patch_plan_week_and_day = 'Week3_Wednesday' and hus the end result of patch_plan = 'foo-Week3_Wednesday-bar'

This is the idea of the code:

patch_plan: 'foo-{{ patch_plan_week_and_day }}-bar'

# Patch Plans
## I want something like this:

# case 1
patch_plan_week_and_day: Week1_Monday
when: role == 'master' and environment == 'srvb'

# case 2
patch_plan_week_and_day: Week1_Tuesday
when: role != 'master' and environment == 'srvb'

# case 3
patch_plan_week_and_day: Week3_Wednesday
when: role == 'slave' and environment == 'pro'

I have 14 cases in total.


Solution

  • At last, this is what fixed it, thank you everyone

    patch_plan: 'foo-{{ patch_plan_week_and_day[environment][role] }}-bar'
    
    srvb:
      master: Week1_Monday
      slave: Week1_Tuesday
    pre:
      master: Week1_Sunday
      slave: Week1_Friday
    pro:
      master: Week1_Thursday
      slave: Week1_Wednesday