--- # Optional CDN Update Playbook # Only runs when CDN_UPDATE=true is passed - name: Update CDN Configuration (Optional) hosts: web_servers become: true gather_facts: true vars: domain_name: "{{ DOMAIN_NAME | default('michaelschiemer.de') }}" cdn_enabled: "{{ CDN_UPDATE | default(false) | bool }}" nginx_conf_path: "/etc/nginx/sites-available/{{ domain_name }}" pre_tasks: - name: Check if CDN update is enabled debug: msg: "CDN update is {{ 'enabled' if cdn_enabled else 'disabled' }}" tags: always - name: Skip CDN tasks if not enabled meta: end_play when: not cdn_enabled tags: always tasks: - name: Check if Nginx configuration exists stat: path: "{{ nginx_conf_path }}" register: nginx_config_check tags: cdn - name: Fail if Nginx config not found fail: msg: "Nginx configuration not found at {{ nginx_conf_path }}" when: not nginx_config_check.stat.exists tags: cdn - name: Backup current Nginx configuration copy: src: "{{ nginx_conf_path }}" dest: "{{ nginx_conf_path }}.backup.{{ ansible_date_time.epoch }}" remote_src: true owner: root group: root mode: '0644' tags: cdn - name: Update Nginx configuration for CDN lineinfile: path: "{{ nginx_conf_path }}" regexp: '^\s*add_header\s+X-CDN-Cache' line: ' add_header X-CDN-Cache "ENABLED" always;' insertafter: '^\s*add_header\s+X-Frame-Options' backup: true notify: reload nginx tags: cdn - name: Add CDN cache headers blockinfile: path: "{{ nginx_conf_path }}" marker: "# {mark} CDN CACHE HEADERS" insertafter: "location ~ \\.(?:css|js|woff2?|svg|gif|ico|jpe?g|png)\\$ {" block: | expires 1y; add_header Cache-Control "public, immutable"; add_header X-CDN-Served "true"; backup: true notify: reload nginx tags: cdn - name: Validate Nginx configuration command: nginx -t register: nginx_test failed_when: nginx_test.rc != 0 tags: cdn - name: CDN configuration success debug: msg: - "CDN configuration updated successfully" - "Domain: {{ domain_name }}" - "Nginx config: {{ nginx_conf_path }}" tags: cdn handlers: - name: reload nginx systemd: name: nginx state: reloaded tags: cdn post_tasks: - name: Verify CDN headers are working uri: url: "https://{{ domain_name }}/favicon.ico" method: HEAD headers: User-Agent: "Mozilla/5.0 (Ansible CDN Check)" return_content: false status_code: [200, 404] # 404 is ok for favicon test register: cdn_test tags: cdn - name: CDN verification results debug: msg: - "CDN Test Results:" - "Status: {{ cdn_test.status }}" - "Cache-Control: {{ cdn_test.cache_control | default('Not set') }}" - "X-CDN-Served: {{ cdn_test.x_cdn_served | default('Not set') }}" when: cdn_test is defined tags: cdn