Mapping a Network Drive on a Windows Guest using Ansible

前端 未结 1 1446
旧巷少年郎
旧巷少年郎 2021-01-23 03:17

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, d

相关标签:
1条回答
  • 2021-01-23 03:52

    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 :

    - name: map drive and run a task
      script: files/mapdrive.ps1 -network_password "{{ network_password }" -command_to_run "{ Copy-Item Y:\file_to_copy.txt C:\Some\Were }"
    

    and my ps1 looks like this :

    param(
      $network_password,
      $command_to_run
    )
    $PWord = ConvertTo-SecureString $network_password -AsPlainText -Force
    $myCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "domain\user",$PWord
    New-PSDrive -Name "Y" -PSProvider "FileSystem" -Root "\\remoteserver\share" -Credential $myCreds
    Invoke-Command -ScriptBlock $command_to_run
    

    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.

    0 讨论(0)
提交回复
热议问题