Ansible: Run commands on Windows node/machine with Ansible

  • 6
    Shares

In our previous articles, we discussed managing windows machine with Ansible by default method and managing windows machine by CredSSP method. In this article we will see executes/run a command on a Windows node with Ansible.

Ansible ships with a number of modules (called the ‘module library’) that can be executed directly on remote hosts or through Playbooks. Ansible provides huge number of windows modules, from which following are the couple of modules are used to run commands on remote windows machine/node.

1. win_command – Executes a command on a remote Windows node

Synopsis:

  • The win_command module takes the command name followed by a list of space-delimited arguments.
  • The given command will be executed on all selected nodes. It will not be processed through the shell, so variables like $env:HOME and operations like "<"">""|", and ";" will not work (use the win_shell module if you need these features).
  • For non-Windows targets, use the command module instead.

Example:

- name: Save the result of 'whoami' in 'whoami_out'
  win_command: whoami
  register: whoami_out

For more options please visit Ansible official documentation

2. win_shell – Executes shell commands on remote Windows node

Synopsis:

  • The win_shell module takes the command name followed by a list of space-delimited arguments. It is similar to the win_command module, but runs the command via a shell (defaults to PowerShell) on the target host.
  • For non-Windows targets, use the shell module instead.

Example:

# Execute a command in the remote shell; stdout goes to the specified
# file on the remote.
- win_shell: C:\somescript.ps1 >> c:\somelog.txt

# Change the working directory to somedir/ before executing the command.
- win_shell: C:\somescript.ps1 >> c:\somelog.txt chdir=c:\somedir

For more options please visit Ansible official documentation

For more windows modules please visit Ansible Windows Module List

References:
http://docs.ansible.com/ansible/latest/win_command_module.html
http://docs.ansible.com/ansible/latest/win_shell_module.html

Avinash Pawar

DevOps Practitioner interested in learning new technologies and interested in sharing the knowledge with others.

More Posts - Website

Follow Me:
TwitterFacebookLinkedInGoogle Plus

Avinash Pawar

DevOps Practitioner interested in learning new technologies and interested in sharing the knowledge with others.

Leave a Reply