Facing an error with user_data. After droplet creation nginx is not installed. I wanted the following coding to run on my server after droplet creation with the use user data
#!/bin/bash
apt-get -y update
apt-get -y install nginx
export HOSTNAME=$(curl -s http://169.254.169.254/metadata/v1/hostname)
export PUBLIC_IPV4=$(curl -s http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/address)
echo Droplet: $HOSTNAME, IP Address: $PUBLIC_IPV4 > /usr/share/nginx/html/index.html
so i used that code in
$userData = "#!/bin/bash
apt-get -y update
apt-get -y install nginx
export HOSTNAME=$(curl -s http://169.254.169.254/metadata/v1/hostname)
export PUBLIC_IPV4=$(curl -s http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/address)
echo Droplet: $HOSTNAME, IP Address: $PUBLIC_IPV4 > /usr/share/nginx/html/index.html";
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 :-) I dont know what i am doing wrong.
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
Click below to sign up and get $100 of credit to try our products over 60 days!
Thanks . I got an error with this coding though as i dint get the hostname and ip to show on the html file this was the coding used in v 1 api now i am using v2 export HOSTNAME=$(curl -s http://169.254.169.254/metadata/v1/hostname) export PUBLIC_IPV4=$(curl -s http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/address) echo Droplet: $HOSTNAME, IP Address: $PUBLIC_IPV4 > /usr/share/nginx/html/index.html
as i am using v2 api now ,How can i get the hostname with the new API . The new api is not easy to understand for me as i am beginner in coding. Any help would be appreciated Thanks.
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:
Note that the
$HOSTNAME
is escaped like\$HOSTNAME
in order to prevent PHP from attempting to treat it as a variable.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.