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

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

问题描述

我正在编写Ansible剧本,以在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

在这种特殊情况下,我正在搜索静态用户竹子".您可以改用这样的变量:

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

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

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