Ansible win_shell/win_command prints logo output instead of actual output of the command:
- name: get Ps1 files
win_shell: get-ChildItem -path $testFolder -Filter *.ps1 -Recurse -File -Name -Depth 0
register: ps1_files
args:
executable: powershell
Should print a list of *.ps1 folders but instead prints wrong output (command works when running directly on powershell on the server):
"msg": {
2022-12-22T02:30:46.455812-0500 info: "changed": true,
2022-12-22T02:30:46.455867-0500 info: "cmd": "get-ChildItem -path $realProcessesFolder -Filter *.ps1 -Recurse -File -Name -Depth 0",
2022-12-22T02:30:46.455917-0500 info: "delta": "0:00:00.954839",
2022-12-22T02:30:46.455969-0500 info: "end": "2022-12-22 07:30:46.385668",
2022-12-22T02:30:46.456017-0500 info: "failed": false,
2022-12-22T02:30:46.456065-0500 info: "rc": 0,
2022-12-22T02:30:46.456115-0500 info: "start": "2022-12-22 07:30:45.430828",
2022-12-22T02:30:46.456165-0500 info: "stderr": "",
2022-12-22T02:30:46.456237-0500 info: "stderr_lines": [],
2022-12-22T02:30:46.456289-0500 info: "stdout": "\r\n\r\nComputerName : SL143312\r\nBuilddate : 2019-Aug-26 13:43:8\r\nProfile : Standard Application Server\r\nOS : Windows Server 2016 Standard Edition\r\nMachineType : VMware Virtual Platform\r\nModel : VMware, Inc.\r\nServerAppCode : TVP0\r\n\r\n\r\n\r\n",
2022-12-22T02:30:46.456343-0500 info: "stdout_lines": [
2022-12-22T02:30:46.456393-0500 info: "",
2022-12-22T02:30:46.456445-0500 info: "",
2022-12-22T02:30:46.456504-0500 info: "ComputerName : SL143312",
2022-12-22T02:30:46.456556-0500 info: "Builddate : 2019-Aug-26 13:43:8",
2022-12-22T02:30:46.456615-0500 info: "Profile : Standard Application Server",
2022-12-22T02:30:46.456663-0500 info: "OS : Windows Server 2016 Standard Edition",
2022-12-22T02:30:46.456718-0500 info: "MachineType : VMware Virtual Platform",
2022-12-22T02:30:46.456767-0500 info: "Model : VMware, Inc.",
2022-12-22T02:30:46.456816-0500 info: "ServerAppCode : TT00",
2022-12-22T02:30:46.456866-0500 info: "",
2022-12-22T02:30:46.456916-0500 info: "",
2022-12-22T02:30:46.456977-0500 info: ""
2022-12-22T02:30:46.457027-0500 info: ]
2022-12-22T02:30:46.457079-0500 info: }
This looks to me more like a logo.
I have used also the win_command module with nologo and came up with same result:
win_command: powershell -noninteractive -nologo -command "get-ChildItem -path $env:realProcessesFolder -Filter *.ps1 -Recurse -File -Name -Depth 0"
It would be great if you would have any suggestions.
Many thanks!
Related
I have an issue when trying to remotely execute a PowerShell script with Ansible. The PowerShell script (which works on its own without Ansible) essentially creates a virtual machine and copies a sysprepped VHD which is located in our NAS. It needs 3 arguments from the user (on which server do you want to create the virtual machine in, on which partition should the vhd and vm data be located in and what will be the name of the VM).
This is how the playbook looks like:
- hosts: windows_host
tasks:
- name: Run remote PowerShell script
win_shell: powershell.exe -ExecutionPolicy ByPass -File C:/Path/To/Script/Script.ps1 {{ server }} {{ partition }} {{ hostname }}
This is how I execute the playbook:
ansible-playbook /etc/ansible/playbook.yml --extra-var "server=server.mydomain.local partition=E: hostname=devtest" -vvvv
The connection gets established, but the playbook never finishes it just stays stuck. Enabling debug and verbose does not give any additional information. This is the last line I get when using debugging:
<windows_host.MYDOMAIN.LOCAL> ESTABLISH WINRM CONNECTION FOR USER: user#MYDOMAIN.LOCAL on PORT 5985 TO windows_host.MYDOMAIN.LOCAL
1058240 1669392256.73059: checking if winrm_host windows_host.MYDOMAIN.LOCAL is an IPv6 address
calling kinit with pexpect for principal user#MYDOMAIN.LOCAL
EXEC (via pipeline wrapper)
I created a different playbook and PowerShell script (creates a file which name gets assigned by the user)
$name=$args[0]
New-Item -Path "C:\Temp$name.txt"
and I am able to successfully execute the playbook which starts the PowerShell script without error.
Below is my ansible configuration (if needed):
user#ansible:/etc/ansible$ ansible -i hosts windows_host -m setup
HOSTNAME.MYDOMAIN.LOCAL | SUCCESS => {
"ansible_facts": {
"ansible_architecture": "64-bit",
"ansible_architecture2": "x86_64",
"ansible_bios_date": "05/23/2012",
"ansible_bios_version": "090006",
"ansible_date_time": {
[more data]
"ansible_distribution": "Microsoft Windows Server 2022 Datacenter",
"ansible_distribution_major_version": "10",
"ansible_distribution_version": "10.0.20348.0",
"ansible_domain": "MYDOMAIN.LOCAL",
[[more data]]
},
"ansible_fqdn": "HOSTNAME.MYDOMAIN.LOCAL",
"ansible_hostname": "HOSTNAME",
"ansible_interfaces": [
{
"connection_name": "Ethernet",
"default_gateway": "192.168.0.254",
"dns_domain": null,
"interface_index": 5,
"interface_name": "Microsoft Hyper-V Network Adapter",
"ipv4": {
"address": "192.168.0.100",
"prefix": "24"
},
"ipv6": {},
"mtu": 1500,
"speed": 10000
}
],
"ansible_ip_addresses": [
"192.168.0.100"
],
user#ansible:/etc/ansible$ ansible --version
ansible [core 2.12.10]
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python3/dist-packages/ansible
ansible collection location = /home/user/.ansible/collections:/usr/share/ansible/collections
executable location = /usr/bin/ansible
python version = 3.8.10 (default, Jun 22 2022, 20:18:18) [GCC 9.4.0]
jinja version = 2.10.1
libyaml = True
user#ansible:/etc/ansible$ sudo nano hosts
[windows_host]
windows_host.MYDOMAIN.LOCAL
[windows_host:vars]
ansible_user=windows_user#MYDOMAIN.LOCAL
ansible_password= {{ password }}
ansible_connection=winrm
ansible_port=5985
ansible_winrm_transport=kerberos
ansible_winrm_server_cert_validation=ignore
ansible_winrm_read_timeout_sec: 60
ansible_winrm_operation_timeout_sec: 58
Any advice?
EDIT: This is the content of the PowerShell script:
$userName="user"
$File="C:\Path\To\User\user.txt"
$hyperv_host=$args[0]
$partition=$args[1]
$host_name=$args[2]
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "$userName", (Get-Content $File | ConvertTo-SecureString)
$PSDefaultParameterValues = #{'Invoke-Command:ConfigurationName'='remote_host' }
$nas_location = "Microsoft.PowerShell.Core\FileSystem::\\path\in\NAS\location\VHD\sysprep.vhdx"
Invoke-Command -Credential $credentials -ScriptBlock {
(New-Item -Verbose "$using:partition\$using:host_name" -type directory)
(Copy-Item -Verbose -Path "$using:nas_location" -Destination "$using:partition\$using:host_name")
(Write-Host "VHD successfully copied from \\NAS\")
(Rename-Item -Verbose -Path "$using:partition\$using:host_name\sysprep.vhdx" -NewName "$using:host_name.vhdx")
(New-VM -Verbose -Name "$using:host_name" -MemoryStartupBytes 16GB -Generation 2 -Path "$using:partition\$using:host_name" -BootDevice VHD -VHDPath "$using:partition\$using:host_name\$using:host_name.vhdx")
(Set-VMProcessor -Verbose "$using:host_name" -Count 4)
} -ComputerName $hyperv_host
And this is how I execute it:
powershell.exe -ExecutionPolicy ByPass -File C:/Path/To/Script/Script.ps1 hypervhost.mylocal.domain F: dev-vm
I have been trying to schedule an ACR BUILD on a machine using Powershell. The approach I am using is with a service principal (as shown here: https://learn.microsoft.com/en-us/azure/container-registry/container-registry-authentication?tabs=azure-cli)
I have created a build script which works fine, if I call it form within the Powershell console. However, when I schedule the script to run from the windows scheduler, it seems to skip past the ACR BUILD portion and not execute as expected.
Script below:
$myreg = "myreg"
$myregfull = "myreg.azurecr.io"
$Date = Get-Date -format "yyyyMMdd"
$logfile = "c:\Log-$Date.txt"
$user ="xxx"
$pass="xxx"
$tenant="xxx"
$subscription="xxx"
$myimage="myimage:"
Try {
# 1. Logging in as service principal
$DateForLog = Get-Date | Out-File -FilePath $logfile -Append
"--- Logging in as service principal ---" | Out-File -FilePath $logfile -Append
az login --service-principal -u $user -p $pass --tenant $tenant | Out-File -FilePath $logfile -Append
}
Catch{
"Logging in as service principal failed at $(Get-Date). Error: $($_.Exception.Message)" |
Out-File -FilePath $logfile -Append
}
Try {
# 2. Switching to subscription
$DateForLog = Get-Date | Out-File -FilePath $logfile -Append
"--- Switching to subscription ---" | Out-File -FilePath $logfile -Append
az account set --subscription $subscription | Out-File -FilePath $logfile -Append
}
Catch{
"Switching to subscription failed at $(Get-Date). Error: $($_.Exception.Message)" |
Out-File -FilePath $logfile -Append
}
Try {
# 3. Logging in to registry
$DateForLog = Get-Date | Out-File -FilePath $logfile -Append
"--- Logging in to registry $myreg.azurecr.io ---" | Out-File -FilePath $logfile -Append
$TOKEN=$(az acr login --name $myreg --expose-token --output tsv --query accessToken)
docker login $myregfull -u 00000000-0000-0000-0000-000000000000 -p $TOKEN | Out-File -FilePath $logfile -Append
}
Catch{
"Logging in to registry failed at $(Get-Date). Error: $($_.Exception.Message)" |
Out-File -FilePath $logfile -Append
}
Try {
# 4. Confirm connected
$DateForLog = Get-Date | Out-File -FilePath $logfile -Append
"--- Confirming connected ---" | Out-File -FilePath $logfile -Append
az acr show -n $myreg | Out-File -FilePath $logfile -Append
az acr repository list -n $myreg | Out-File -FilePath $logfile -Append
}
Catch{
"Confirm connected failed at $(Get-Date). Error: $($_.Exception.Message)" |
Out-File -FilePath $logfile -Append
}
Try {
# 5. Triggerng Build
$DateForLog = Get-Date | Out-File -FilePath $logfile -Append
"--- Triggering build of myreg.azurecr.io/myimage:initial ---" | Out-File -FilePath $logfile -Append
az acr build -t $myimage$Date -r $myreg . --platform windows | Out-File -FilePath $logfile -Append
}
Catch{
"Triggerng Build failed at $(Get-Date). Error: $($_.Exception.Message)" |
Out-File -FilePath $logfile -Append
}
$DateForLog = Get-Date | Out-File -FilePath $logfile -Append
When called from console, the logs show the command called, then some 15mins later (after context upload) it shows (etc). :
2022/06/14 10:26:12 Downloading source code...
Then taking approx 30 mins to build before moving to next step.
Whereas when called form scheduler, it shows the step being finished in 8 secs.
The login process is definitely successful though, because the list of repositories is shown, no matter where it is called form.
Any suggestions on what might be causing this issue would be greatly appreciated.
EDIT
Updating the question to show logs.
From scheduler:
14 June 2022 14:46:05
--- Logging in as service principal ---
[
{
"cloudName": "AzureCloud",
"homeTenantId": "xxx",
--- OMMITTED ---
"user": {
"name": "xxx",
"type": "servicePrincipal"
}
}
]
14 June 2022 14:46:31
--- Switching to subscription ---
14 June 2022 14:46:36
--- Logging in to registry myreg.azurecr.io ---
Logging in to registry failed at 06/14/2022 14:46:47. Error: The term 'docker' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
14 June 2022 14:46:47
--- Confirming connected ---
{
"adminUserEnabled": true,
"anonymousPullEnabled": false,
"creationDate": "2021-04-06T10:23:22.985285+00:00",
--- OMMITTED ---
"type": "Microsoft.ContainerRegistry/registries",
"zoneRedundancy": "Disabled"
}
[
"myrepo1",
--- OMMITTED ---
"myrepo2"
]
14 June 2022 14:47:03
--- Triggering build of myreg.azurecr.io/myimage:initial ---
14 June 2022 14:47:12
From console:
14 June 2022 14:50:14
--- Logging in as service principal ---
[
{
"cloudName": "AzureCloud",
"homeTenantId": "xxx",
--- OMMITTED ---
"user": {
"name": "xxx",
"type": "servicePrincipal"
}
}
]
14 June 2022 14:50:41
--- Switching to subscription ---
14 June 2022 14:50:47
--- Logging in to registry myreg.azurecr.io ---
Logging in to registry failed at 06/14/2022 14:50:57. Error: The term 'docker' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
14 June 2022 14:50:57
--- Confirming connected ---
{
"adminUserEnabled": true,
"anonymousPullEnabled": false,
"creationDate": "2021-04-06T10:23:22.985285+00:00",
--- OMMITTED ---
"type": "Microsoft.ContainerRegistry/registries",
"zoneRedundancy": "Disabled"
}
[
"myrepo1",
--- OMMITTED ---
"myrepo2"
]
14 June 2022 14:51:11
--- Triggering build of myreg.azurecr.io/myimage:initial ---
2022/06/14 14:51:23 Downloading source code...
2022/06/14 14:51:29 Finished downloading source code
2022/06/14 14:51:30 Using acb_vol_77064302-024f-4c7c-8933-8f1fc9a4ce4f as the home volume
2022/06/14 14:51:31 Setting up Docker configuration...
2022/06/14 14:51:38 Successfully set up Docker configuration
2022/06/14 14:51:38 Logging in to registry: myreg.azurecr.io
2022/06/14 14:51:42 Successfully logged into myreg.azurecr.io
2022/06/14 14:51:42 Executing step ID: build. Timeout(sec): 28800, Working directory: '', Network: ''
2022/06/14 14:51:42 Scanning for dependencies...
2022/06/14 14:51:46 Successfully scanned dependencies
2022/06/14 14:51:46 Launching container with name: build
Sending build context to Docker daemon 804.4kB
Step 1/7 : FROM myreg.azurecr.io/myimage:empty
empty: Pulling from myimage
4612f6d0b889: Pulling fs layer
5ff1512f88ec: Pulling fs layer
--- OMMITTED ---
The problem was that the ACR BUILD command needed an absolute file path for the docker file and also <SOURCE_LOCATION>.
When called from the console, the current location was taken, but when the script was called from the scheduler it needed to be absolute.
So instead of:
az acr build -t $myimage$Date -r $myreg . --platform windows
It needed to be:
az acr build -t $myimage$Date -r $myreg -f c:/path-to-docker-file c:/path-to-source-folder/ --platform windows
The reason this was not evident to begin with, was because of the way I was capturing the logs. No errors or warnings were given when piping the output from ACR BUILD to Out-File -FilePath $logfile.
It was only when I switched to creating a transcript of the session (and removing the piped output) that an error was shown about not being able to see dockerfile.
Start-Transcript -Path "E:\transcript.txt" -NoClobber
I am trying to install Visual Studio 2017 using Ansible for Windows and I'm running into a strange issue. The installer is located at Z:\visualstudio\2017\vs2017_professional\vs2017_Professional.exe, and here is my task to run it:
- name: Install Visual Studio
win_shell: Start-Process -FilePath Z:\visualstudio\2017\vs2017_professional\vs2017_Professional.exe -ArgumentList '--quiet --norestart' -Wait
args:
creates: 'C:\Program Files (x86)\MSBuild\14.1\Bin\MSBuild.exe'
become_user: Administrator
However, it always fails:
fatal: [hostname]: FAILED! => {"changed":
true, "cmd": "Start-Process -FilePath
Z:\visualstudio\2017\vs2017_professional\vs2017_Professional.exe
-ArgumentList '--quiet --norestart' -Wait", "delta": "0:00:06.157773", "end": "2018-10-17 09:00:35.262158", "msg": "non-zero return code",
"rc": 1, "start": "2018-10-17 09:00:29.104384", "stderr":
"Start-Process : This command cannot be run due to the error: The
system cannot find the drive specified.\r\nAt line:1 char:65\r\n+ ...
ing $false; Start-Process -FilePath
Z:\visualstudio\2017\vs2017_profe ...\r\n+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n +
CategoryInfo : InvalidOperation: (:) [Start-Process],
InvalidOperationException\r\n + FullyQualifiedErrorId :
InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand",
"stderr_lines": ["Start-Process : This command cannot be run due to
the error: The system cannot find the drive specified.", "At line:1
char:65", "+ ... ing $false; Start-Process -FilePath
Z:\visualstudio\2017\vs2017_profe ...", "+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", " +
CategoryInfo : InvalidOperation: (:) [Start-Process],
InvalidOperationException", " + FullyQualifiedErrorId :
InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand"],
"stdout": "", "stdout_lines": []}
The file path is definitely valid, and the exact same script works just fine as a standalone powershell file run locally on the machine. What am I doing wrong?
Maybe this helps:
- name: Install Visual Studio
win_shell: Start-Process -FilePath " Z:\\visualstudio\\2017\\vs2017_professional\\vs2017_Professional.exe" -ArgumentList '--quiet --norestart' -Wait
args:
creates: 'C:\Program Files (x86)\MSBuild\14.1\Bin\MSBuild.exe'
become_user: Administrator
I just set up a few containerized agents and I'm running into build issues with few regression tests which work fine on regular build agents.
Was wondering if anyone had issues with containerized build agents?
Error Log:
Add-Type : (0) : Unable to find messages file 'cscui.dll' (1) : namespace VstsTaskSdk.FS At C:\tfsagent_work_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.119.0\ps_modules\VstsTaskSdk\LongPathFunctions.ps1:212 char:1 + Add-Type -Debug:$false -TypeDefinition #' + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidData: (Microsoft.Power...peCompilerError:AddTypeCompilerError) [Add-Type], Exception + FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddTypeCommand
#
Unable to find type [VstsTaskSdk.TerminationException]. Exit code 1
returned from process: file name
'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe', arguments
'-NoLogo -Sta -NoProfile -NonInteractive -ExecutionPolicy Unrestricted
-Command ". ([scriptblock]::Create('if (!$PSHOME) { $null = Get-Item -LiteralPath ''variable:PSHOME'' } else { Import-Module -Name ([System.IO.Path]::Combine($PSHOME,
''Modules\Microsoft.PowerShell.Management\Microsoft.PowerShell.Management.psd1''))
; Import-Module -Name ([System.IO.Path]::Combine($PSHOME,
''Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1''))
}')) 2>&1 | ForEach-Object { Write-Verbose $_.Exception.Message
-Verbose } ; Import-Module -Name 'C:\tfsagent_work_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.119.0\ps_modules\VstsTaskSdk\VstsTaskSdk.psd1'
-ArgumentList #{ NonInteractive = $true } -ErrorAction Stop ; $VerbosePreference = 'SilentlyContinue' ; $DebugPreference =
'SilentlyContinue' ; Invoke-VstsTaskScript -ScriptBlock
([scriptblock]::Create('.
''C:\tfsagent_work_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.119.0\VSBuild.ps1'''))"'.
I am unable to run this PowerShell script
# Execute .exe file
Get-ChildItem "C:\vagrant" -Filter *.exe | Where Name -NotMatch '.*NoDB\.exe$' | % {
New-Object psobject -Property #{
No = [int]([regex]::Match($_.Name, '(?<=CL)\d+').Value)
Name = $_.FullName
}
} | Sort No -Descending | Select -ExpandProperty Name -First 1 |
Foreach { & $_ -s2 -sp"-SilentInstallation=server -UpdateMaterials=yestoall -UpgradeDBIfRequired=yes"}
in Windows Windows 2008 R2 Standard because
**********************
Windows PowerShell Transcript Start
Start time: 20160719080730
Username : VAGRANT-2008R2\vagrant
Machine : VAGRANT-2008R2 (Microsoft Windows NT 6.1.7601 Service Pack 1)
**********************
Transcript started, output file is C:\Users\vagrant\Documents\PowerShell_transc
ript.20160719080730.txt
Where-Object : Cannot bind parameter 'FilterScript'. Cannot convert the "Name"
value of type "System.String" to type "System.Management.Automation.ScriptBlock
".
At C:\vagrant\Install_Ortho.ps1:7 char:49
+ Get-ChildItem "C:\vagrant" -Filter *.exe | Where <<<< Name -NotMatch '.*NoDB
\.exe$' | % {
+ CategoryInfo : InvalidArgument: (:) [Where-Object], ParameterBi
ndingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerSh
ell.Commands.WhereObjectCommand
**********************
Windows PowerShell Transcript End
End time: 20160719080730
**********************
I tried to use this advice "Try using {} instead of parentheses around your argument." Same error.
This syntax:
Where Property -[OperatorAsParameterName] 'value'
is introduced in PowerShell 3.0 - Windows 2008 R2 comes with PowerShell 2.0!
The version 2.0 equivalent would be:
Where {$_.Name -NotMatch '.*NoDB\.exe$'}
You may fix that one instance, but then other parts of the scripts will likely going to fail, and you have to keep fixing version 3.0 syntax until you've rewritten the entire thing
I would recommend finding a 2008R2-specific version of Vagrant, or filing this finding as a compatibility bug with their development team