I'm trying to automate some tasks on Windows guests using Ansible, and I'm running into some issues mapping a network drive.
What I'm trying to do is map the drive, do something to it (in my example here, I just try to list the files), and then unmap it.
When I run Ansible, the output suggests that the shared drive was mapped successfully, but listing the files and unmapping both result in errors that state that the drive doesn't exist. ("A drive with the name 'K' does not exist.")
When I login to the Windows guest after running Ansible, the drive is mapped.
If I run Ansible while I am logged in the guest, the drive only becomes visible after I logout and log back in again. The script I use to mount the drive also creates a file on the guest for debugging purposes, and the file does appear even when I'm logged in. I don't need to logout and back in again for it to become visible. So it seems only the network drive mapping requires a logout and login to take effect.
I also tried "net use
" to map the drive, and the results were the same.
My Ansible playbook looks like this. (I have left out some sensitive parts.)
tasks:
- name: Mount share
script: scripts/mount.ps1 {{ share }}
- name: Test
script: scripts/test.ps1
register: test
- name: Test stdout
debug: msg="{{ test.stdout }}"
- name: Test stderr
debug: msg="{{ test.stderr }}"
- name: Umount share
script: scripts/umount.ps1
mount.ps1.
param([string]$share)
$share | Out-File c:\ansible-test\debug.txt
New-PSDrive -Name "K" -PSProvider FileSystem -Root "$share" -Persist
test.ps1
Get-ChildItem K:\
umount.ps1
Remove-PSDrive "K"
Unfortunately this is down the way Ansible communicates with windows. I've had similar issues where commands and package installation didn't work as expected.
When Ansible communicates over WinRM to the windows box it initiates a batch connection, not a full session. Mapping drives is one of those tasks that requires a full session, but each task that Ansible runs creates it's own batch connection so when you map a drive as soon as it disconnects, you loose that mapping because there is no actual user to register it too.
The only work around you have here is to create a .ps1 to map the drive then use Invoke-Command.
Here is my work around :
and my ps1 looks like this :
Apparently future releases of Ansible will employ a form of "become" which will allow these persistent sessions making this type of task a lot easier, but that could be a couple of years away and at least 2 or 3 releases ahead.