So recently I have gotten my head into Ansible and as I figure stuff out I will share my findings.
This time my find is jinja2 conditionals used to include vars and template if they exist.
So I’m building a dynamic role to configure virtual hosts on a web server. The role gets called with a single parameter like this:
- { role: vhost, vhost_name: awesomecoolwebsite.com }
And this is the essence of that role which include some vars specific to the web site and either use a common config template or a custom one if it exists (forgive WordPress formatting):
--- - assert: that: "vhost_name is defined" - name: Detect if we have custom vhost config set_fact: vhost_template_file: "vhost.d/{{ vhost_name }}.conf.j2" when: (role_path + '/templates/vhost.d/' + vhost_name + '.conf.j2') | is_file - name: Load application config include_vars: "{{ vhost_name }}.yml" when: (role_path + '/vars/' + vhost_name + '.yml') | is_file - name: Create vhost directory file: path: "{{ vhost_base }}/{{ vhost_name }}" state: directory owner: root group: apache mode: 0750 - name: Configure vhost template: src: "{{ vhost_template_file|default('vhost.conf.j2') }}" dest: "/etc/httpd/vhost.d/{{ vhost_name }}.conf" notify: Reload webserver