Unable to create Mapped Drive using Powershell script from ansible

Viewed 14

I am trying to map Network drives on my windows machine using powershell scripts through ansible.

My powershell script:

param(
    [string]$MountDrive = $(throw "MountDrive is a mandatory parameter"),
    [string]$MountPath = $(throw "MountPath is a mandatory parameter"),
    [string]$ServiceAccountSecret = $(throw "ServiceAccountSecret is a mandatory parameter")
)

$secret = (Get-SECSecretValue -SecretId $ServiceAccountSecret).SecretString | ConvertFrom-Json
$domainJoinUserName = $secret.service_account_user
$domainJoinPassword = $secret.service_account_password
$secpasswd = ConvertTo-SecureString $domainJoinPassword -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential($domainJoinUserName, $secpasswd)

$mapping_exists = $False
$mapped_drive = Get-PSDrive `
-Name "$MountDrive" `
-PSProvider "FileSystem" `
-Scope Global `
-ErrorAction SilentlyContinue

If($mapped_drive){
    If($mapped_drive.DisplayRoot -eq "$MountPath"){
        $mapping_exists = $True
    } Else {
        Remove-PSDrive -Name "$MountDrive" -PSProvider "FileSystem" -Scope Global -Force
    }
}

If(-not $mapping_exists){
    New-PSDrive `
    -Name "$MountDrive" `
    -Root "$MountPath" `
    -PSProvider "FileSystem" `
    -Credential $creds `
    -Scope Global `
    -Persist
}

My ansible task calling this script is:

---
- name: Map Shared Drives
  become: true
  become_method: runas
  become_user: "{{service_account}}"  
  ansible.windows.win_powershell:
    script: |
      param(
        [string]$MountDrive,
        [string]$MountPath,
        [string]$ServiceAccountSecret
      )
      . D:\Temp\mountShare.ps1 `
      -MountDrive $MountDrive `
      -MountPath $MountPath `
      -ServiceAccountSecret $ServiceAccountSecret
    parameters:
      MountDrive: "{{item.mount_drive|upper}}"
      MountPath: \\{{fsx_dns_name}}\{{item.name}}
      ServiceAccountSecret: "{{ServiceAccountSecretManagerId}}"
  vars:
    ansible_become_pass: "{{service_account_pass}}"
  loop: "{{fileshare_config}}"
  register: mounted_shares 
  failed_when: "mounted_shares.module_stderr != '' or '\"failed\":true' in mounted_shares.module_stdout or '\"error\":[{' in mounted_shares.module_stdout"
  changed_when: "'\"changed\":true' in mounted_shares.module_stdout"

I have already tested the script mountShare.ps1 in the same machine, by loggig in as the same user. And its working as expected. But when I run it from ansible, I get an output in ansible that the PSDrive is created, but when I login to check from windows explorer, its not there.

I have added everything recommended by microsoft, dot sourcing, Scope set to Global, but its not working

0 Answers
Related