Ansible:在文件中的现有行上插入一个单词 [英] Ansible: insert a single word on an existing line in a file

查看:27
本文介绍了Ansible:在文件中的现有行上插入一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用 Ansible 模块来编辑/etc/ssh/sshd_config 文件 - 每次我创建一个新用户时,我都想将它附加到这两行:

I have to use Ansible modules in order to edit the /etc/ssh/sshd_config file - every time I create a new user I want to append it at these two lines:

AllowUsers root osadmin <new_user>
AllowGroups root staff <new_group>

此时我正在使用 shell 模块来执行 sed 命令,但如果可能的话,我想使用 lineinfile

At this moment I'm using the shell module to execute a sed command but would like to use lineinfile, if possible

- shell: "sed -i '/^Allow/ s/$/ {{ user_name }}/' /etc/ssh/sshd_config"

如有任何建议,我们将不胜感激.

Any suggestions would be sincerely appreciated.

推荐答案

您可以使用换行符在一次播放中完成,但我认为为此使用两个 lineinfile 播放更干净.

You could do it in a single play with a newline, but I think it's cleaner to use two lineinfile plays for this.

- hosts: '127.0.0.1'
  vars:
    usernames:
       - larry
       - curly
       - moe
    usergroups:
       - stooges
       - admins
  tasks:
    - lineinfile:
        dest: /etc/ssh/sshd_config
        regexp: '^AllowUsers'
        line: "AllowUsers {{usernames | join(' ')}}"
    - lineinfile:
        dest: /etc/ssh/sshd_config
        regexp: '^AllowGroups'
        line: "AllowGroups {{usergroups | join(' ')}}"

请注意,groups 是一个保留字,因此不要将其用作变量名.

Note that groups is a reserved word so don't use that as a variable name.

这篇关于Ansible:在文件中的现有行上插入一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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