execute a command by switching to root user in ansible
Solution 1
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
Solution 2
From your comment:
I know command module is working fine bcoz I verified for other tasks and they work fine.
command
module might be working for other commands, but in this example you use a shell syntax (&&
) to execute multiple commands. This syntax will not work in the command
module (because this module runs commands directly from Python and does not support combined commands).
You need to use the shell
module in this case.
- name: install gnu parallel
shell: ./configure && make && make install
args:
chdir=/tmp/parallel-20140422
sudo: true
sudo_user: root
john
Updated on June 08, 2020Comments
-
john almost 4 years
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
-
Admin almost 7 yearsIn ansible 1.5.4 there is no become I believe? right? and I cannot upgrade looks like