provisioner/elevated: Add cleanup logic to remove elevated user scheduled task artifacts

This commit is contained in:
Wilken Rivera 2020-04-03 07:26:10 -04:00
parent 11db6014fa
commit 91c8afda8e
1 changed files with 13 additions and 2 deletions

View File

@ -25,6 +25,7 @@ type elevatedOptions struct {
TaskDescription string TaskDescription string
LogFile string LogFile string
XMLEscapedCommand string XMLEscapedCommand string
ScriptFile string
} }
var psEscape = strings.NewReplacer( var psEscape = strings.NewReplacer(
@ -117,6 +118,14 @@ $result = $t.LastTaskResult
if (Test-Path $log) { if (Test-Path $log) {
Remove-Item $log -Force -ErrorAction SilentlyContinue | Out-Null Remove-Item $log -Force -ErrorAction SilentlyContinue | Out-Null
} }
$script = [System.Environment]::ExpandEnvironmentVariables("{{.ScriptFile}}")
if (Test-Path $script) {
Remove-Item $script -Force -ErrorAction SilentlyContinue | Out-Null
}
$f = $s.GetFolder("\")
$f.DeleteTask("\$name", "")
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($s) | Out-Null [System.Runtime.Interopservices.Marshal]::ReleaseComObject($s) | Out-Null
exit $result`)) exit $result`))
@ -166,12 +175,16 @@ func GenerateElevatedRunner(command string, p ElevatedProvisioner) (uploadedPath
elevatedPassword, escapedElevatedPassword) elevatedPassword, escapedElevatedPassword)
} }
uuid := uuid.TimeOrderedUUID()
path := fmt.Sprintf(`C:/Windows/Temp/packer-elevated-shell-%s.ps1`, uuid)
// Generate command // Generate command
err = elevatedTemplate.Execute(&buffer, elevatedOptions{ err = elevatedTemplate.Execute(&buffer, elevatedOptions{
User: escapedElevatedUser, User: escapedElevatedUser,
Password: escapedElevatedPassword, Password: escapedElevatedPassword,
TaskName: taskName, TaskName: taskName,
TaskDescription: "Packer elevated task", TaskDescription: "Packer elevated task",
ScriptFile: path,
LogFile: logFile, LogFile: logFile,
XMLEscapedCommand: escapedCommand, XMLEscapedCommand: escapedCommand,
}) })
@ -180,8 +193,6 @@ func GenerateElevatedRunner(command string, p ElevatedProvisioner) (uploadedPath
fmt.Printf("Error creating elevated template: %s", err) fmt.Printf("Error creating elevated template: %s", err)
return "", err return "", err
} }
uuid := uuid.TimeOrderedUUID()
path := fmt.Sprintf(`C:/Windows/Temp/packer-elevated-shell-%s.ps1`, uuid)
log.Printf("Uploading elevated shell wrapper for command [%s] to [%s]", command, path) log.Printf("Uploading elevated shell wrapper for command [%s] to [%s]", command, path)
err = p.Communicator().Upload(path, &buffer, nil) err = p.Communicator().Upload(path, &buffer, nil)
if err != nil { if err != nil {