template task: write to root owned directory

1.3k Views Asked by At

I want to copy a template generated file to /etc/init.d folder. But template task doesn't seem to support sudo parameter. What is the recommended way to handle this? should I copy it to temporary directory and then move file with with sudo?

The playbook task looks like as shown below. Ansible version 1.8.2

   - name: copy init script
     template: src=template/optimus_api_service.sh dest=/etc/init.d/optimus-api mode=0755 force=yes owner=root group=root
1

There are 1 best solutions below

2
On BEST ANSWER

I have tested the following playbook and it works.

My setup:

The User vagrant on the machine vm is allowed to execute commands password-free with sudo.

I created a simple template and installed it with the following playbook:

---
- name: Test template
  hosts: vm
  gather_facts: no
  remote_user: vagrant

  vars:
    bla: blub                # some variable used in the template

  tasks:
    - name:  copy init script
      sudo: yes              # << you have to activate sudo
      sudo_user: root        # << and provide the user
      template: src=template/test.j2 dest=/opt/test mode=0755 force=yes owner=root group=root