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

4
我正在尝试使用boto3(环境Python 3.5,Windows 7)提交EC2 SPOT实例请求。 我需要传递UserData参数以运行初始脚本。
我遇到的错误是: File "C:\ Users ... \ Python \ Python35 \ lib \ site-packages \ botocore \ client.py",第222行,在_make_api_call中 引发ClientError(parsed_response,operation_name) botocore.exceptions.ClientError:调用RequestSpotInstances操作时出现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
    }
    })
1个回答

8
我认为你不应该将你的 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")

它给我一个错误:参数LaunchSpecification.UserData的类型无效,值为b'fdfd',类型为<class 'bytes'>,有效类型为<class 'str'> - 因为它期望一个字符串。 - user1811107
4
文档没有明确指出类型,它只写了 "String"。尝试:base64.b64encode(b'yum install -y php').decode("ascii") - Laurent LAPORTE
成功了!谢谢 - 我的编辑使代码更易读,像这样 base64.b64encode('yum install -y php'.encode()).decode("ascii"). - user1811107

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接