Ansible: How to run local powershell script on remote hosts



  • I'm trying to write a play that will take a locally stored powershell script from my Ansible server and run it on Windows hosts. I have been using the "win_shell" module to run scripts placed inside my playbook files, but for testability I want to have the scripts being executed stored outside of my playbook yaml files.

    Here's what I'm trying right now:

    - hosts: "AnsibleDevTestingHosts"
      tasks:
        - name: "showing playbook_dir"
          debug:
            msg: "{{ playbook_dir }}"
    
    - name: Testing Ansible
      ansible.builtin.script: "{{ playbook_dir }}/scripts/calibrate_flux_capacitor.ps1"
    

    When I run this, I'm currently getting back an error message:

    TASK [Testing Ansible] *********************************************************
    An exception occurred during task execution. To see the full traceback, use -vvv. The error was: IndexError: list index out of range
    fatal: [delorian-car-1.local]: FAILED! => {"msg": "Unexpected failure during module execution.", "stdout": ""}
    

    I've been looking at the https://docs.ansible.com/ansible/latest/collections/ansible/builtin/script_module.html and it seems pretty simple to use (and supports Windows). So, I'm unsure what the problem here is.



  • I've found a half-solution to this. You can load a file in to a Ansible variable and use that. So instead of having an inline script, you could store your local script file in to a variable string and then pass it to a shell module like win_shell.

    Example:

    - hosts: "DocsTimeMachines"
      tasks:
        - name: Calibrate Flux Capacitors
          win_shell: "{{ lookup('file', 'scripts/calibrate_flux_capacitor.ps1') }}"
    

    In the above example, under the directory with my playbook, there's a script "scripts" directory with the referenced script file.

    How this kinda sucks still is I want to be able to call the script and use named arguments, for instance, the script call might look like:

    scripts/calibrate_flux_capacitor.ps1 --mrfusion_enabled=false --hover_systems_enabled=false --retro_1950s_transistor_hack_enabled=true
    

    I don't think I can call it like this with my string variable solution here. I'll leave this open for other answers and accept one that can actually call the script, if it comes up.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2