Skip to main content

Automating Host Creation with the API

Creating new hosts on the DN admin panel is quick and easy, but if you are regularly creating ephemeral hosts that live for a short time before being torn down, you might want to consider using the DN API to automate the process of creating and enrolling the hosts into your DN network. This guide will explain how to generate and use a DN API key.

How to create an API key

To create a new key, visit the API Keys page of the DN admin panel. If you have no keys previously set up, click the “Create API key” button. Or, if you have other keys, click the “Add” button in the top right. Choose a descriptive name for the key which will help you remember the reason it was created. After pressing the “Generate token” button, you will be shown the new token in a green banner. Be sure to store this key somewhere safe, because it will only be shown once.

The DN admin panel opened to the API Keys page with a new API key shown

How to use the DN API

Prerequisites

Make sure you have these tools installed before starting.

1. Setup your environment

Open a terminal and export the following variables to be used in our API calls. Grab the $ROLEID from the roles list.

export DNKEY="[paste the key you generated above]" \
export HOSTNAME="[name of the the new host]" \
export ROLEID="[optional role ID copied from the roles list]" \
export NETWORKID="[]"

2. Create a host and enrollment code

Run the following curl command, which references the variables you just set for your environment.

curl -s -d '{
"name": "'$HOSTNAME'",
"roleID": "'$ROLEID'",
"networkID": "'$NETWORKID'"
}' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $DNKEY" \
https://api.defined.net/v1/host-and-enrollment-code \
| jq .

You should get back a response that looks something like:

{
"data": {
"host": {
"id": "host-ABCDEFGHIJKLMNOPQRSTUVWXYZ0",
"organizationID": "org-ABCDEFGHIJKLMNOPQRSTUVWXYZ0",
"networkID": "network-ABCDEFGHIJKLMNOPQRSTUVWXYZ0",
"roleID": "$ROLEID",
"name": "$HOSTNAME",
"ipAddress": "192.168.0.4",
"staticAddresses": [],
"listenPort": 0,
"isLighthouse": false,
"createdAt": "2022-08-11T22:00:13Z"
},
"enrollmentCode": {
"code": "$ENROLLCODE",
"lifetimeSeconds": 600
}
},
"metadata": {}
}

3. Install dnclient and use the enroll code

Link to dnclient installation guide.

On POSIX devices, run sudo ./dnclient enroll -code $ENROLLCODE, and on Windows, run .\dnclient.exe enroll -code $Env:ENROLLCODE.

The host has now been created and enrolled into your DN network.