Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
AWS Lambda + babashka + minimal container image
(require '[babashka.curl :as curl] '[cheshire.core :as json])
;; logging
(def prefix "lambda-example")
(defn log [level msg] (println (format "[%s]:%s %s" prefix level msg)))
(defn logf [level msg & args]
(log level (apply format (concat [msg] args))))
;; Lambda-specific functions
(def runtime-api (System/getenv "AWS_LAMBDA_RUNTIME_API"))
(defn get-arguments []
(let [next-url (format "http://%s/2018-06-01/runtime/invocation/next" runtime-api)
response (curl/get next-url)
body (-> response
(json/parse-string true))
args {:payload body
:request {:id (get-in response [:headers "lambda-runtime-aws-request-id"])
:function-arn (get-in response [:headers "lambda-runtime-invoked-function-arn"])}}]
(logf :warn "args=%s" args)
(defn notify-success [{:keys [id]}]
(let [success-url (format "http://%s/2018-06-01/runtime/invocation/%s/response" runtime-api id)]
(curl/post success-url {:body "SUCCESS"})))
(defn notify-error [{:keys [id]} {:keys [error message]}]
(let [error-url (format "http://%s/2018-06-01/runtime/invocation/%s/error" runtime-api id)]
(curl/post error-url {:body (json/generate-string {:errorMessage message
:errorType error})})))
;; Biz logic
(defn handler [payload]
(logf :debug "payload=%s" payload)
;; Entry points
(defn lambda-main
"Entry point for lambda"
(log :info "starting in lambda")
(let [{:keys [payload request]} (get-arguments)]
(if (handler payload)
(notify-success request)
(notify-error request {:error "handler failed" :message "really-bad"}))
(catch Exception e
(notify-error request {:error "handler crashed"
:message (str e)})))))
(defn main
"Entrypoint for scripts"
(log :info "starting script")
(handler *command-line-args*))
;; Actually run things
(if runtime-api
FROM alpine:3.11.3
RUN apk update && apk add curl ca-certificates unzip && rm -rf /var/cache/apk/*
RUN curl -L '' -o /tmp/ && \
unzip /tmp/ && \
mv bb /usr/bin/bb && \
chmod +x /usr/bin/bb
RUN mkdir -p /app
COPY core.clj .
COPY /usr/bin/
ENTRYPOINT ['/usr/bin/']
#!/usr/bin/env sh
/usr/bin/bb /app/core.clj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment