Debian Codegraph @

lib/ansible/executor/powershell/bootstrap_wrapper.ps1

raw
1 param([string]$InputFile)
2
3 if ($PSVersionTable.PSVersion -lt [Version]"5.1") {
4 '{"failed":true,"msg":"Ansible requires PowerShell v5.1"}'
5 exit 1
6 }
7
8 $isClm = $ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage'
9
10 # Input is either from stdin or a separate file for non-pipelining scenarios.
11 if ($InputFile) {
12 if ($isClm) {
13 # While this reads it all in memory there is no other way to avoid this
14 # if running in CLM. Only way to avoid this is to have the caller start
15 # the process with the content's piped but that is hard to do cross
16 # platform.
17 Get-Content -LiteralPath $InputFile -Encoding UTF8 |
18 & $MyInvocation.MyCommand.ScriptBlock
19 return
20 }
21 else {
22 # .GetEnumerator() is important to ensure we stream the lines rather
23 # than read it all here.
24 $inputData = [System.IO.File]::ReadLines(
25 $InputFile,
26 [System.Text.Encoding]::UTF8).GetEnumerator()
27 }
28 }
29 else {
30 $inputData = $input
31 }
32
33 # First input is a JSON string with name/script/params of what to run. This
34 # ends with a line of 4 null bytes and subsequent input is piped to the code
35 # provided.
36 $codeJson = foreach ($in in $inputData) {
37 if ([string]::Equals($in, "`0`0`0`0")) {
38 break
39 }
40 $in
41 }
42 $code = $codeJson | ConvertFrom-Json
43 $splat = @{}
44 foreach ($obj in $code.params.PSObject.Properties) {
45 $splat[$obj.Name] = $obj.Value
46 }
47
48 $filePath = $null
49 try {
50 $cmd = if ($isClm) {
51 # CLM needs to execute code from a file for it to run in FLM when trusted.
52 # Set-Item on 5.1 doesn't have a way to use UTF-8 without a BOM but luckily
53 # New-Item does that by default for both 5.1 and 7. We need to ensure we
54 # use UTF-8 without BOM so the signature is correct.
55 $filePath = Join-Path -Path $env:TEMP -ChildPath "$($code.name)-$(New-Guid).ps1"
56 $null = New-Item -Path $filePath -Value $code.script -ItemType File -Force
57
58 $filePath
59 }
60 else {
61 # In FLM we can just invoke the code as a scriptblock without touching the
62 # disk.
63 [System.Management.Automation.Language.Parser]::ParseInput(
64 $code.script,
65 "$($code.name).ps1", # Name is used in stack traces.
66 [ref]$null,
67 [ref]$null).GetScriptBlock()
68 }
69
70 $inputData | & $cmd @splat
71 }
72 finally {
73 if ($filePath -and (Test-Path -LiteralPath $filePath)) {
74 Remove-Item -LiteralPath $filePath -Force
75 }
76 }