Ansible 更新 sshd 配置文件

Gau*_*gar 2 unix ssh ansible

我正在编写一个 Ansible play,以在 100 多个 Unix 服务器中自动创建新用户。我已经得到了创建用户并分配密码的部分。但我们的组织强化策略要求,每当添加新用户时,必须在 sshd_config 文件的“AllowUsers”参数中更新用户名。我是 Ansible 的新手,不知道如何完成这项工作。

这是 sshd_config 文件的“AllowUsers”部分。

AllowUsers root user1 user2 user2
Run Code Online (Sandbox Code Playgroud)

添加新用户“testuser”后应该是这样

AllowUsers root user1 user2 testuser
Run Code Online (Sandbox Code Playgroud)

Mic*_*ael 7

我搜索了如果用户已在列表中则不会执行任何操作的解决方案。这就是它在 Ansible 中的工作方式。我的解决方案首先搜索用户,只有当用户不在列表中时才会添加。

tasks:
- name: Check if bamboo user already is in SSHD AllowUsers list
  command: grep -P '^[ \t]*AllowUsers[ \t]+([-\w ]+[ \t]+)*bamboo([ \t]+.+)*$' /etc/ssh/sshd_config
  register: allow_users_exists
  changed_when: no
  ignore_errors: yes

- name: Allow bamboo user SSH login
  lineinfile:
    regexp: ^[ \t]*AllowUsers([ \t]+.*)$
    line: AllowUsers bamboo\1
    dest: /etc/ssh/sshd_config
    backrefs: yes
    validate: sshd -t -f %s
  when: allow_users_exists.rc != 0
  notify:
    - reload sshd

handlers:
- name: reload sshd
  service:
    name: sshd
    state: reloaded
Run Code Online (Sandbox Code Playgroud)

在这种特殊情况下,我正在搜索静态用户“bamboo”。您可以使用变量来代替,如下所示:

command: grep -P '^[ \t]*AllowUsers[ \t]+([-\w ]+[ \t]+)*{{ username | regex_escape() }}([ \t]+.+)*$' /etc/ssh/sshd_config
Run Code Online (Sandbox Code Playgroud)

line: AllowUsers {{ username }}\1
Run Code Online (Sandbox Code Playgroud)

结果

在:

AllowUsers ubuntu #sdfd
Run Code Online (Sandbox Code Playgroud)

出去:

AllowUsers bamboo ubuntu #sdfd
Run Code Online (Sandbox Code Playgroud)

在:

AllowUsers ubuntu
Run Code Online (Sandbox Code Playgroud)

出去:

AllowUsers bamboo ubuntu
Run Code Online (Sandbox Code Playgroud)

在:

AllowUsers ubuntu bamboo
Run Code Online (Sandbox Code Playgroud)

出去:

AllowUsers ubuntu bamboo
Run Code Online (Sandbox Code Playgroud)