Sushil Chaudhari
Sushil Chaudhari

Reputation: 33

How to run sudo -u username command in Ansible?

I want to run a specific command as sudo -u username <command name> using Ansible.

I tried below task, but facing permissions issue.

---
-
  hosts: all
  become: yes
  vars_files:
    - vars.yml

  tasks:
    - name: "Create solr cores"
      shell: /opt/apps/solr/bin/solr create -c test10
      become_flags: '-u solr'
      register: core_one
#      changed_when: '"\"status\":0" in core_one.stdout'

Could anyone suggest on this?

Upvotes: 1

Views: 1433

Answers (2)

Naggappan Ramukannan
Naggappan Ramukannan

Reputation: 2812

remote_user: ansible
  tasks:   
  - name: "Create solr cores" 
     shell: /opt/apps/solr/bin/solr create -c test10
     become: yes
     become_user: solr
     register: core_one

In above example ansible connects to remote machine using user 'ansible'. Now this ansible user should have permission to switch to another user. i.e it should have root privileges

What happens with above code:

* ssh connection is made via ansible user (ansible-play does it)
* It uses command "sudo su solr" internally
* Then execute the command which is mentioned in shell 

Upvotes: 0

techraf
techraf

Reputation: 68489

The correct way to run a task is the following.

Having proper permissions is a prerequisite. Refer to man sudoers to learn more

- name: "Create solr cores" 
  shell: /opt/apps/solr/bin/solr create -c test10
  become: yes
  become_user: solr
  register: core_one

You already have become: yes on the play level, so just for clarity.

Upvotes: 2

Related Questions