Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute a command by switching to root user in ansible

I am working on Ansible playbook to execute some of my tasks. In one of my tasks, I need to switch to particular directory and then execute a command using sudo but I need to do all these things by switching to root user first otherwise it won't work. So in general this is what I do without ansible:

david@machineA:/tmp/parallel-20140422$ sudo su
root@machineA:/tmp/parallel-20140422# sudo ./configure && make && make install

After above steps, I see GNU parallel library is installed in my system correctly. But with the below steps using Ansible, I don't see my GNU library getting installed at all.

- name: install gnu parallel
  command: chdir=/tmp/parallel-20140422 sudo ./configure && make && make install

Now my question is how can I switch to root user and execute a particular command. I am running Ansible 1.5.4 and looks like I cannot upgrade. I even tried with below but still it doesn't work:

- name: install gnu parallel
  command: chdir=/tmp/parallel-20140422 sudo ./configure && make && make install
  sudo: true
  sudo_user: root

I am running my playbook using below command:

ansible-playbook -e 'host_key_checking=False' setup.yml -u david --ask-pass --sudo -U root --ask-sudo-pass
like image 526
john Avatar asked Sep 02 '25 10:09

john


1 Answers

You need the become directive.

For example, to start a service as root:

- name: Ensure the httpd service is running
  service:
    name: httpd
    state: started
  become: true

you can also become another user, such as the apache user:

- name: Run a command as the apache user
  command: somecommand
  become: true
  become_user: apache

For your case, it will be:

- name: install gnu parallel
  command: chdir=/tmp/parallel-20140422 sudo ./configure && make && make install
  become: true
like image 52
Ortomala Lokni Avatar answered Sep 04 '25 05:09

Ortomala Lokni