Skip to content

Instantly share code, notes, and snippets.

@iAugur
Last active June 23, 2023 07:45
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iAugur/6d846db121ca5d70ae40 to your computer and use it in GitHub Desktop.
Save iAugur/6d846db121ca5d70ae40 to your computer and use it in GitHub Desktop.
Testing Apache configuration with Ansible templates
---
# create vhost for site
- name: Apache | Create vhost for site
template:
src: vhost.conf.j2
dest: "{{ apache_vhost_available }}/{{ vhost_name }}.conf"
mode: 0644
owner: root
group: root
# validate: 'apachectl -t -f %s' - this fails
sudo: true
register: vhost_updated
tags:
- apache
# set a fact so we can pass the file path to the test template
- name: Set fact for config to test
set_fact:
apache_conf_to_test: "{{ apache_vhost_available }}/{{ vhost_name }}.conf"
# create a test configuration file that links in all of the required config
- name: Apache | test Updated hosts
template:
src: config-test.conf.j2
dest: "/tmp/config-test.conf"
mode: 0644
owner: root
group: root
validate: 'apachectl -t -f %s'
register: apache_result
when: vhost_updated.changed
ignore_errors: yes
sudo: true
tags:
- apache
# if the config test succeeds we can put the new vhost live
- name: Apache | enable host
file:
src: "{{ apache_vhost_available }}/{{ vhost_name }}.conf"
dest: "{{ apache_vhost_enabled }}/{{ vhost_name }}.conf"
state: link
when: apache_result|success
sudo: true
notify:
- restart apache
- name: Clear out test file
file:
path: "/tmp/config-test.conf"
state: absent
sudo: true
when: apache_result|success
- name: Apache | enable host success
fail: msg="Apache configuration is invalid. Please check before re-running the playbook."
when: apache_result|failed
tags: [apache]
#{{ ansible_managed }}
# A temp config file to test Apache configuration
ErrorLog /var/log/apache2/error_log
Include {{ apache_conf_enabled }}
Include {{ apache_mods_enabled }}/*.conf
Include {{ apache_mods_enabled }}/*.load
Include {{ apache_conf_to_test }}
# Some vars set in ./default/main.yml or your host vars:
# these may vary depending on your Apache version and OS
apache_vhost_available: /etc/apache2/sites-available
vhost_name: your site vhost name (e.g. my.example.site)
# apache_conf_available: /etc/apache2/conf_enabled or /etc/apache2/conf.d or /etc/httpd/conf.d etc
apache_conf_available: /etc/apache2/conf_enabled
#apache_mods_enabled: /etc/apache2/mods_enabled or /etc/httpd/mods_enabled
apache_mods_enabled: /etc/apache2/mods_enabled
#apache_conf_to_test: set by the task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment