How to load variables Dynamically in Ansible

Task

  • Create a single role for configuring the webserver
  • Must be able to configure more than one distributions
name =  webserveruser = ec2_user
name = webserveruser = ubuntu

Task File

---
# tasks file for dynamic_var
- include_vars: "{{ansible_distribution}}.yml"
- name: installing http webserver
package:
name: "{{ package_name }}"
state: present
- name: starting service
service:
name: "{{service_name}}"
state: started
- name: copying templates
template:
src: "{{ansible_distribution}}.html.j2"
dest: "/var/www/html/index.html"
notify: restart webserver
ansible all -m setup -a "filter=ansible_distibution"

Var Files

RedHat.yml

package_name: httpd
service_name: httpd

Ubuntu.yml

package_name: apache2
service_name: apache2

Templates

RedHat.yml

Hello from {{ ansible_distribution}}

Ubuntu.yml

Hello from {{ ansible_distribution}}

Playbook

- hosts: tag_name_webserver
tasks:
- name: config webserver
include_role:
name: ../roles/dynamic_var
ansible-playbook test.yml

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store