Search code examples
ansibleansible-2.xansible-inventory

Run Ansible Task in localhost instead of inventory host


I need to check one file (/tmp/test.html) exist on localhost and if it exist execute the other tasks. Can you please help to run this first task (name: Check exist and copy) in localhost(workstation).

localhost: workstation remotehost: servera,serverb

Below is my playbook.yml

---
- name: Check exist and copy
  hosts: all
  tasks:
  - name: check if file is exists #need to execute this task in workstation
    stat: 
     path: /tmp/test.html
    register: file_present

  - name: copy to taggroup 1
    copy: 
     src: /tmp/test.html 
     dest: /tmp/dest1.html
    when: file_present.stat.exists == 0 and inventory_hostname in groups ['taggroup1']

  - name: copy to taggroup 2
    copy: 
     src: /tmp/test.html 
     dest: /tmp/dest2.html
    when: file_present.stat.exists == 0 and inventory_hostname in groups ['taggroup2']


Solution

  • Q: "Check file /tmp/test.html exists on localhost."

    A: Module stat is not needed when paths are tested at localhost. For example, the play will fail if the file /tmp/test.html does not exist, and continue the play otherwise

    - hosts: all
    
      vars:
    
        my_file: /tmp/test.html
    
      tasks:
    
        - fail:
            msg: "[ERROR] {{ my_file }} does not exist."
          when: my_file is not exists
          delegate_to: localhost
          run_once: true
    
        - debug:
            msg: Continue play.
          run_once: true