Learn › Ansible

Ansible for Windows Admins: Manage Windows Servers from Git and Jenkins

Ansible basics for Windows admins: connect to Windows Server over SSH, write your first playbook in Git, and run it from Jenkins with one click.

Beginner 18 min read Part 3 of 3
By Gopinath Karthikeyan · 29 Nov 2026

This is where it all comes together. In Part 1 your scripts went into Git. In Part 2 Jenkins started checking them. Now Ansible takes those scripts to your Windows servers – one server or a hundred, with the same command.

By the end, you’ll click Build with Parameters in Jenkins, type a server or group name, and get a disk-space report from your Windows servers – using the very Get-DiskReport.ps1 you wrote in Part 1.

What you need: the Ubuntu Jenkins machine from Part 2, and one Windows Server 2022 or 2025 VM that the Ubuntu machine can reach on the network. A free 180-day evaluation from Microsoft’s Evaluation Center is perfect for a lab. About 75 minutes.

How Ansible thinks – 6 words

Word What it means
Control node The machine that runs Ansible – your Ubuntu/Jenkins machine. Must be Linux (or WSL)
Managed node A server Ansible manages – your Windows Servers. Nothing to install on them except the remote connection
Inventory A file listing your servers and groups, like windows or webservers
Module A ready-made action, such as “run PowerShell”, “install a feature”, “manage a service”
Task One step that uses a module
Playbook A YAML file with a list of tasks to run on a group of servers – your runbook, as code

Why Ansible on top of PowerShell? PowerShell does the work on a server. Ansible handles which servers, in what order, with which credentials, and what happened on each one – the parts you normally do by hand with RDP and a spreadsheet.

Step 1: install Ansible on the Jenkins machine

Use the official Ansible PPA so you get a current version installed for all users (Jenkins runs as its own jenkins user, so a per-user install wouldn’t work):

sudo apt update
sudo apt install -y software-properties-common
sudo add-apt-repository --yes --update ppa:ansible/ansible
sudo apt install -y ansible
ansible --version

The ansible package already includes the ansible.windows collection – the Windows modules.

Step 2: prepare the Windows Server (OpenSSH)

Ansible can reach Windows over WinRM or SSH. We’ll use SSH: it’s built into Windows Server 2022 and later, uses a key instead of a password, and is the same connection Linux admins already use.

On the Windows Server, open PowerShell as Administrator and run these commands from the Ansible documentation:

Get-WindowsCapability -Name OpenSSH.Server* -Online |
    Add-WindowsCapability -Online
Set-Service -Name sshd -StartupType Automatic -Status Running

$firewallParams = @{
    Name        = 'sshd-Server-In-TCP'
    DisplayName = 'Inbound rule for OpenSSH Server (sshd) on TCP port 22'
    Action      = 'Allow'
    Direction   = 'Inbound'
    Enabled     = 'True'
    Profile     = 'Any'
    Protocol    = 'TCP'
    LocalPort   = 22
}
New-NetFirewallRule @firewallParams

# Make PowerShell the default shell for SSH (Ansible is best tested with it)
$shellParams = @{
    Path         = 'HKLM:\SOFTWARE\OpenSSH'
    Name         = 'DefaultShell'
    Value        = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
    PropertyType = 'String'
    Force        = $true
}
New-ItemProperty @shellParams

If New-NetFirewallRule says the rule already exists, that’s fine – Windows created it during install.

Note the server’s IP address (ipconfig). We’ll call the server SRV01 and use 192.168.56.10 in the examples – replace it with yours.

Step 3: connect with a key, not a password

On the Ubuntu machine, create a key pair just for this lab:

ssh-keygen -t ed25519 -f ~/.ssh/winlab -C "ansible-lab" -N ""
cat ~/.ssh/winlab.pub

Copy the line that starts with ssh-ed25519. On the Windows Server (PowerShell as Administrator), allow that key for administrator logins:

$key = 'ssh-ed25519 AAAA...paste-your-public-key-here... ansible-lab'
Add-Content -Path C:\ProgramData\ssh\administrators_authorized_keys -Value $key
icacls.exe C:\ProgramData\ssh\administrators_authorized_keys /inheritance:r /grant "Administrators:F" /grant "SYSTEM:F"

The icacls line matters: Windows OpenSSH ignores this file if other users can read it.

Test from Ubuntu:

ssh -i ~/.ssh/winlab Administrator@192.168.56.10

Type yes to trust the server the first time. You should land at a PS C:\Users\Administrator> prompt. Type exit.

