我正在尝试从自定义AMI创建ec2实例时从用户数据框运行powershell脚本。我在创建ami之前已在配置上启用了用户数据执行。
这是我投入用户数据
<powershell>
c:\scripts\github-download.ps1 someuser somepassword
</powershell>
它正在调用的脚本如下所示。
Param($gituser, $gitpass)
C:\Users\Administrator\AppData\Local\GitHub\shell.ps1
git clone https://"$gituser":"$gitpass"@github.com/somegitrepo |out-null
我不知道为什么这不起作用。我在这里做错了吗?任何帮助真的很感激。
答案 0 :(得分:3)
不使用<powsershell>
标记调用用户数据,而是使用<script>
标记调用PowerShell本身。您可以获得对其调用的命令行控制,并可以直接控制执行策略和其他命令行设置:
<script>
PowerShell -ExecutionPolicy Bypass -NoProfile -File c:\scripts\github-download.ps1 -user USER -password PASSWORD
</script>
在您的脚本中,设置脚本的开头和结尾部分,如下所示:
# Server script called from userdata in this format
# <script>
# PowerShell -ExecutionPolicy Bypass -NoProfile -File c:\scripts\github-download.ps1 -user USER -password PASSWORD
# </script>
param (
[string]$user = $(throw "-user is required."),
[string]$password = $(throw "-password is required."),
)
Start-Transcript -Path C:\userscriptlog.txt
Import-Module WebAdministration
if ([System.Diagnostics.EventLog]::SourceExists("Userdata") -eq $False) {
New-Eventlog -Logname Application -Source 'Userdata'
}
Write-Eventlog -Logname Application -Source 'Userdata' -EventId 1 -EntryType Information -Message 'Begining post-deployment configuration script'
-- YOUR MAIN SCRIPT HERE --
Write-Eventlog -Logname Application -Source 'Userdata' -EventId 1 -EntryType Information -Message 'Post-deployment configuration script complete'
Stop-Transcript
对于脚本中的错误处理,您需要对每个命令使用强大的异常处理和日志记录,以便轻松进行故障排除和调试。此块只是获取当前实例ID,但请注意内置的异常处理和日志记录:
# get instance-id
try {
$InstanceId = (Invoke-WebRequest http://169.254.169.254/latest/meta-data/instance-id).content
} catch {
$_.Exception.message | out-file c:\InstanceId_error.log
Write-Host "FATAL: InstanceId exception"
Exit
}
if (!$InstanceId) {
Write-Host "FATAL: InstanceId is null"
Exit
} else {
$InstanceId | out-file C:\InstanceId.txt
Write-Host "InstanceId: $InstanceId"
}
尝试使用您需要实现的任何命令或shell调用。
这个PowerShell脚本&#39;包装&#39;对于用户数据脚本,允许可选的命令行参数,生成执行的脚本,并将事件记录到Windows事件日志,以确认脚本的基本执行。
它将为任何基于Powershell的用户数据脚本提供灵活的框架,便于调试和测试。
答案 1 :(得分:0)
| out-null
会消除git clone可能发生的任何错误,因此除非您将错误传输到其他地方或者不使用| out-null
,否则您不会知道错误。
在尝试使用用户数据自动执行任何操作之前,我会在没有| out-null
的EC2实例上手动运行该命令。