是否可以在 sudoedit 授予的文件上使用 ansible template/copy

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

我喜欢像这样在ansible中使用template(或copy)函数:

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

问题是,我没有对远程文件/etc/file.conf的直接写入权限,我只能通过sudoedit

修改它

是否可以通过 sudoedit 管道 template 命令并像这样修改或复制文件?

问:"Is it possible to use ansible template/copy on sudoedit granted files? I can modify it only via sudoedit. Is it possible to pipe template command through sudoedit and modify or copy the file like this?"

A:不,这不可能。 Privilege escalation must be general 在受限文件上使用 templatecopy 或任何其他 Ansible 模块,commandshell 和可以使用 [=14 的类似模块除外=]命令。

"You cannot limit privilege escalation permissions to certain commands...."

实际上我找到了解决方法:

# 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

...

然后像这样使用它:

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