Invoke a script or command using after creating a droplet

December 12, 2017 1.5k views
API Ubuntu 16.04

When using the DigitalOcean API to create a new droplet, is there a way to have the droplet run a command or script once it spins (using the API)?

Thanks.

4 Answers

you specify it in the user-data tab, your droplet will run cloud-init on boot, and you can specify your script should only run once. You can do loads of stuff in your cloud-init config

Hi @alastairc, thanks for replying.

Just a few more questions

you specify it in the user-data tab,

Where do I find the user-data tab?

Can those be built by using the DO API as well (i.e. built programmatically)?

Thanks!

  • When you create the droplet, it's the checkbox labeled "User Data".

    You can definitely specify it via the API too. It's YAML so you have to be super careful about whitespace.

    • Is there a way to create the configs just by using the API?
      That's what I'm really going for, full programmatic provisioning with custom scripts/commands, no user-interaction whatsoever.

      • The user-data is always visible from the droplet (you make a request to a magical IP and you get back what you sent when you built the droplet), but you can't retrieve it from any other place or in any other way.

        You just have to post the same stuff each time, maybe stick it in git along side whichever script you're writing to do the scaling.

Happy to provide a bit more clarification:

User-data can be either YAML or a script format supported by the droplet's OS by default (ex. Bash). When using a non-YAML script whitespace is only as much of a concern as it would be for any other script in the language you use.

You can paste a user-data script into the create page in the control panel. Check the user-data checkbox in the optional settings and the text box will appear to allow pasting the script.

You can also send user-data via the API populating the user-data field in your request to the create endpoint.

On first boot after it fetches it's network configuration and other basic settings cloud-init will automatically run your script. Make sure that it is non-interactive as any prompt for user input will cause it to stall since there is no user to enter the needed information. You can log into your droplet and view the output of your script (if you're installing a lot of things you can use tail to watch it actually run in real-time if you're quick enough) in the file /var/log/cloud-init-output.log

You can also send user-data via the API populating the user-data field in your request to the create endpoint.

Exactly what I was looking for!

Thank you @ryanpq

And also thanks @alastairc for your suggestions as well.

Have another answer? Share your knowledge.