使用Ansible进行服务器安全加固是一个很好的选择,因为它可以自动化执行许多安全任务,减少人为错误,并确保一致性。以下是一些基本步骤和示例,帮助你使用Ansible进行服务器安全加固:
首先,确保你已经在控制节点上安装了Ansible。你可以使用pip来安装:
pip install ansible
创建一个Ansible playbook文件(例如secure_servers.yml),并在其中定义你的安全任务。
---
- name: Secure servers
hosts: all
become: yes
vars:
ansible_ssh_user: "root"
ansible_ssh_private_key_file: "/path/to/your/private/key"
tasks:
- name: Update apt cache
ansible.builtin.apt:
update_cache: yes
cache_valid_time: 3600
- name: Install security updates
ansible.builtin.apt:
name: "*"
state: latest
update_cache: yes
- name: Ensure fail2ban is installed and running
ansible.builtin.package:
name: fail2ban
state: present
become: yes
notify: restart fail2ban
- name: Configure fail2ban
ansible.builtin.template:
src: /path/to/your/jail.local.j2
dest: /etc/fail2ban/jail.local
notify: restart fail2ban
- name: Ensure SSH keys are used for authentication
ansible.builtin.lineinfile:
path: /etc/ssh/sshd_config
regexp: '^#?PasswordAuthentication'
line: 'PasswordAuthentication no'
create: yes
notify: restart sshd
- name: Ensure SSH root login is disabled
ansible.builtin.lineinfile:
path: /etc/ssh/sshd_config
regexp: '^#?PermitRootLogin'
line: 'PermitRootLogin no'
create: yes
notify: restart sshd
- name: Ensure only necessary services are running
ansible.builtin.service:
name: "{{ item }}"
state: stopped
enabled: no
loop:
- telnet.socket
- http.socket
- name: Ensure firewall is enabled and configured
ansible.builtin.ufw:
state: enabled
policy: deny
default: deny
rules:
- rule: allow
port: ssh
proto: tcp
- rule: allow
port: http
proto: tcp
- rule: allow
port: https
proto: tcp
handlers:
- name: restart fail2ban
ansible.builtin.service:
name: fail2ban
state: restarted
- name: restart sshd
ansible.builtin.service:
name: sshd
state: restarted
创建一个Jinja2模板文件(例如jail.local.j2),用于配置fail2ban。
jail.local.j2)[DEFAULT]
bantime = 600
maxretry = 3
[ssh]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
使用以下命令运行你的playbook:
ansible-playbook -i inventory_file secure_servers.yml
确保你有一个inventory_file文件,其中列出了你要加固的服务器。
运行playbook后,检查服务器上的安全设置是否已按预期更改。你可以手动检查或编写额外的Ansible任务来验证这些更改。
通过这些步骤,你可以使用Ansible自动化地进行服务器安全加固,确保所有服务器都遵循相同的安全策略。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。