将PowerShell脚本发送到Windows EC2的用户数据中
我正在按照这些说明,用一个PowerShell脚本(叫做“bootstrap.ps1”)来启动一个Windows的EC2实例。但是,当我第一次登录到机器时,似乎这个脚本根本没有运行。我查看了C:\Program Files\Amazon\Ec2ConfigService\Logs\Ec2ConfigLog,发现了以下内容:
2014-03-11 00:08:02: Ec2HandleUserData: Start running user scripts
2014-03-11 00:08:02: Ec2HandleUserData: Could not find <script> and </script>
2014-03-11 00:08:02: Ec2HandleUserData: Could not find <powershell> and </powershell>
我的脚本长这样:
<powershell>
(multiple lines of powershell script here)
</powershell>
我在Python中对这个脚本进行了base64编码,并通过boto发送它:
import base64
# (create connection to aws region in boto called 'conn')
conn = ...
# run the instance and provide base64-encoded bootstrap powershell script in user_data
with open("bootstrap.ps1", "r") as fd:
conn.run_instances(..., user_data=base64.encodestring(fd.read()))
我确保了以下几点:
- 我发送的脚本(“bootstrap.ps1”)使用的是\r\n作为换行符
- 在
http://169.254.169.254/latest/user-data
上获取的脚本,经过base64解码后,与我写的原始“bootstrap.ps1”是一样的(通过下载后,再用Python的base64.decodestring
运行验证) - 在“bootstrap.ps1”中,
<powershell>
和</powershell>
前后没有多余的字符。
显然,我在user_data中包含了<powershell>
和</powershell>
。这些是经过base64编码的,但不知为何ec2config没有找到它们?有没有人能看出我哪里做错了?
1 个回答
6
问题出在 user_data
的编码上,这个编码已经由 boto
处理过了。根据 boto 的文档,user_data
应该是“要提供给这个预定实例的 Base64 编码的 MIME 用户数据”,我觉得这个说法 非常 容易让人误解,因为在调用 run_instances
时,编码不需要也 不应该 进行。现在,下面的 Python 代码对我来说是有效的:
# create connection...
conn = ...
# run instance
with open("bootstrap.ps1", "r") as fd:
# don't encode user_data
conn.run_instances(..., user_data=fd.read())