How to send UserData for an EC2 instance

I’m trying to use the resource section to include a CloudFormation setup for a custom EC2 configuration. Yeah, I know, it’s not serverless. Sue me, we can’t always do things the way we want to.

Question is: How do I specify the UserData script for the EC2 instance without having the serverless framework try to interpret any variable declarations in there (it’s a Bash script).

Any clues?

1 Like

In case anyone finds this and wants to know how, here’s what I did:

You can use the ‘UserData’ property when defining an EC2 instance in serverless.yml to send the user data. The value of that property can be a file using the ${file(myfile.txt)} syntax.

However, the contents of the file sent have to be base64 encoded because you’re using the bare cloudformation syntax, not serverless syntax.

So, that’s OK. Build a script. Let’s call it “”. You can fill it with whatever you need.
Then, base64 encode it using your favorite command line tool into a new file, maybe called “”.

Now, in the UserData property, use this: “${file(}” and you should get the intended result.

In case anyone finds this you can go one step further :wink:

You don’t have to do the base64 encoding yourself

    Fn::Base64: "${file(}"

If useful to anyone else here is how I did it all within serverless.yml and using pseudo parameters. Note that when using \n you must put the string in double quotes.

  'Fn::Base64': !Join
    - ''
    - - "#!/bin/bash -ex\n"
      - '/opt/aws/bin/cfn-init -v'
      - ' --resource MyInstance'
      - ' --region '
      - !Ref AWS::Region
      - ' --stack '
      - !Ref AWS::StackName
      - "\n"
1 Like