Skip to content

Instantly share code, notes, and snippets.

@dustyfresh
Last active December 29, 2020 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dustyfresh/36f19fcc14251449ab7854d1dcb9f101 to your computer and use it in GitHub Desktop.
Save dustyfresh/36f19fcc14251449ab7854d1dcb9f101 to your computer and use it in GitHub Desktop.
Simple python script for launching a Vultr instance using the v2 API https://www.vultr.com/api/v2
#!/usr/bin/python
import os
import json
import requests
from time import sleep
def main():
# API configuration
VULTR_SECRET = os.getenv("VULTR_SECRET")
# SSH_KEYS must be a list of SSH key uuids as tracked by Vultr.
# You can find those at the /ssh-keys endpoint
# https://www.vultr.com/api/v2/#operation/list-ssh-keys
SSH_KEYS = [
"changeme"
]
SERVER_LABEL = "changeme"
SERVER_HOSTNAME = "changeme"
# you can find deets on these options here:
# https://www.vultr.com/api/v2/#operation/create-instance
instance = {
"region": "ewr",
"plan": "vhf-3c-8gb",
"label": SERVER_LABEL,
"os_id": 352, # Debian 10 x64 (buster)
"backups": "disabled",
"enable_ipv6": False,
"ddos_protection": False,
"activation_email": False,
"hostname": SERVER_HOSTNAME,
"sshkey_id": SSH_KEYS
}
# Common headers we use for our request, includes the api secret
headers = {
"User-Agent": "",
"Authorization": f"Bearer {VULTR_SECRET}",
"Content-Type": "application/json"
}
# This request creates the instance from the specified instance parameters
r = requests.post(
"https://api.vultr.com/v2/instances",
headers=headers,
data=json.dumps(instance)
)
# Instance metadata response
instance = r.json()["instance"]
instance_id = instance["id"]
# Wait for instance to come online
print(f"Waiting on instance {instance_id} to become active...")
while True:
instance = requests.get(
f"https://api.vultr.com/v2/instances/{instance_id}",
headers=headers
)
instance = instance.json()["instance"]
if instance["status"] != "active":
print(f"{instance_id} -- {instance['status']}...")
sleep(5)
elif instance["status"] == "active":
print(f"{instance_id} is active!")
print(json.dumps(instance, indent=4))
break
print('\nInstance launched!')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment