【问题标题】:AWS Boto3 BASE64 encoding error thrown when invoking client.request_spot_instances method调用 client.request_spot_instances 方法时引发 AWS Boto3 BASE64 编码错误
【发布时间】:2017-02-07 06:28:24
【问题描述】:

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

我得到的错误是 _make_api_call 中的文件“C:\Users...\Python\Python35\lib\site-packages\botocore\client.py”,第 222 行 引发 ClientError(parsed_response, operation_name) botocore.exceptions.ClientError:发生错误(InvalidParameterValue)时 调用 RequestSpotInstances 操作:用户数据代码的 BASE64 编码无效

我正在关注此文档 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
    }
    })

【问题讨论】:

    标签: python amazon-web-services amazon-ec2 base64 boto3


    【解决方案1】:

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

    替换:

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

    作者:

    myparam = base64.b64encode(b'yum install -y php').decode("ascii")
    

    【讨论】:

    • 它给了我一个错误 Invalid type for parameter LaunchSpecification.UserData, value: b'fdfd', type: , valid types: - 因为它期望一个字符串
    • 文档中的类型不清楚。它说“字符串”。试试看:base64.b64encode(b'yum install -y php').decode("ascii").
    • 成功了!谢谢-我对其进行了编辑以使代码更具可读性,例如 base64.b64encode('yum install -y php'.encode()).decode("ascii")。
    猜你喜欢
    • 2020-12-11
    • 2014-12-27
    • 2018-09-18
    • 2018-03-20
    • 2019-01-18
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    相关资源
    最近更新 更多