Last active
May 18, 2021 10:38
-
-
Save andrewsomething/75a1d6acd1155013fabd to your computer and use it in GitHub Desktop.
Assign a DigitalOcean Floating IP to a Droplet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import os | |
import sys | |
import requests | |
import json | |
api_base = 'https://api.digitalocean.com/v2' | |
def usage(): | |
print('{0} [Floating IP] [Droplet ID]'.format(sys.argv[0])) | |
print('\nYour DigitialOcean API token must be in the "DO_TOKEN"' | |
' environmental variable.') | |
def main(floating_ip, droplet_id): | |
payload = {'type': 'assign', 'droplet_id': droplet_id} | |
headers = {'Authorization': 'Bearer {0}'.format(os.environ['DO_TOKEN']), | |
'Content-type': 'application/json'} | |
url = api_base + "/floating_ips/{0}/actions".format(floating_ip) | |
r = requests.post(url, headers=headers, data=json.dumps(payload)) | |
resp = r.json() | |
if 'message' in resp: | |
print('{0}: {1}'.format(resp['id'], resp['message'])) | |
sys.exit(1) | |
else: | |
print('Moving IP address: {0}'.format(resp['action']['status'])) | |
if __name__ == "__main__": | |
if 'DO_TOKEN' not in os.environ or not len(sys.argv) > 2: | |
usage() | |
sys.exit() | |
main(sys.argv[1], sys.argv[2]) |
If you do not want to install Python, see the Bash version of the script below (requires curl instead, though):
#!/usr/bin/env bash API_BASE="https://api.digitalocean.com/v2" if [[ -z "${DO_TOKEN}" ]] || [[ $# != 2 ]]; then echo "Usage: $0 <Floating IP> <Droplet ID>" echo "Your DigitalOcean API token must be in the \"DO_TOKEN\" environmental variable." exit 1 fi curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer ${DO_TOKEN}" -d "{\"type\":\"assign\",\"droplet_id\":$2}" "${API_BASE}/floating_ips/$1/actions"
Thx Jarno, wasted a few hours before I found your solution
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you do not want to install Python, see the Bash version of the script below (requires curl instead, though):