Connect to newly created droplet via API in Laravel

April 5, 2018 117 views
API DigitalOcean Development PHP PHP Frameworks Programming Project Ubuntu 16.04

Hello, I am trying to get something done in my project, When a user completes a step program in my app, A new droplet will be created. I need to connect to this newly created droplet so I can perform commands on it using my code. How can I achieve that with the DigitalOcean API in Laravel?

In my code, I look for all images and create a new droplet with the image that has the ID of 0 (This is the base that is needed for every newly created droplet). See the code below.

Code

$images = DigitalOcean::image()->getAll(['private' => true]);
$storeName = str_replace(' ', '-', $mainsetting['store_name']);

$droplet = DigitalOcean::droplet()->create($storeName, 'ams3', 's-1vcpu-1gb', $images[0]->id);

Somehow I need to be able to retrieve the login information from the newly created droplet and try to log in on it with my code. Or something else that allows me to perform commands on the newly created droplet. The way I perform the commands on a droplet is putting the commands in an array called $commands and execute the following code:

Code

\SSH::run($commands, function($line){
            \Log::debug($line);
});

I think it is needed to add every newly created droplet to the DigitalOcean config file within my laravel application and connect to it using the config file. But that could be me complicating things.

How can I achieve the above in Laravel using the DigitalOcean API? Thanks in advance!

1 Answer

There are two ways to achieve what you're looking to do. The simpler of which will prevent you from needing to make an ssh connection after creation.

  1. Use cloud-init user-data to automatically run your commands as soon as the droplet launches. User-data can be in the form of a YAML file or a script in a language like Bash that can be run by the server with it's default packages. By doing this you will only need to provide your script in the user-data field in the API call used to create it.

  2. Poll for droplet status. Droplet creation can take up to a minute at times. Because of this, tracking the status of a droplet you created may require an additional tool to poll the API every few seconds when a creation is ongoing to check the status of the droplet using the id that the create event returned. During creation the status will be "new". Once the status changes you will be able to make an ssh connection.

For #2 you will want to ensure that you are using an ssh-key when creating your droplet. This avoids having to wait for a password to be emailed and the requirement to change that password on your first login.

Have another answer? Share your knowledge.