In the lab we use the built-in Administrator account. At work, use a dedicated service account with only the rights it needs, and keep the private key in a vault or in Jenkins credentials – never in Git.

Step 4: write the inventory and settings

On your Windows laptop, in the winops-lab repo, create ansible\inventory.yml:

all:
  children:
    windows:
      hosts:
        SRV01:
          ansible_host: 192.168.56.10
      vars:
        ansible_connection: ssh
        ansible_shell_type: powershell
        ansible_user: Administrator

Read it as: “there’s a group called windows; SRV01 is in it at this IP; connect to every Windows server over SSH, into PowerShell, as Administrator”. To add servers later, just add more lines under hosts:.

Now create ansible\ansible.cfg:

[defaults]
inventory = inventory.yml
host_key_checking = False

host_key_checking = False skips the “trust this server?” question so Jenkins doesn’t get stuck on it. That’s fine for a lab; in production, pre-load known host keys instead.

Step 5: your first playbook

Create ansible\disk-report.yml. It reuses your Part 1 script, so the PowerShell lives in one place:

- name: Windows disk space report
  hosts: "{{ target | default('windows') }}"
  gather_facts: false

  tasks:
    - name: Check the connection
      ansible.windows.win_ping:

    - name: Run Get-DiskReport.ps1 from the repo
      ansible.windows.win_powershell:
        script: "{{ lookup('ansible.builtin.file', '../scripts/Get-DiskReport.ps1') }}"
      register: disks
      changed_when: false

    - name: Show free space per drive
      ansible.builtin.debug:
        msg: "{{ inventory_hostname }} {{ item.DeviceID }} – {{ item.FreeGB }} GB free of {{ item.SizeGB }} GB ({{ item.FreePct }}%)"
      loop: "{{ disks.output }}"
      loop_control:
        label: "{{ item.DeviceID }}"

    - name: Fail if any drive is below 10% free
      ansible.builtin.assert:
        that: item.FreePct >= 10
        fail_msg: "{{ inventory_hostname }} {{ item.DeviceID }} is low on space ({{ item.FreePct }}% free)"
        success_msg: "{{ item.DeviceID }} OK"
      loop: "{{ disks.output }}"
      loop_control:
        label: "{{ item.DeviceID }}"

What each part does:

  • hosts: – which servers. By default the whole windows group; we’ll let Jenkins pass a different target
  • win_ping – proves Ansible can log in and run PowerShell
  • win_powershell – runs your script on the server and returns its objects, so Ansible can read FreeGB and FreePct
  • changed_when: false – tells Ansible this task only reads, it doesn’t change the server
  • assert – turns “low disk space” into a failed run, which Jenkins will show as red

Commit and push:

git switch -c add-ansible-disk-report
git add ansible
git commit -m "Add Windows inventory and disk report playbook"
git push -u origin add-ansible-disk-report

Open a pull request on GitHub and merge it.

Step 6: run it by hand first

On the Ubuntu machine, get the latest repo and run the playbook yourself before automating it:

git clone https://github.com/YOUR-USER/winops-lab.git ~/winops-lab   # first time only
cd ~/winops-lab && git pull
cd ansible
ansible windows -m ansible.windows.win_ping --private-key ~/.ssh/winlab
ansible-playbook disk-report.yml --private-key ~/.ssh/winlab

The clone asks for your GitHub username and a token (use the read-only token from Part 2, or a new one). You should see SUCCESS for the ping, then one line per drive and ok= in the PLAY RECAP. If it works here, it will work in Jenkins.

Step 7: give Jenkins the SSH key

  1. Manage Jenkins → Credentials → System → Global credentials → Add Credentials.
  2. Kind: SSH Username with private key.
  3. ID: win-lab-ssh. Username: Administrator.
  4. Private Key → Enter directly → paste the whole content of ~/.ssh/winlab (print it with cat ~/.ssh/winlab, including the BEGIN and END lines).
  5. Click Create.

Jenkins now holds the key encrypted, hands it to the build only while it runs, and hides it in the log.

Step 8: add an Ansible stage to the Jenkinsfile

Update jenkins\Jenkinsfile in your repo so it looks like this (the first two stages are from Part 2):

