Berlin
Berlin

Reputation: 1464

AWS boto3 request_spot_fleet pass jinja template as userdata - Invalid BASE64 encoding of user data

I am trying to create AWS request spot fleet and specify the jinja template as the user-data and pass to the instance and I am following this documentation: http://boto3.readthedocs.io/en/latest/reference/services/ec2.html

look for - request_spot_fleet(**kwargs):

'UserData': 'string',

UserData (string) -- The user data to make available to the instances. If you are using an AWS SDK or command line tool, Base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide Base64-encoded text.

     template_file = (current_dir + '/config/user.jinja')
     template = templateEnv.get_template( template_file )
     template_vars = template_vars = { 'var1' : var1 }
     output_template = template.render( template_vars )
     self.output_template = base64.b64encode(output_template).decode("ascii")

Error:

    self.output_template = base64.b64encode(output_template).decode("ascii")
    File "/usr/lib/python3.5/base64.py", line 59, in b64encode
    encoded = binascii.b2a_base64(s)[:-1]
    TypeError: a bytes-like object is required, not 'str'

If I pass the jinja template as is:

self.output_template = output_template

com.amazonaws.services.ec2.model.AmazonEC2Exception: 
Invalid BASE64 encoding of user data 
(Service: AmazonEC2; Status Code: 400; Error Code: InvalidParameterValue)

Everything works well if I change the UserData to string:

self.output_template = base64.b64encode(b'test').decode("ascii")
'UserData': self.output_template,

Any suggestions?

Upvotes: 0

Views: 1142

Answers (1)

mootmoot
mootmoot

Reputation: 13166

Python 3 has explicitly require you to specify bytes and string object to prevent codepage encoding issues.

# this line only works in python2 
self.output_template = base64.b64encode(output_template).decode("ascii")

# You must convert str to bytes in Python3 
self.output_template = base64.b64encode(output_template.encode("ascii")).decode("ascii")

Note : remember to specify your python version when asking question.

Upvotes: 2

Related Questions