Skip to content

Instantly share code, notes, and snippets.

@retrogradeorbit
Last active July 8, 2020 08:22
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 retrogradeorbit/c4df067f8b8477749e3042e58d3831bf to your computer and use it in GitHub Desktop.
Save retrogradeorbit/c4df067f8b8477749e3042e58d3831bf to your computer and use it in GitHub Desktop.
digital ocean API example using spire
(ns digitalocean
(:require [spire.modules :refer :all]
[clojure.data.json :as json]))
(defn- make-url [suffix & args]
(apply format (str "https://api.digitalocean.com/v2/" suffix) args))
(defn request [args]
(curl (merge {:url (make-url "droplets")
:headers {:authorization (format "Bearer %s" (System/getenv "DO_TOKEN"))
:content-type "application/json"}
:decode-opts {:key-fn keyword}}
args)))
(defn get-droplets []
(-> (request {})
(get-in [:decoded :droplets])))
(defn get-droplet [{:keys [id]}]
(-> (request {:url (make-url "droplets/%d" id)})
(get-in [:decoded :droplet])))
(defn create-droplet [drop]
(-> (request {:method :POST
:data-binary (json/write-str drop)})
(get-in [:decoded :droplet]))
)
(defn wait-for-droplet [drop]
(loop [next-drop (get-droplet drop)]
(if (empty? (get-in next-drop [:networks :v4]))
(do
(Thread/sleep 1000)
(recur (get-droplet drop)))
next-drop
)))
(defn delete-droplet [{:keys [id]}]
(-> (request {:method :DELETE
:url (make-url "droplets/%d" id)})))
(defn account-keys []
(-> (request {:url (make-url "account/keys")})
(get-in [:decoded :ssh_keys])))
(defn get-key-by-name [ssh-keys name]
(->> ssh-keys
(filter #(= name (:name %)))
first))
(defn extract-ident-set [ident-set droplet]
(map (fn [ident] (if (vector? ident)
(get-in droplet ident)
(get droplet ident))) ident-set))
(defn drop-matches? [droplet find ident-set]
(let [matcher (partial extract-ident-set ident-set)]
(= (matcher droplet)
(matcher find))))
(def instantiated-mappings
{:name [:name]
:region [:region :slug]})
(defn create-or-return-droplet [drop ident-set]
(let [droplets (get-droplets)
matching
(->> droplets
(filter
(fn [result]
(= (extract-ident-set ident-set drop)
(extract-ident-set (map instantiated-mappings ident-set) result))))
first)
]
(if matching
matching
(-> drop
create-droplet
wait-for-droplet))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment