Search code examples
linuxansibleprivilegessudoers

Is it possible to use ansible template/copy on sudoedit granted files


I like to use template (or copy) function in ansible like this:

- name: Template a file to /etc/files.conf
  template:
    src: /mytemplates/foo.j2
    dest: /etc/file.conf

Problem is, I don't have direct write permissions for remote file /etc/file.conf, I can modify it only via sudoedit

Is it possible to pipe template command through sudoedit and modify or copy the file like this?


Solution

  • Actually I found a workaround for it:

    # sudoedit.yml
    
    ---
    
    - name: Create temp file 
      tempfile:
        suffix: ".{{ sudoedit.suffix }}"
      register: tempfile
      check_mode: no
      changed_when: false
    
    - name: "Check if {{ sudoedit.suffix }} exists"
      stat:
        path: "{{ sudoedit.dest }}"
      register: dest
    
    - name: "Copy content of {{ sudoedit.suffix }} into temp file"
      copy:
        src: "{{ sudoedit.dest }}"
        dest: "{{ tempfile.path }}"
        remote_src: yes
      diff: no
      check_mode: no
      changed_when: false
      when: dest.stat.exists
    
    - name: "Copy file {{ sudoedit.suffix }}"
      copy:
        src : "{{ sudoedit.src }}"
        dest: "{{ tempfile.path }}"
      register: sudoresult
    
    - name: "Modify file {{ sudoedit.suffix }} with sudoedit"
      shell: 
        cmd: sudoedit -n "{{ sudoedit.dest }}"
        stdin: ":%d|:r {{ tempfile.path }}|:1d|:wq"
        executable: /bin/bash
      environment:
        SUDO_EDITOR: /usr/bin/vi
      when: sudoresult.changed
      changed_when: false
    
    - name: Delete the temp file
      file:
        path: "{{ tempfile.path }}"
        state: absent
      changed_when: false
      when: tempfile.path is defined
    
    ...
    

    Then use it like this:

    - name: Set NFS exports
      include_tasks: sudoedit.yml
      vars:
        sudoedit:
          src: source/etc/exports
          dest: /etc/exports
          suffix: exports