Search code examples
jenkinsansibleansible-2.xrhel7ansible-inventory

How can we run sudo rpm commands using ansible


In my ansible role, I have a task where I am trying to install Jenkins rpm. The rpm is located in /tmp directory on target host. Also, I have permission to run the command, "sudo /bin/rpm -Uvh /tmp/jenkins-2.107.1.2-1.1.noarch.rpm" which work when I tried to run it on the server directly. But running the same command via command module it fails.

Task :

- name: run the rpm command on masters
  command: sudo /bin/rpm -Uvh jenkins-2.107.1.2-1.1.noarch.rpm
  args:
    chdir: /tmp 

Error:

fatal: [xxxx. xxx.com]: FAILED! => {"changed": false, "cmd": "'sudo rpm' -Uvh 'jenkins-2.107.1.2-1.1.noarch.rpm'", "msg": "[Errno 2] No such file or directory", "rc": 2} 

Permission on target host :

User XXXX may run the following commands on target_Host_Name:
    (root) NOPASSWD: /usr/sbin/service jenkins stop, /usr/sbin/service jenkins start, /bin/rpm -Uvh jenkins*.noarch.rpm

Solution

  • You could use the ansible yum module with become: true rather than the command module with sudo for example:

    - name: install jenkins rpm from a local file
      yum:
        name: /tmp/jenkins-2.107.1.2-1.1.noarch.rpm
        state: present
      become: true
    

    Note: the error [Errno 2] No such file or directory is explicit, the file /tmp/jenkins-2.107.1.2-1.1.noarch.rpm does not exist. You need to ensure that the file exists before attempting to install the rpm.

    For additional information on privilege escalation in ansible refer to: https://docs.ansible.com/ansible/latest/user_guide/become.html