Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Profile.boot for postgres in a docker
(require '[boot.pod :as pod])
(def pod-deps '[[boot/core "2.6.0" :scope "test"]
[adzerk/env "0.3.0" :scope "test"]
[me.raynes/conch "0.8.0" :scope "test"]])
(deftask postgres []
(let [pod (future (pod/make-pod (update-in (get-env) [:dependencies] into pod-deps)))]
(with-pass-thru _
(pod/with-eval-in @pod
(require '[adzerk.env :as env]
'[me.raynes.conch :as sh]
'[boot.core :as core]
'[boot.util :as util])
(sh/programs docker)
(def db-name "my-db")
;; Note that these are treated as system properties, see
;; and adopt the syntax for cprop:
database_username ""
database_password "")
(defn postgres-endpoint! []
(let [{:keys [stdout exit-code]} (docker "inspect" "--format" "{{ .NetworkSettings.IPAddress }}" "postgres"
{:verbose true
:throw false
:seq true})]
(when (= 0 @exit-code) ;; return nil if it fails
(str (first stdout) ":5432"))))
(defn set-env-vars! []
(case (core/get-env :type)
"prod" (env/def database_jdbc.url "")
"test" (env/def database_jdbc.url (str "jdbc:postgresql://" (postgres-endpoint!) "/" db-name "-test"))
(env/def database_jdbc.url (str "jdbc:postgresql://" (postgres-endpoint!) "/" db-name))))
;; Kill and remove the current docker instance
(let [{:keys [exit-code]} (docker "kill" "postgres" {:verbose true :throw false})
{:keys [exit-code]} (when (= 0 @exit-code)
(docker "rm" "postgres" {:verbose true :throw false}))]
(if (and (not (nil? exit-code)) (= 0 @exit-code))
(util/info "Postgres docker successfully removed!\n")
(util/info "No Postgres docker to remove.\n")))
;; Add a new docker instance
(let [postgres-user (get (env/env) "database_username")
postgres-psw (get (env/env) "database_password")]
(util/dbug "Bootstrapping postgres docker...")
(let [{exit-code :exit-code} (docker "run" "-d"
"--name" "postgres"
"-e" (str "POSTGRES_PASSWORD=" postgres-psw)
"-e" (str "POSTGRES_USER=" postgres-user)
"-e" (str "POSTGRES_DB=" db-name)
{:verbose true :throw true})]
(when (= 0 @exit-code)
(let [endpoint (postgres-endpoint!)]
(util/dbug "Postgres endpoint: %s\n" endpoint)
(util/info "Postgres running!\n")))))
;; Sneaky call - dangerous because it performs side effects - don't do this at home
;; The upside of executing it in a pod is that we don't introduce unnecessary dependencies
;; (transitive as well) to the main environment
(boot (postgres))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment