Skip to content

Instantly share code, notes, and snippets.

@lukaszkorecki
Created February 17, 2021 17:04
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukaszkorecki/a1fe27bf08f9b98e9def9da4bcb3264e to your computer and use it in GitHub Desktop.
Save lukaszkorecki/a1fe27bf08f9b98e9def9da4bcb3264e to your computer and use it in GitHub Desktop.
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
:body
(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)
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)
payload)
;; Entry points
(defn lambda-main
"Entry point for lambda"
[]
(log :info "starting in lambda")
(let [{:keys [payload request]} (get-arguments)]
(try
(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
(lambda-main)
(main))
FROM alpine:3.11.3
RUN apk update && apk add curl ca-certificates unzip && rm -rf /var/cache/apk/*
RUN curl -L 'https://github.com/babashka/babashka/releases/download/v0.2.10/babashka-0.2.10-linux-static-amd64.zip' -o /tmp/bb.zip && \
unzip /tmp/bb.zip && \
mv bb /usr/bin/bb && \
chmod +x /usr/bin/bb
RUN mkdir -p /app
WORKDIR /app
COPY core.clj .
COPY entrypoint.sh /usr/bin/entrypoint.sh
ENTRYPOINT ['/usr/bin/entrypoint.sh']
#!/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