Skip to content
Snippets Groups Projects
main.yaml 1.82 KiB
Newer Older
  • Learn to ignore specific revisions
  • istmxrein's avatar
    istmxrein committed
    # Configure Fail2Ban
    # Configure SSH with same port as fail2ban
    - name: Save ssh port
      set_fact:
        ansible_host_port: "{{ ansible_port }}"
    
    - name: Change ssh port to 22
      set_fact:
        ansible_port: 22
    
    - name: Install System Tools
      apt:
        pkg:
        - fail2ban
        state: latest
        update_cache: yes
        install_recommends: no
    
    - name: sshd configuration file update
      lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "^{{ item.key }}"
        line: "{{ item.key }} {{ item.value }}"
        validate: /usr/sbin/sshd -T -f %s
      with_items: 
        - {key: "PermitRootLogin", value: "no"}
        - {key: "PasswordAuthentication", value: "no"}
        - {key: "ClientAliveInterval", value: "300"}
        - {key: "ClientAliveCountMax", value: "1"}
        - {key: "AllowUsers", value: "{{ ansible_user }}"}
        - {key: "Port", value: "{{ ansible_host_port }}"}
        - {key: "MaxAuthTries", value: "2"}
        - {key: "AllowTcpForwarding", value: "no"}
        - {key: "X11Forwarding", value: "no"}
        - {key: "AllowAgentForwarding", value: "no"}
        - {key: "AuthorizedKeysFile", value: ".ssh/authorized_keys"}
    
    - name: Enable service fail2ban
      ansible.builtin.systemd:
        name: fail2ban
        enabled: yes
        state: started
    
    - name: copy fail2ban config
      copy:
        src: /etc/fail2ban/jail.conf
        dest: /etc/fail2ban/jail.local
        remote_src: true
    
    - name: fail2ban configuration file update
      lineinfile:
        path: "/etc/fail2ban/jail.local"
        firstmatch: true
        regexp: "^port.*=.*ssh$"
        line: "port = {{ ansible_host_port }}"
    
    - name: fail2ban configuration file update
      lineinfile:
        path: "/etc/fail2ban/jail.local"
        insertafter: |
          ^\[sshd\]
        line: "enabled = true"
    
    - name: Enable service fail2ban
      ansible.builtin.systemd:
        name: fail2ban
        enabled: yes
        state: restarted
    
    - name: Restart SSHD
      service:
        name: sshd
        state: restarted