Created
February 8, 2023 09:35
-
-
Save mrhalix/fc471d62936cb450d1bfa22a81c66d4b to your computer and use it in GitHub Desktop.
Ansible to add a new Apache vhost
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<VirtualHost *:{{ http_port }}> | |
ServerAdmin webmaster@localhost | |
ServerName {{ http_host }} | |
ServerAlias www.{{ http_host }} | |
ErrorLog ${APACHE_LOG_DIR}/error.log | |
CustomLog ${APACHE_LOG_DIR}/access.log combined | |
DocumentRoot "/var/www/{{ http_host }}" | |
</VirtualHost> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
- name: Setup new apache2 vhost | |
hosts: all | |
become: true | |
vars: | |
# user to chown related directories (most of times its www-data) | |
app_user: "www-data" | |
# domain name of new host | |
http_host: "amin.com" | |
# desired name for vhost configuration name | |
config_name: "amin.com.conf" | |
# this port is shared between all hosts. | |
http_port: "80" | |
# disable default apache2 webpage. | |
disable_default: false | |
tasks: | |
- name: Check if Apache2 is installed | |
command: apache2 -v | |
register: apache2_check | |
- name: Install Apache2 | |
apt: | |
name: apache2 | |
state: latest | |
update_cache: true | |
when: apache2_check.rc != 0 | |
- name: Create domain root | |
ansible.builtin.file: | |
path: "/var/www/{{ http_host }}" | |
state: directory | |
owner: "{{ app_user }}" | |
mode: '0755' | |
- name: Create simple html webpage | |
ansible.builtin.copy: | |
dest: "/var/www/{{ http_host }}/index.html" | |
content: | | |
Custom Web Page | |
- name: Create vhost configuration | |
ansible.builtin.template: | |
src: "templates/apache.conf.j2" | |
dest: "/etc/apache2/sites-available/{{ config_name }}" | |
- name: Enable vhost | |
ansible.builtin.command: "/usr/sbin/a2ensite {{ config_name }}" | |
notify: Restart apache service | |
- name: Disable default apache webpage | |
ansible.builtin.command: "/usr/sbin/a2dissite 000-default.conf" | |
when: disable_default | |
notify: Restart apache service | |
- name: Allow firewall | |
community.general.ufw: | |
rule: allow | |
port: "{{ http_port }}" | |
proto: tcp | |
handlers: | |
- name: Restart apache service | |
ansible.builtin.service: | |
name: apache2 | |
state: reloaded |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment