Jninja Jninja - 3 months ago 10
YAML Question

Registering Each Host Specific Value from Dictionary

We wanted to have a single playbook for all the deployments and the multiple hosts will be looped in. Ansible calls will be made from Jenkins pipeline by passing in the environments, for example dev6 and dev8

env1=dev6
env2=dev8


Pipeline Call:

ansible-playbook -i hosts --limit $env1:$env2 deploy_test.yml -e "env1={{$env1}} env2={{$env2}}"


I defined all the host specific variables (dev1,dev2......PERF8 etc.) in single file so it is easy to manage and maintain,

dev6:
- { deploy_domain: "Dev6Domain",
WL_Admin: "DEV6WLAdmin",
WL_Managed: "DEV6Managed" }

dev7:
- { deploy_domain: "Dev7Domain",
WL_Admin: "Dev7WLAdmin",
WL_Managed: "Dev7Managed" }


Playbook "Deploy_test.yml"

- hosts: all
vars_files:
- host_variables.yml
tasks:

- debug: msg='Target Domain is "{{ item[0].deploy_domain }}"'
with_nested:
- "{{ env1 }}"
- "{{ env2 }}"


The env1 and env2 values are being read from jenkins, no issues there

Problem-1: When the playbook runs on dev6 first, it takes dev8 values as well since it is defined under with_nested items.

Problem-2: How do I register the values specific to every environment?
for example, down the playbook when I say, mkdir /tmp/{{deploy_domain}, I need seperate values for dev6 and dev8.

Answer

Here is an example how you can read name-specific variable for every host:

hosts:

[dev6]
box1
[dev8]
box2

host_variables.yml:

dev6:
  deploy_domain: "Dev6Domain"
  WL_Admin: "DEV6WLAdmin"
  WL_Managed: "DEV6Managed"

dev8:
  deploy_domain: "Dev8Domain"
  WL_Admin: "Dev8WLAdmin"
  WL_Managed: "Dev8Managed"

I stripped out list level from original host_variables.yml, because it is not necessary in this case, there is always single element in the list.

deploy_test.yml:

- hosts: all
  tasks:
    - include_vars: host_variables.yml
    - set_fact:
        my_env: "{{ hostvars[inventory_hostname][group_names[0]] }}"
    - debug: msg="My domain = {{ my_env.deploy_domain }}"

execution: ansible-playbook -i hosts --limit $env1:$env2 deploy_test.yml

This will execute deploy_test.yml for all hosts in groups set in env vars env1 and env2.
In the begining of playbook, we load everything from host_variables.yml as host facts.
And with set_fact extract variable named after current host's group name as my_env.
So box1 will have dev6 as my_env and box2 will have dev8.