fbonalair / traefik-crowdsec-bouncer

A http service to verify request and bounce them according to decisions made by CrowdSec.
MIT License
266 stars 21 forks source link

read API_KEY from file #48

Open totoschka opened 1 year ago

totoschka commented 1 year ago

I use the secrets mechanism of docker und would like to read environment-variables from a file. CROWDSEC_BOUNCER_API_KEY_FILE e.g.

MrInterBugs commented 11 months ago

Whilst it would be great to get this officially supported here is a head start for people not wanting to wait:

Creating a go app

We will replace the start up file to read the value from the file then call the other go app.

  1. Create a empty folder: mkdir secrets_startup
  2. Initialise the go folder: go mod init example.com/m
  3. Create a file contain the script traefik.go
package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "os/exec"
        "strings"
)

func main() {
    keyBytes, err := ioutil.ReadFile("/run/secrets/traefik.bouncer")
    if err != nil {
        fmt.Fprintf(os.Stderr, "Failed to read API key: %v\n", err)
        os.Exit(1)
    }
        key := strings.TrimSpace(string(keyBytes))
    os.Setenv("CROWDSEC_BOUNCER_API_KEY", string(key))
    cmd := exec.Command("/app")
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    err = cmd.Run()
    if err != nil {
        fmt.Fprintf(os.Stderr, "Failed to run app: %v\n", err)
        os.Exit(1)
    }
}
  1. Build the app: go build -o traefik-bouncer

Using the go app for startup

  1. Modify the docker-compose.yml:
traefik-bouncer:
    image: fbonalair/traefik-crowdsec-bouncer
    container_name: traefik-bouncer
    volumes:
      - ./secrets_startup/traefik-bouncer:/traefik-bouncer
    command: ["/traefik-bouncer"]
    restart: always
    networks:
      - traefik_default
    environment:
      GIN_MODE: release
      CROWDSEC_AGENT_HOST: crowdsec:8080
      CROWDSEC_BOUNCER_LOG_LEVEL: 2
    secrets:
      - traefik.bouncer
  1. Restart your container: docker compose up -d
  2. Check the logs: docker logs traefik-bouncer
  3. Finally, check it is connected to CrowdSec: docker compose exec crowdsec cscli bouncers list

Extra Notes

There is already a PR so hopefully this will not be needed for long. (https://github.com/fbonalair/traefik-crowdsec-bouncer/pull/29)

totoschka commented 6 months ago

Thank you - works fine for me.