Ansible 更新 sshd 配置文件 [英] Ansible to update sshd config file

查看:30
本文介绍了Ansible 更新 sshd 配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing an Ansible play to automate new user creation in 100+ Unix servers. I've got the part right where it creates an user and assigns password. But our organization hardening policy demands, whenever a new user is added, username must be updated in "AllowUsers" parameter of sshd_config file. I'm new to Ansible and have no clue how to get this done.

这是 sshd_config 文件的AllowUsers"部分.

Here's "AllowUsers" section of sshd_config file.

AllowUsers root user1 user2 user2

这是添加新用户testuser"后的样子

This is how it should be after adding a new user "testuser"

AllowUsers root user1 user2 testuser

推荐答案

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

I searched for solution that doesn't do anything if the user already is on the list. This is how it should work in Ansible. My solution at first searches for the user and only if the user is not on the list it will be added.

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

在这种特殊情况下,我正在搜索静态用户bamboo".你可以像这样使用一个变量:

In this special case I'm searching for static user "bamboo". You could use a variable instead like this:

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

line: AllowUsers {{ username }}\1

结果

在:

AllowUsers ubuntu #sdfd

出:

AllowUsers bamboo ubuntu #sdfd

在:

AllowUsers ubuntu

出:

AllowUsers bamboo ubuntu

在:

AllowUsers ubuntu bamboo

出:

AllowUsers ubuntu bamboo

这篇关于Ansible 更新 sshd 配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