假设我有一台服务器,我想执行以下操作:
- 将 SSH 端口更改为 33333
- 禁用root登录
- 禁用密码登录,只允许基于 key 的身份验证
我对执行这些任务的说明不感兴趣。网上有很多东西。
我的问题是关于最佳实践。
这里有几个问题:
- 当我更改剧本的默认 SSH 端口时,我无法在同一主机上再次运行同一剧本。这是因为我需要在 playbook 运行一次后更改 inventory 文件中的 SSH 端口参数。
- 与上面类似,我使用 root 登录系统,一旦 root 登录被禁用,我需要在某处更改“remote_user”参数。
- 禁用密码登录会导致与上述类似的问题。
如果我的方法有一些基本问题,我将不胜感激。
最佳答案
就像@mwp 一样,我有 playbook 来初始化 ansible。它创建特殊用户(名为'ansible)来连接到服务器,将它们添加到 sudoers。该剧本尽可能精简。
---
# This playbook for prepare server for ansible.
- name: add role ansible_init
hosts: '{{ target }}'
remote_user: root
roles:
- ansible_init
'ansible_init' 的角色是:
---
- name: install ansible client library
yum: name={{ item }} state=latest
with_items:
- libselinux-python
- policycoreutils-python
- name: useradd ansible
user:
name={{ ansible_init.ansible_user.login }}
password={{ ansible_init.ansible_user.password }}
- name: add default ssh key for ansible user
authorized_key:
user={{ ansible_init.ansible_user.login }}
key="{{ lookup('file', '{{ ansible_init.ansible_user.ssh_key_file }}') }}"
state=present
- name: nopasswd sudo for ansible user
lineinfile: "dest=/etc/sudoers state=present regexp='^{{ ansible_init.ansible_user.login }}' line='{{ ansible_init.ansible_user.login }} ALL=(ALL) NOPASSWD: ALL'"
作为 ansible 用户执行的其他操作(remote_user = ansible
in ansible.cfg)。
设置服务器(邮件、数据库、Web 等)的一些剧本包括必要的角色、在普通剧本中分开的普通步骤(包括在第一步中)。 Common playbook 设置 sshd、firewalld、fail2ban、安装额外的 repos、服务器的 known_hosts 等。
典型的剧本如下:
# This playbook deploys 'webserver' server.
- include: init_server.yml
- name: deploy 'webserver'
hosts: '{{ target | default("webservers") }}'
become: true
become_user: root
roles:
- git
- nginx
...........
init_server.yml 从未直接调用,仅从具体的剧本中调用。
关于ssh - 使用 Ansible 锁定 SSH 的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39175623/