使用RequestSpotInstances API传文件格式UserData时出现BASE64编码错误
Fixing Invalid BASE64 Encoding Error for AWS Spot Instance UserData
The problem here is that unlike the AWS CLI, the boto3 request_spot_instances API doesn’t automatically parse the file:// prefix for UserData. You’ll need to manually read your script file, encode its content to base64, and pass that encoded string directly to the API.
Here’s how to adjust your code to resolve this error:
First, import Python’s built-in base64 module (no extra installation required). Then read your file content and encode it properly:
import boto3 import base64 session = boto3.Session() client = session.client('ec2', region_name='us-west-2') # Read and encode the user data file to base64 with open('my_script0.txt', 'rb') as f: user_data_base64 = base64.b64encode(f.read()).decode('utf-8') response = client.request_spot_instances( InstanceCount=1, LaunchSpecification={ 'ImageId': 'ami-012345', 'InstanceType': 't2.medium', 'Placement': {'AvailabilityZone': 'us-west-2a'}, 'SecurityGroupIds': ['sg-012345'], 'SubnetId': 'subnet-012345', 'UserData': user_data_base64 # Use the encoded string here }, SpotPrice='0.0139', Type='persistent', InstanceInterruptionBehavior='stop' )
Key Details:
- We read the file in binary mode (
'rb') to handle all content types (like scripts with special characters) correctly. base64.b64encode()returns bytes, so we call.decode('utf-8')to convert it to a string—this is the format the API expects for UserData.- If you want your script to run automatically when the instance launches, make sure it starts with a shebang line (e.g.,
#!/bin/bashfor bash scripts) — this is a standard AWS user data requirement.
This should eliminate the "Invalid BASE64 encoding of user data" error you’re encountering.
内容的提问来源于stack exchange,提问作者Ashish Mittal
相关产品推荐
相关产品推荐