pipeline {
    agent any

    options {
        timestamps()
        buildDiscarder(logRotator(numToKeepStr: '10'))
    }

    parameters {
        string(name: 'TARGET', defaultValue: 'windows', description: 'Server name or inventory group')
        booleanParam(name: 'RUN_REPORT', defaultValue: true, description: 'Run the disk report on Windows servers')
    }

    triggers {
        pollSCM('H/15 * * * *')
    }

    stages {
        stage('Show what we are building') {
            steps {
                sh 'git log -1 --oneline'
            }
        }
        stage('Check PowerShell syntax') {
            steps {
                sh 'pwsh -NoProfile -File scripts/Test-ScriptSyntax.ps1 -Path scripts'
            }
        }
        stage('Disk report on Windows') {
            when { expression { params.RUN_REPORT } }
            steps {
                withCredentials([sshUserPrivateKey(credentialsId: 'win-lab-ssh',
                                                   keyFileVariable: 'SSH_KEY',
                                                   usernameVariable: 'SSH_USER')]) {
                    sh '''
                        cd ansible
                        ansible-playbook disk-report.yml \
                          --private-key "$SSH_KEY" -u "$SSH_USER" \
                          -e target="$TARGET"
                    '''
                }
            }
        }
    }

    post {
        success { echo 'Scripts are valid and all drives have enough space.' }
        failure { echo 'Something failed – check the stage that turned red.' }
    }
}

What’s new:

  • parameters – adds a TARGET box and a RUN_REPORT tick box to the build page
  • when – the Ansible stage runs only if the box is ticked
  • withCredentials – unlocks the SSH key just for this stage
  • the sh '''...''' uses single quotes, so the shell – not Groovy – fills in $SSH_KEY. That’s the safe way to pass secrets

Commit, push, open a pull request and merge, like before.

Step 9: run it from Jenkins

  1. Open the winops-lab-checks job and click Build Now once. Jenkins reads the new Jenkinsfile and learns the parameters.
  2. From now on you’ll see Build with Parameters. Click it, keep TARGET = windows (or type SRV01) and click Build.
  3. Open the build’s Console Output: the syntax check, then Ansible logging in to each server and printing free space per drive.

Want to see it fail? Set the threshold in the playbook to 90 instead of 10, push it, and run again: the Disk report stage turns red with the drive that’s “low”. Set it back afterwards.

You’ve just built the full loop: change a script in Git → pull request → Jenkins checks it → one click runs it on your Windows servers through Ansible, with a log of who ran what and when.

Common errors

  • UNREACHABLE … Connection timed out – the Ubuntu machine can’t reach port 22 on the server. Check the IP, that both VMs are on the same network, and the firewall rule from Step 2.
  • Permission denied (publickey…) – the key isn’t accepted. Re-check the icacls line, that you pasted the .pub key on the server, and that Jenkins has the private key.
  • The term 'xyz' is not recognized or odd quoting errors – the SSH default shell is still cmd. Re-run the DefaultShell part of Step 2 and make sure the inventory says ansible_shell_type: powershell.
  • provided hosts list is empty – Ansible didn’t find ansible.cfg, so it never loaded the inventory. Run ansible-playbook from inside the ansible folder, as in the examples.
  • ansible-playbook: not found in Jenkins – Ansible was installed for one user only. Install it with apt as in Step 1.
  • No “Build with Parameters” button – run the job once with Build Now so Jenkins reads the parameters.

Where to go from here

  • More servers: add hosts to inventory.yml, or make groups like web and file and pass them as TARGET.
  • Make changes, not just reports: modules like ansible.windows.win_feature, win_service and win_updates install roles, manage services and patch servers. Start with --check (dry run) – the same “report first, change second” rule.
  • Real-world safety: run against one test server first, then batches (serial: in the playbook), and keep an approval step in Jenkins for anything that restarts a server.

FAQ

WinRM or SSH for Ansible on Windows? Both work. WinRM is the traditional option and is everywhere in older estates; SSH is simpler to set up with keys and is officially supported by Ansible for Windows Server 2022 and later. Use what your servers and security team support.

Do I need to install anything on the Windows servers? No agent. Just the remote connection (OpenSSH or WinRM) and an account Ansible can use.

Can I run Ansible directly on Windows? Not as the control node. Use a Linux machine or WSL to run Ansible – it can still manage as many Windows servers as you like.

Learning path complete 🎉

You now have the core toolkit of a modern Windows automation engineer: Git for every script, Jenkins to check and run them, and Ansible to reach every server. Test yourself with the practice questions below, and look out for the next guides in the Jenkins and Ansible categories.

Practise this topic

Test yourself with free questions on this topic – instant answers and explanations.

Start practice questions

AnsibleJenkinsGitWindows ServerPowerShellAutomationBeginner

Gopinath Karthikeyan

Gopinath Karthikeyan – Windows Site Reliability Engineer with about 12 years in enterprise Windows Server infrastructure, and founder of WinOps Academy. YouTube · LinkedIn