I’ve continued to work on my create server script from time to time. The latest update was checking that we could connect to the Hetzner API using the key that is given and bailing out if we cannot.
curl is a interesting and useful tool. curl has been around since 1996 and it is ubiquitous. curl is simple to use: curl https://l10systems
will download this website. It’s also very powerful with many, many options..
For testing the API key, I wanted to make a call, get the response code back and discard the contents. If the response code is 200, then continue with the script. Otherwise, bail.
The snippet looks like:
# ensure we can connect to Hetzner
api_response=$(curl -s -o /dev/null -w "%{response_code}" -H "Authorization: Bearer $API_TOKEN" \
"https://api.hetzner.cloud/v1/actions")
if [[ $api_response != "200" ]];
then
echo "Could not connect to Hetzner API. Check key."
exit 1
fi
The curl options I use here are:
- -s: silent mode to suppress the progress reporting
- -o /dev/null: redirect the content output to /dev/null instead of stdout
- -w “%{response_code}”: write the response_code variable out
- -H: add a header to the call
I’ll continue to iterate on the create server script to add a few more things but it’s working well right now.