Ansible: insert a single word on an existing line

2019-04-22 15:10发布

问题:

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>

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.

回答1:

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(' ')}}"

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



回答2:

The replace module will replace all instances of a regular expression pattern within a file. Write a task to match the AllowUsers line and replace it with the original line appended with the user name. To ensure the task is idempotent, a negative lookahead assertion in the regular expression checks if the user name already appears in the line. For example:

- name: Add user to AllowUsers
  replace:
    backup: yes
    dest: /etc/ssh/sshd_config
    regexp: '^(AllowUsers(?!.*\b{{ user_name }}\b).*)$'
    replace: '\1 {{ user_name }}'


回答3:

This worked for me

 - name: Add Group to AllowGroups
   lineinfile: 
     dest=/etc/ssh/sshd_config
     backup=True
     backrefs=True
     state=present
     regexp='^(AllowGroups(?!.*\b{{ groupname }}\b).*)$'
     line='\1 {{ groupname }}'


回答4:

I had the same problem. I needed add user to sudoers group, let's say 'testuser' to line:

User_Alias SOMEADMIN = smoeuser1, someuser2, someuser3

This worked well for me:

- name: add testuser to end of line
      lineinfile:
        dest: /etc/sudoers.d/somegroup
        state: present
        regexp: '^(User_Alias(.*)$)'
        backrefs: yes
        line: '\1, testuser'

The point is that if I had '^User_Alias(..)$'* in regexp and not '^(User_Alias(..)$)'* it didn't work and whole line was replaced. With () arround searched text the result was OK:

User_Alias SOMEADMIN = smoeuser1, someuser2, someuser3, testuser

So then anything can work in line:, included ansible variables like "{{ usernames | join(', ') }}"



标签: ansible sshd