简体   繁体   中英

PowerShell script with input parameters with packer(.json)

I have this Ps1 script,

param   ([string] $userpassword, [string] $UserName)

Write-host "Start.." (Get-date)

Write-host "User Name is "$UserName Write-host "User password is
"$userpassword

if ($userpassword.length -lt 0) {
    Write-host "Please enter password!"$UserName }

Write-host "End.." (Get-date)

packer(.json) as follows:

"provisioners":    [
    {
      "type": "powershell",
      "environment_vars": 
      [
        "userpassword=********",
        "UserName=ABC"
      ],      
      "scripts": 
      [
        "test.ps1"
      ]
    } ]

.Ps1 can not read input para from packer(.json)...

Unlike a Unix shell script, Powershell variables (and params) aren't environment variables.

The syntax in Powershell for reading an environment variable is $env:variablename .


You can either set the param default values to be the env var:

param(
    [string] $userpassword = $env:userpassword,
    [string] $UserName = $env:username
)

Write-host "Start.." (Get-date)
[...]

Or scrap the param block and just assign the variables directly:

[string] $userpassword = $env:userpassword
[string] $UserName = $env:username

Write-host "Start.." (Get-date)
[...]

Whilst the question is not very clear I surmise from the title that you wish to run a PowerShell script under packer passing parameters to it.

Packer does support this but only for inline scripts. It does not matter if the parameter is an environment variable or direct entry. the key thing is to ensure that the script runs from the building machine.

It's a 2 step process.

  1. Copy the file up to the machine.
  2. Run the file inline passing params.

Eg

 "provisioners": [ { "type": "file", "source": "c:\\myscripts\\MyPowerShellScript.ps1", "destination": "c:\\temp\\MyPowerShellScript.ps1", "direction": "upload" }, { "type": "shell", "inline": [ "c:\\temp\\MyPowerShellScript.ps1 Param1 {{user `Param2_from_an_env_var`}}" ] }, 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM