Skip to content

Commit 2d39e21

Browse files
authored
Feature/template handling (#6)
* detect vhost templates on controler instance * update vhost template handling
1 parent 5efd4a0 commit 2d39e21

File tree

8 files changed

+131
-64
lines changed

8 files changed

+131
-64
lines changed

filter_plugins/nginx.py

+42-18
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
from __future__ import (absolute_import, division, print_function)
77
__metaclass__ = type
88

9-
# import json
9+
import os
10+
import json
11+
import hashlib
1012

1113
from ansible.utils.display import Display
1214

@@ -23,10 +25,11 @@ def filters(self):
2325
'vhost_directory': self.vhost_directory,
2426
'vhost_listen': self.vhost_listen,
2527
'vhost_templates': self.vhost_templates,
28+
'vhost_templates_checksum': self.vhost_templates_checksum,
29+
'vhost_templates_validate': self.vhost_templates_validate,
2630
'http_vhosts': self.http_vhosts,
2731
'changed_vhosts': self.changed_vhosts,
2832
'certificate_existing': self.certificate_existing,
29-
'validate_listener': self.validate_listener,
3033
}
3134

3235
def vhost_directory(self, data, directory, state="present"):
@@ -58,7 +61,6 @@ def vhost_listen(self, data, port, default):
5861
used in jinja_macros.j2
5962
"""
6063
# display.v(f"vhost_listen({port}, {default})")
61-
6264
result = []
6365

6466
if (isinstance(port, str) or isinstance(port, int)):
@@ -91,6 +93,43 @@ def vhost_templates(self, data, defaults):
9193
display.v(f" = result {result}")
9294
return result
9395

96+
def vhost_templates_checksum(self, data):
97+
"""
98+
"""
99+
result = {}
100+
101+
for tpl in data:
102+
if os.path.exists(tpl):
103+
with open(tpl,"rb") as f:
104+
bytes = f.read()
105+
readable_hash = hashlib.sha256(bytes).hexdigest()
106+
result[tpl] = readable_hash
107+
108+
# display.v(f" = result {result}")
109+
return result
110+
111+
def vhost_templates_validate(self, data, ansible_local):
112+
"""
113+
"""
114+
result = {}
115+
changed_templates = {}
116+
117+
for tpl, checksum in data.items():
118+
local_checksum = ansible_local.get(tpl, "-")
119+
120+
if checksum != local_checksum:
121+
changed_templates[tpl] = checksum
122+
123+
changed = len(changed_templates) > 0
124+
125+
result = {
126+
"changed": changed,
127+
"templates": changed_templates
128+
}
129+
130+
# display.v(f" = result {result}")
131+
return result
132+
94133
def http_vhosts(self, data, tls=False):
95134
"""
96135
"""
@@ -142,23 +181,8 @@ def certificate_existing(self, data):
142181
returns a list of vhosts where the certificate exists.
143182
"""
144183
# display.v(f"certificate_existing({data})")
145-
146184
if isinstance(data, list):
147185
data = [x for x in data if x.get("ssl", {}).get("state") == "present"]
148186

149187
# display.v(f" = result {data}")
150188
return data
151-
152-
def validate_listener(self, data, replace='(quic|reuseport)'):
153-
"""
154-
"""
155-
result = []
156-
157-
if isinstance(data, str):
158-
result.append(re.sub(find, replace, s).strip())
159-
if isinstance(data, list):
160-
for i in data:
161-
result.append(re.sub(find, replace, i).strip())
162-
163-
display.v(f" = {result}")
164-
return result

library/nginx_vhosts.py

+20-8
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def create_vhost(self, data):
114114

115115
# state = data.get("state", "present")
116116
enabled = data.get("enabled", True)
117-
template = data.get("template", None)
117+
template_file = data.get("template", None)
118118
tls = data.get("ssl", None)
119119
tls_enabled = False
120120

@@ -133,16 +133,28 @@ def create_vhost(self, data):
133133
else:
134134
return True, False, "[ERROR] TLS certificate missing"
135135

136-
if not template:
136+
if not template_file:
137137
if tls_enabled:
138-
template = self.default_https_template
138+
template_file = self.default_https_template
139139
else:
140-
template = self.default_http_template
140+
template_file = self.default_http_template
141141

