Gowtham Velmurugan
Gowtham Velmurugan

Reputation: 31

The user data commands do not execute after droplet creation

With the use of the Digital Ocean api I am facing an error with user_data. After a droplet creation nginx is not installed. I wanted the following code to run on my server after a droplet is created with the use of user data.

!/bin/bash
apt-get -y update
apt-get -y install nginx

so I used that code in:

$userData = "#!/bin/bash
apt-get -y update
apt-get -y install nginx";

For passing the data to the api I use this code below:

$data = array(
    "name" => "NewDroplet",  
    "region" => "ams3", 
    "size" => "512mb", 
    "image" => "ubuntu-14-04-x64", 
    "user_data" => $userData
);

I am new to coding with api's :-) So correct me if i am wrong somewhere.

Upvotes: 2

Views: 1315

Answers (2)

andrewsomething
andrewsomething

Reputation: 2256

It's hard to know exactly where your error is without seeing the rest of the code or the error logs. In general, you seem to going in the right direction. Here's a working example:

<?php
$user_data = <<<EOD
#!/bin/bash

apt-get -y update
apt-get -y install nginx
EOD;

$data = array(
    'name'               => 'nginx-droplet',
    'region'             => 'nyc3',
    'size'               => '512mb',
    'image'              => 'ubuntu-14-04-x64',
    'user_data'          => $user_data
);

$data_string = json_encode($data);

$ch = curl_init('https://api.digitalocean.com/v2/droplets');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization: Bearer YOUR_TOKEN_API_HERE',
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch);
print_r($result);
?>

For more information on the DigitalOcean metadata service see: An Introduction to Droplet Metadata

You might also want to check out the community contributed PHP bindings for DgitialOcean's APIv2.

Full-disclosure, among other things, I'm a Community Manager at Digitalocean

Upvotes: 1

user254948
user254948

Reputation: 1056

From the dropbox website:

user_data
String

A string of the desired User Data for the Droplet. User Data is currently only available in regions with metadata listed in their features.

This is just information that gets stored in a metadata service, which can then later be obtained in for example a bash script.

I was unable to find an automated way through the digitalocean api to install programs. I assume you would need to set up key based authorization in your digital ocean configuration panel. You could then connect and execute commands using ssh from the same script you create the droplet with.

Upvotes: 0

Related Questions