调用 client.request_spot_instances 方法时抛出 AWS Boto3 BASE64 编码错误

use*_*107 4 python base64 amazon-ec2 amazon-web-services boto3

我正在尝试使用 boto3(Environment Python 3.5,Windows 7)提交对 EC2 SPOT 实例的请求。我需要传递UserData参数来运行初始脚本。

我得到的错误是文件 "C:\Users...\Python\Python35\lib\site-packages\botocore\client.py", line 222, in _make_api_call raise ClientError(parsed_response, operation_name) botocore.exceptions.ClientError:调用RequestSpotInstances 操作时发生错误 (InvalidParameterValue) : Invalid BASE64 encoding of user data Code

我正在关注此文档 https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.request_spot_instances

如果我去掉 UserData 参数 - 一切正常。

我尝试了不同的方法来传递参数,但最终还是出现了相同的.类似错误。

Boto 3 脚本

    client = session.client('ec2')

    myparam = str(base64.b64encode(bytes('yum install -y php', 'utf-8')))

    response = client.request_spot_instances(
    SpotPrice='0.4',
    InstanceCount=1,
    Type='one-time',
    LaunchSpecification={
    'ImageId': 'ami-xxxxxx',
    'KeyName': 'xxxxx',
    'InstanceType': 't1.micro',
    'UserData': myparam,
    'Monitoring': {
    'Enabled': True
    }
    })
Run Code Online (Sandbox Code Playgroud)

Lau*_*RTE 7

我认为您不应该将 base64 字符串转换为str. 你在使用 Python 3 吗?

代替:

myparam = str(base64.b64encode(bytes('yum install -y php', 'utf-8')))
Run Code Online (Sandbox Code Playgroud)

经过:

myparam = base64.b64encode(b'yum install -y php').decode("ascii")
Run Code Online (Sandbox Code Playgroud)

  • 文档不清楚类型。它说“字符串”。尝试:`base64.b64encode(b'yum install -y php').decode("ascii")`。 (4认同)