142-
template = os.path.join(self.template_path, template)
142+
template = os.path.join(self.template_path, template_file)
143+
144+
self.module.log(msg=f"- template {template}")
145+
146+
if not os.path.exists(template):
147+
"""
148+
"""
149+
_error = True
150+
_changed = False
151+
_msg = f"The template {template_file} does not exist."
152+
return _error, _changed, _msg
143153

144154
file_available, file_enabled, file_temporary = self.__file_names(data)
145155

156+
self.module.log(msg=f"- file_available {file_available} - {file_enabled} - {file_temporary}")
157+
146158
vhost_data = self.render_template(template, data)
147159

148160
changed, msg = self.save_vhost(file_available, file_temporary, vhost_data)
@@ -337,9 +349,9 @@ def __file_names(self, data):
337349
available = os.path.join(self.site_available, file_name)
338350
temporary = os.path.join(self.tmp_directory, file_name)
339351

340-
# self.module.log(msg=f" enabled {enabled}")
341-
# self.module.log(msg=f" available {available}")
342-
# self.module.log(msg=f" temporary {temporary}")
352+
self.module.log(msg=f" enabled {enabled}")
353+
self.module.log(msg=f" available {available}")
354+
self.module.log(msg=f" temporary {temporary}")
343355

344356
return available, enabled, temporary
345357

molecule/configured/group_vars/all/nginx_vhosts.yml

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ nginx_vhosts:
1010

1111
- name: nginx-status
1212
filename: 00-status.conf
13+
template: vhost_status.j2
1314
state: present # default: present
1415
enabled: true # default: true
1516
# domain(s)

molecule/configured/molecule.yml

+2-2
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ platforms:
2828
- /run
2929
- /tmp
3030
published_ports:
31-
- 80:80
32-
- 443:443
31+
- 8080:80
32+
- 8443:443
3333

3434
provisioner:
3535
name: ansible
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#jinja2: trim_blocks: True, lstrip_blocks: True
2+
# {{ ansible_managed }}
3+
4+
{% import 'jinja_macros.j2' as tpl with context %}
5+
{% set data = item %}
6+
{% set _server_name = data.domains | default('_') %}
7+
{% set _upstreams = data.upstreams | default({}) %}
8+
{% set _logfiles = data.logfiles | default({}) %}
9+
{% set _locations = data.locations | default([]) %}
10+
{% set _listen = data.listen | default('80') %}
11+
12+
server {
13+
{{ tpl.vhost_server_name(_server_name) }}
14+
{{ tpl.vhost_listen(_listen) | indent(0, first=False) }}
15+
{{ tpl.vhost_logfile(_logfiles, item.name) | indent(0, first=False) }}
16+
{% if data.includes is defined %}
17+
{% for inc in data.includes %}
18+
include {{ inc }};
19+
{% endfor %}
20+
{%- endif -%}
21+
{% if data.root is defined %}
22+
root {{ data.root }};
23+
{% endif %}
24+
25+
{% if data.index is defined %}
26+
index
27+
{{ data.index | join('\n') | indent(4, first=False) }};
28+
{% endif %}
29+
30+
{{ tpl.vhost_locations(_locations) | indent(0, first=False) -}}
31+
}

tasks/vhosts/prepare.yml

+33-34
Original file line numberDiff line numberDiff line change
@@ -13,23 +13,23 @@
1313
nginx_vhosts_https: "{{ nginx_vhosts | http_vhosts(tls=True) }}"
1414
nginx_templates: "{{ nginx_vhosts | vhost_templates(defaults=nginx_vhost_templates) }}"
1515

16-
- name: find templates archive on ansible controller
17-
become: false
18-
delegate_to: localhost
19-
ansible.builtin.stat:
20-
path: "{{ nginx_local_tmp_directory }}/templates/{{ ansible_fqdn }}_templates.tgz"
21-
get_md5: false
22-
get_mime: false
23-
get_attributes: false
24-
register: nginx_template_ansible_controller
16+
- name: detect vhost templates
17+
ansible.builtin.set_fact:
18+
_nginx_templates: "{{ query('bodsch.core.file_glob', '.j2') }}"
19+
vars:
20+
search_path:
21+
- ".."
22+
- "../.."
23+
search_regex: "(vhost|jinja_macros).*"
24+
25+
- name: define vhosts templates checksum
26+
ansible.builtin.set_fact:
27+
nginx_templates_checksums: "{{ _nginx_templates | default([]) | vhost_templates_checksum }}"
28+
# nginx_templates_checksum: "{{ _nginx_templates | default('-') | hash('sha256') }}"
2529

