Skip to content

Instantly share code, notes, and snippets.

@andrewsomething
Last active May 18, 2021 10:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewsomething/75a1d6acd1155013fabd to your computer and use it in GitHub Desktop.
Save andrewsomething/75a1d6acd1155013fabd to your computer and use it in GitHub Desktop.
Assign a DigitalOcean Floating IP to a Droplet
#!/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])
@derekdon
Copy link

derekdon commented Jan 16, 2018

Don't suppose you know of any docker image (keepalived, corosync and pacemaker, heartbeat) that has been setup to work with digital ocean floating ip re-assignment? Working with a stack in docker cloud that needs a HA setup.

@jarnovanleeuwen
Copy link

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"

@kpoleyn
Copy link

kpoleyn commented May 18, 2021

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