user1811107 user1811107 - 2 months ago 15
Python Question

AWS Boto3 BASE64 encoding error thrown when invoking client.request_spot_instances method

I am trying to submit a request for an EC2 SPOT instance using boto3 (Environment Python 3.5,Windows 7).
I need to pass the UserData parameter for running initial scripts.

The error I get is
File "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: An error occurred (InvalidParameterValue) when
calling the
RequestSpotInstances operation: Invalid BASE64 encoding of user data Code

I am following this documentation
https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.request_spot_instances

If I take the UserData parameter out – everything works well.

I have tried different ways to pass the parameter but I end up with the same.similar errors.

Boto 3 Script

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
}
})

Answer

I think you shouldn't convert your base64 string to str. Are you using Python 3?

Replace:

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

By:

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