Search code examples
ansibleansible-inventory

How to run some tasks locally in Ansible


I have a playbook with some roles/tasks to be executed on the remote host. There is a scenario where I want some tasks to execute locally like downloading artifacts from svn/nexus to local server.

Here is my main playbook where I am passing the target_env from the command line and dynamically loading the variables using group_vars directory

---
 - name: Starting Deployment of Application to tomcat nodes
   hosts: '{{ target_env }}'
   become: yes
   become_user: tomcat
   become_method: sudo
   gather_facts: yes
   roles:
     - role: repodownload
       tags:
         - repodownload
     - role: stoptomcat
       tags:
         - stoptomcat

The first role repodownload actually download the artifacts from svn/nexus to the local server/controller. Here is the main.yml of this role -

 - name: Downloading MyVM Artifacts on the local server
   delegate_to: localhost
   get_url: url="http://nexus.com/myrelease.war" dest=/tmp/releasename/

 - name: Checkout latest application configuration templates from SVN repo to local server
   delegate_to: localhost
   subversion:
     repo: svn://12.57.98.90/release-management/config
     dest: ../templates
     in_place: yes

But it's not working. Could it be because in my main yml file I am becoming the user using which I want to execute the commands on remote host.

Let me know if someone can help. It will be appreciated.

ERROR -

    "changed": false,
    "module_stderr": "sudo: a password is required\n",
    "module_stdout": "",
    "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error",
    "rc": 1
}

Solution

  • Given the scenario, you can do it multiple ways. One could be adding another play for repodownload role to your main playbook that runs only on localhost. Then remove delegate_to: localhost from the role tasks and move the variables accordingly.

     ---
     - name: Download repo
       hosts: localhost
       gather_facts: yes
       roles:
         - role: repodownload
           tags:
             - repodownload
    
     - name: Starting Deployment of Application to tomcat nodes
       hosts: '{{ target_env }}'
       become: yes
       become_user: tomcat
       become_method: sudo
       gather_facts: yes
       roles:
         - role: stoptomcat
           tags:
             - stoptomcat
    

    Another way could be removing become from play level and add to role stoptomcat. Something like below should work.

     ---
     - name: Starting Deployment of Application to tomcat nodes
       hosts: '{{ target_env }}'
       gather_facts: yes
       roles:
         - role: repodownload
           tags:
             - repodownload
         - role: stoptomcat
           become: yes
           become_user: tomcat
           become_method: sudo
           tags:
             - stoptomcat
    

    Haven't tested the code so apologies if any formatting issues.