0
votes

When I create and instance with UserData, I am doing so like this:

_i = ec2.create_instances(
  ImageId=my_ami,
  MinCount=1, 
  MaxCount=1,
  KeyName=my_key,
  InstanceType="t2.small",
  UserData=u_data)

This instance is then launched. I ssh into the instance and my UserData file does not seem to be executed. I logged everything in the console using boto3.set_stream_logger('botocore') and inspected the base64 encoding of my UserData parameter. It looks like this:

#!/bin/bash
echo "Hello World" >> /tmp/data.txt

I can copy that to a shell file on the ec2 instance, make it executable, and execute it just fine. I am really confused why my UserData argument is not applied when I create the instance. Any help is much appreciated.

2

2 Answers

0
votes

This is very silly, but I found the problem. When I create a string variable to hold the UserData, I had a line break at the top of the file before the shebang. The shebang must be the very fist line of the UserData file. Learn something every day!

Hopefully this helps someone down the road.

0
votes

Hope this helps somebody else.

u_data = '''#!/bin/bash
    echo "Hello World" >> /tmp/data.txt'''

_i = ec2.create_instances(
  ImageId=my_ami,
  MinCount=1, 
  MaxCount=1,
  KeyName=my_key,
  InstanceType="t2.small",
  UserData=u_data) # the script we wrote above