Ansible: insert a single word on an existing line in a file

后端 未结 5 1721
天命终不由人
天命终不由人 2021-01-11 15:34

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:

AllowUs         


        
5条回答
  •  囚心锁ツ
    2021-01-11 16:29

    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 }}'
    

提交回复
热议问题