--- # UFW Firewall Configuration - name: Reset UFW to defaults ufw: state: reset when: ufw_reset | bool tags: - firewall - reset - name: Set UFW default policies ufw: policy: "{{ item.policy }}" direction: "{{ item.direction }}" loop: - { policy: "{{ ufw_default_incoming }}", direction: incoming } - { policy: "{{ ufw_default_outgoing }}", direction: outgoing } - { policy: "{{ ufw_default_forward }}", direction: routed } tags: - firewall - policy - name: Configure UFW logging ufw: logging: "{{ ufw_logging }}" tags: - firewall - logging - name: Allow SSH before enabling firewall ufw: rule: allow port: "{{ ssh_port }}" proto: tcp comment: "SSH Access - Priority" tags: - firewall - ssh - name: Configure UFW rules ufw: rule: "{{ item.rule }}" port: "{{ item.port | default(omit) }}" proto: "{{ item.proto | default(omit) }}" src: "{{ item.src | default(omit) }}" dest: "{{ item.dest | default(omit) }}" interface: "{{ item.interface | default(omit) }}" direction: "{{ item.direction | default(omit) }}" comment: "{{ item.comment | default(omit) }}" loop: "{{ ufw_rules }}" tags: - firewall - rules - name: Add environment-specific firewall rules ufw: rule: "{{ item.rule }}" port: "{{ item.port | default(omit) }}" proto: "{{ item.proto | default(omit) }}" src: "{{ item.src | default(omit) }}" comment: "{{ item.comment | default(omit) }}" loop: "{{ environment_specific_rules | default([]) }}" tags: - firewall - rules - environment - name: Configure production-specific strict rules ufw: rule: "{{ item.rule }}" port: "{{ item.port | default(omit) }}" proto: "{{ item.proto | default(omit) }}" src: "{{ item.src | default(omit) }}" comment: "{{ item.comment | default(omit) }}" loop: - rule: deny port: "3306" proto: tcp comment: "Block external MySQL access" - rule: deny port: "6379" proto: tcp comment: "Block external Redis access" - rule: deny port: "9090" proto: tcp comment: "Block external Prometheus access" - rule: limit port: "{{ ssh_port }}" proto: tcp comment: "Rate limit SSH connections" when: environment == 'production' and firewall_strict_mode | bool tags: - firewall - production - strict - name: Allow Docker container communication ufw: rule: allow interface: docker0 direction: in comment: "Docker container communication" ignore_errors: true # Docker may not be installed yet tags: - firewall - docker - name: Allow established and related connections ufw: rule: allow direction: in interface: any from_ip: any to_ip: any comment: "Allow established connections" tags: - firewall - established - name: Enable UFW firewall ufw: state: enabled tags: - firewall - enable - name: Check UFW status command: ufw status verbose register: ufw_status changed_when: false tags: - firewall - status - name: Display UFW status debug: var: ufw_status.stdout_lines tags: - firewall - status