26-
- name: find templates archive on destination system
27-
ansible.builtin.stat:
28-
path: "{{ nginx_remote_tmp_directory }}/{{ ansible_fqdn }}/templates.tgz"
29-
get_md5: false
30-
get_mime: false
31-
get_attributes: false
32-
register: nginx_template_remote_archive
30+
- name: validate vhost template checksums
31+
ansible.builtin.set_fact:
32+
nginx_templates_changed: "{{ nginx_templates_checksums | vhost_templates_validate(ansible_local.nginx.templates_checksums | default({})) }}"
3333

3434
- name: find templates directory on destination system
3535
ansible.builtin.stat:
@@ -39,26 +39,10 @@
3939
get_attributes: false
4040
register: nginx_template_remote_directory
4141

42-
# - name: templates
43-
# ansible.builtin.debug:
44-
# msg:
45-
# - "{{ nginx_template_ansible_controller.stat.checksum | default('-') }}"
46-
# - "{{ nginx_template_remote_archive.stat.checksum | default('+') }}"
47-
# - "{{ nginx_template_remote_directory.stat }}"
48-
4942
- name: templates for remote system
5043
when:
51-
- not nginx_template_remote_archive.stat.exists or
52-
nginx_template_remote_archive.stat.checksum | default('+') != nginx_template_ansible_controller.stat.checksum | default('-')
44+
- nginx_templates_changed.changed
5345
block:
54-
- name: detect vhost templates
55-
ansible.builtin.set_fact:
56-
_nginx_templates: "{{ query('bodsch.core.file_glob', '.j2') }}"
57-
vars:
58-
search_path:
59-
- ".."
60-
- "../.."
61-
search_regex: "(vhost|jinja_macros).*"
6246

6347
- name: transfer vhost templates to destination instance
6448
tags:
@@ -121,16 +105,31 @@
121105
state: absent
122106
path: "{{ nginx_remote_tmp_directory }}/{{ ansible_fqdn }}"
123107

108+
- name: find templates archive on destination system
109+
ansible.builtin.stat:
110+
path: "{{ nginx_remote_tmp_directory }}/{{ ansible_fqdn }}/templates.tgz"
111+
get_md5: false
112+
get_mime: false
113+
get_attributes: false
114+
register: nginx_template_remote_archive
115+
124116
- name: extract {{ ansible_fqdn }}/templates.tgz
125117
ansible.builtin.unarchive:
126118
src: "{{ nginx_remote_tmp_directory }}/{{ ansible_fqdn }}/templates.tgz"
127119
dest: "{{ nginx_remote_tmp_directory }}/"
128120
remote_src: true
129121
when:
130122
- not nginx_template_remote_archive.stat.exists or
131-
nginx_template_remote_archive.stat.checksum | default('+') != nginx_template_ansible_controller.stat.checksum | default('-') or
123+
nginx_templates_changed.changed or
132124
not nginx_template_remote_directory.stat.isdir
133125

126+
- name: create custom fact file
127+
bodsch.core.facts:
128+
name: nginx
129+
facts:
130+
templates: "{{ _nginx_templates }}"
131+
templates_checksums: "{{ nginx_templates_checksums }}"
132+
134133
- name: ensure vhosts root path exists
135134
ansible.builtin.file:
136135
path: "{{ item }}"

templates/vhosts/vhost_http.conf.j2

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#jinja2: trim_blocks: True, rstrip_blocks: True, lstrip_blocks: True
1+
#jinja2: trim_blocks: True, lstrip_blocks: True
22
# {{ ansible_managed }}
33

44
{% import 'jinja_macros.j2' as tpl with context %}

templates/vhosts/vhost_https.conf.j2

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#jinja2: trim_blocks: True, rstrip_blocks: True, lstrip_blocks: True
1+
#jinja2: trim_blocks: True, lstrip_blocks: True
22
# {{ ansible_managed }}
33

44
{% import 'jinja_macros.j2' as tpl with context %}

0 commit comments

Comments
 (0)