• Stars
    star
    119
  • Rank 287,544 (Top 6 %)
  • Language
    Go
  • License
    Apache License 2.0
  • Created about 5 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

konfig

konfig enables serverless workloads running on GCP to reference Kubernetes configmaps and secrets stored in GKE clusters at runtime. konfig currently supports Cloud Run and Cloud Functions workloads.

Usage

konfig is enabled via a single import statement:

import (
    ...

    _ "github.com/kelseyhightower/konfig"
)

How Does it Work

The side effect of importing the konfig library will cause konfig to:

  • call the Cloud Run or Cloud Functions API to get a list of env vars to process. We avoid scanning the running environment as any library can set env vars before konfig runs.
  • retrieve the GKE endpoint based on the secret or configmap reference
  • retrieve configmap and secret keys from the GKE cluster using the service account provided to the Cloud Run or Cloud Function instance.
  • substitute the reference string with the value of the configmap or secret key.

References to Kubernetes configmaps and secrets can be made when defining Cloud Run and Cloud Functions environment variables using the reference syntax.

Tutorials

A GKE cluster is used to store configmaps and secrets referenced by Cloud Run and Cloud Function workloads. Ideally an existing cluster can be used. For the purpose of this tutorial create the smallest GKE cluster possible in the us-central1-a zone:

gcloud container clusters create k0 \
  --cluster-version latest \
  --no-enable-basic-auth \
  --no-enable-ip-alias \
  --metadata disable-legacy-endpoints=true \
  --no-issue-client-certificate \
  --num-nodes 1 \
  --machine-type g1-small \
  --scopes gke-default \
  --zone us-central1-a

Download the credentials for the k0 cluster:

gcloud container clusters get-credentials k0 \
  --zone us-central1-a

We only need the Kubernetes API server as we only plan to use Kubernetes as an secrets and config store, so delete the default node pool.

gcloud container node-pools delete default-pool \
  --cluster k0 \
  --zone us-central1-a

With the k0 GKE cluster in place it's time to create the secrets that will be referenced later in the tutorial.

cat > config.json <<EOF
{
  "database": {
    "username": "user",
    "password": "123456789"
  }
}
EOF

Create the env secret with two keys foo and config.json which holds the contents of the configuration file created in the previous step:

kubectl create secret generic env \
  --from-literal foo=bar \
  --from-file config.json

Create the env configmap with a single key environment:

kubectl create configmap env \
  --from-literal environment=production

At this point the env secret and configmap can be referenced from either Cloud Run or Cloud Functions using the konfig library.

Cloud Run Tutorial

In this section Cloud Run will be used to deploy the gcr.io/hightowerlabs/env:0.0.1 container image which responds to HTTP requests with the contents of the ENVIRONMENT, FOO and CONFIG_FILE environment variables, which reference the env secret and configmap created in the previous section.

A GKE cluster ID is required when referencing configmaps and secrets. Extract the cluster ID for the k0 GKE cluster:

CLUSTER_ID=$(gcloud container clusters describe k0 \
  --zone us-central1-a \
  --format='value(selfLink)')

Strip the https://container.googleapis.com/v1 from the previous response and store the results:

CLUSTER_ID=${CLUSTER_ID#"https://container.googleapis.com/v1"}

The CLUSTER_ID env var should hold the fully qualified path to the k0 cluster. Assuming hightowerlabs as the project ID the value would be /projects/hightowerlabs/zones/us-central1-a/clusters/k0.

Create the env Cloud Run service and set the ENVIRONMENT, FOO and CONFIG_FILE env vars to reference the env configmaps and secrets in the k0 GKE cluster:

gcloud alpha run deploy env \
  --allow-unauthenticated \
  --concurrency 50 \
  --image gcr.io/hightowerlabs/env:0.0.1 \
  --memory 2G \
  --region us-central1 \
  --set-env-vars "FOO=\$SecretKeyRef:${CLUSTER_ID}/namespaces/default/secrets/env/keys/foo,CONFIG_FILE=\$SecretKeyRef:${CLUSTER_ID}/namespaces/default/secrets/env/keys/config.json?tempFile=true,ENVIRONMENT=\$ConfigMapKeyRef:${CLUSTER_ID}/namespaces/default/configmaps/env/keys/environment"

The CONFIG_FILE env var reference uses the tempFile option to write the contents of the config.json secret key to a temp file. The CONFIG_FILE env var will hold the path to the temp file which can be read during normal program execution.

Retrieve the env service HTTP endpoint:

ENV_SERVICE_URL=$(gcloud alpha run services describe env \
  --namespace hightowerlabs \
  --region us-central1 \
  --format='value(status.url)')

Make an HTTP request to the env service:

curl $ENV_SERVICE_URL

Output:

CONFIG_FILE: /tmp/363780357
ENVIRONMENT: production
FOO: bar

# /tmp/363780357
{
  "database": {
    "username": "user",
    "password": "123456789"
  }
}

Cloud Functions Tutorial

konfig pulls referenced secrets and configmaps from GKE clusters using the GCP service account assigned to a Cloud Function. Create the konfig service account with the following IAM roles:

  • roles/iam.serviceAccountTokenCreator
  • roles/cloudfunctions.viewer
  • roles/container.viewer
PROJECT_ID=$(gcloud config get-value core/project)
SERVICE_ACCOUNT_NAME="konfig"
gcloud iam service-accounts create ${SERVICE_ACCOUNT_NAME} \
  --quiet \
  --display-name "konfig service account"
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --quiet \
  --member="serviceAccount:${SERVICE_ACCOUNT_NAME}@${PROJECT_ID}.iam.gserviceaccount.com" \
  --role='roles/iam.serviceAccountTokenCreator'
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --quiet \
  --member="serviceAccount:${SERVICE_ACCOUNT_NAME}@${PROJECT_ID}.iam.gserviceaccount.com" \
  --role='roles/cloudfunctions.viewer'
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --quiet \
  --member="serviceAccount:${SERVICE_ACCOUNT_NAME}@${PROJECT_ID}.iam.gserviceaccount.com" \
  --role='roles/container.developer'

Enable the konfig GCP service account to access the env secret and configmap created in previous section:

SERVICE_ACCOUNT_EMAIL="konfig@${PROJECT_ID}.iam.gserviceaccount.com"

Create the konfig role in the k0 GKE cluster:

kubectl create role konfig \
  --verb get \
  --resource secrets \
  --resource configmaps \
  --resource-name env

Bind the konfig GCP service account and konfig role:

kubectl create rolebinding konfig \
  --role konfig \
  --user ${SERVICE_ACCOUNT_EMAIL}

At this point the konfig GCP service account has access to the configmap and secret named env in the default namespace in the k0 GKE cluster.

The konfig Kubernetes role limits the konfig GCP service to the defined env secret and configmap in a single namespace. Access to additional secrets and configmaps will require additional permissions.

Deploy the env function.

cd examples/cloudfunctions/env/
gcloud alpha functions deploy env \
  --entry-point F \
  --max-instances 10 \
  --memory 128MB \
  --region us-central1 \
  --runtime go111 \
  --service-account $SERVICE_ACCOUNT_EMAIL \
  --set-env-vars "FOO=\$SecretKeyRef:${CLUSTER_ID}/namespaces/default/secrets/env/keys/foo,CONFIG_FILE=\$SecretKeyRef:${CLUSTER_ID}/namespaces/default/secrets/env/keys/config.json?tempFile=true,ENVIRONMENT=\$ConfigMapKeyRef:${CLUSTER_ID}/namespaces/default/configmaps/env/keys/environment" \
  --timeout 30s \
  --trigger-http

Enable unauthenticated access to the env function HTTP endpoint:

gcloud alpha functions add-iam-policy-binding env \
  --member allUsers \
  --role roles/cloudfunctions.invoker

Retrieve the HTTPS trigger URL:

HTTPS_TRIGGER_URL=$(gcloud beta functions describe env \
  --format 'value(httpsTrigger.url)')

Make an HTTP request to the env function:

curl $HTTPS_TRIGGER_URL
CONFIG_FILE: /tmp/813067742
ENVIRONMENT: production
FOO: bar

# /tmp/813067742
{
  "database": {
    "username": "user",
    "password": "123456789"
  }
}

More Repositories

1

nocode

The best way to write secure and reliable applications. Write nothing; deploy nowhere.
Dockerfile
59,013
star
2

kubernetes-the-hard-way

Bootstrap Kubernetes the hard way on Google Cloud Platform. No scripts.
38,169
star
3

confd

Manage local application configuration files using templates and data from etcd or consul
Go
8,274
star
4

envconfig

Golang library for managing configuration data from environment variables
Go
4,881
star
5

kube-cert-manager

Manage Lets Encrypt certificates for a Kubernetes cluster.
Go
1,087
star
6

intro-to-kubernetes-workshop

Intro to Kubernetes Workshop
1,016
star
7

pipeline

A step by step guide on creating build and deployment pipelines for Kubernetes.
747
star
8

consul-on-kubernetes

Running HashiCorp's Consul on Kubernetes
Shell
598
star
9

konfd

Manage application configuration using Kubernetes secrets, configmaps, and Go templates.
Go
494
star
10

kubernetes-cluster-federation

Kubernetes cluster federation tutorial
458
star
11

vault-controller

Automate the creation of unique Vault tokens for Kubernetes Pods using init containers.
Go
448
star
12

compose2kube

Convert docker-compose service files to Kubernetes objects.
Go
417
star
13

serverless-vault-with-cloud-run

Guide to running Vault on Cloud Run
Shell
392
star
14

vault-on-google-kubernetes-engine

How to guide on running HashiCorp's Vault on Google Kubernetes Engine
Shell
387
star
15

app

Example 12 Facter App
Go
379
star
16

terminus

Get facts about a Linux system.
Go
361
star
17

nomad-on-kubernetes

Tutorial on running Nomad on Kubernetes.
Shell
342
star
18

istio-ingress-tutorial

How to run the Istio Ingress Controller on Kubernetes
Shell
322
star
19

kubernetes-initializer-tutorial

Hands-on tutorial for building and deploying Kubernetes Initializers.
Go
321
star
20

kubestack

Manage Kubernetes with Packer and Terraform on Google Compute Engine.
297
star
21

grpc-hello-service

grpc examples
Go
272
star
22

coreos-ipxe-server

CoreOS iPXE server
Go
218
star
23

kubernetes-redis-cluster

Kubernetes Redis Cluster configs and tutorial
Shell
215
star
24

standalone-kubelet-tutorial

Standalone Kubelet Tutorial
Go
204
star
25

grafeas-tutorial

A step by step guide for getting started with Grafeas and Kubernetes.
Go
191
star
26

docker-kubernetes-tls-guide

Step by step guide on how to secure Docker and Kubernetes using TLS with CloudFlare’s CFSSL
191
star
27

google-cloud-functions-go

Google Cloud Function tutorial and hacks to enable the use of Go.
Go
180
star
28

helloworld

Go
180
star
29

scheduler

Toy Kubernetes Scheduler
Go
174
star
30

craft-kubernetes-workshop

Craft Kubernetes Workshop
Shell
172
star
31

ingress-with-static-ip

Tutorial on creating a Kubernetes Ingress Resource with a Static IP Address in GCP or GKE
165
star
32

mesh

Cloud native service mesh for the rest of us.
160
star
33

lobsters-on-kubernetes

Lobsters, the Hacker News clone, on Kubernetes
Shell
156
star
34

denyenv-validating-admission-webhook

An Kubernetes validating admission webhook that rejects pods that use environment variables.
JavaScript
154
star
35

vault-init

Automate the initialization and unsealing of HashiCorp Vault on Google Cloud Platform.
Go
151
star
36

certificate-init-container

Bootstrap TLS certificates for Pods using the Kubernetes certificates API.
Go
146
star
37

kubeadm-single-node-cluster

How to bootstrap a single-node Kubernetes cluster on Google Compute Engine using kubeadm.
Shell
140
star
38

hashiapp

Demo 12 Factor application that utilizes Hashicorp tools.
Go
134
star
39

kubernetes-envoy-sds

Kubernetes Envoy Service Discovery Service.
Go
133
star
40

setup-network-environment

Create an environment file with system networking information.
Go
131
star
41

kargo

Go
125
star
42

contributors

Display GitHub contributors for a specific repo.
Go
123
star
43

self-deploying-hello-universe

What if applications could deploy themselves?
Go
123
star
44

event-gateway-on-kubernetes

How to guide on running Serverless.com's Event Gateway on Kubernetes
Go
119
star
45

gke-service-accounts-tutorial

A tutorial on using Google Cloud service account with Google Container Engine (GKE).
Go
109
star
46

run

Package run provides helper functions for building Cloud Run applications.
Go
107
star
47

hashiconf-eu-2016

HashiConf EU 2016
Shell
106
star
48

talks

Shell
99
star
49

badger

Generate build status images for Google Cloud Build
Go
98
star
50

riff-tutorial

How-to guide for testing the riff FaaS platform and Istio on Google Kubernetes Engine.
Go
97
star
51

cri-o-tutorial

A guided tutorial for the cri-o (ocid) Kubernetes container runtime.
95
star
52

lambda-on-cloud-run

Tutorial: Running Lambda Functions on Cloud Run
Dockerfile
83
star
53

gophercon-2018

Kelsey's GopherCon 2018 Keynote: Going Serverless
Go
72
star
54

12-fractured-apps

Example code for the 12 Fractured Apps blog posts.
Go
71
star
55

etcd-production-setup

Setting up etcd to run in production.
69
star
56

cmd-tutorial

68
star
57

oscon-2017-kubernetes-tutorial

OSCON 2017 Kubernetes Tutorial
68
star
58

jira-on-kubernetes

Notes: Running Atlassian's Jira on Kubernetes
67
star
59

conf2kube

conf2kube can read and create Kubernetes secrets based on the contents of configuration files.
Go
64
star
60

endpoints

Kubernetes endpoints load balancer.
Go
62
star
61

oscon-metrics-tutorial

OSCON Metrics Tutorial
60
star
62

echo

echo prints the first positional argument to stdout
Assembly
59
star
63

memkv

Simple in-memory key/value store backed by a map
Go
58
star
64

motorboat

Dynamically sync Nginx Plus backends from Kubernetes service endpoints.
Go
57
star
65

app-healthz

Example app with a healthz endpoint
Go
55
star
66

dynamic-ports-tutorial

A prototype of using dynamic ports with Kubernetes.
Go
54
star
67

ipxed

Web interface and api for ipxed
Go
51
star
68

helloworld-infrastructure-production

51
star
69

intro-to-go-workshop

Intro to Go Workshop
Go
50
star
70

pipeline-application

Go
48
star
71

reposync

Sync GitHub and Google Cloud Source Repos
Go
45
star
72

journal-2-logentries

Ship systemd journal entries to logentries.com
Go
45
star
73

pm

Package manager
Go
44
star
74

time

Educational package to teach aspiring programmers about history through the lens of time.
Go
44
star
75

container-instance-metadata-server

Cloud Run Container Instance Metadata Server Emulator
Go
41
star
76

kube

Basic single node Kubernetes using a bash script.
Shell
40
star
77

helloworld-infrastructure-staging

36
star
78

gcscache

GCS Cache implements the autocet.Cache interface using Google Cloud Storage.
Go
35
star
79

helloworld-infrastructure-qa

35
star
80

memq

In memory message queue prototype.
Go
32
star
81

kubestack-solo

Create a single node Kubernetes image for local testing with VMware Fusion.
32
star
82

jsonrpc-server

Complete example on using net/rpc over HTTP with the jsonrpc encoding
Go
32
star
83

opa-on-cloud-run

Tutorial: Open Policy Agent on Cloud Run
Shell
31
star
84

confidence

Example application which demonstrates various configuration options for modern applications.
Go
30
star
85

cloud-functions-min-instances-tutorial

Cloud Functions Min Instances Tutorial
Go
30
star
86

hello-cuelang

Learning CUE in public
Go
29
star
87

kube-rsa

Generate self-signed TLS certificates for Kubernetes
Go
29
star
88

kur

Kubernetes Up and Running
Shell
28
star
89

echod

A small echo server written in x86-32 asm
Assembly
28
star
90

redis-enterprise-on-kubernetes

How to deploy Redis Enterprise on Kubernetes
Shell
27
star
91

kubernetes-letsencrypt-tutorial

WIP: Kubernetes Lets Encrypt Tutorial
Go
27
star
92

krane

Convert Google Compute Engine (GCE) autoscaling instance groups to Kubernetes autoscaling deployments.
Go
27
star
93

twelve

Go
26
star
94

buildinfo

Go
25
star
95

etcd-pod-gen

Generate etcd pod specs for running under the Kubernetes Kubelet
Go
24
star
96

istio-initializer

Kubernetes Initializer that injects the Istio sidecar into pods.
Go
24
star
97

config-connector-policy-demo

Kubernetes Config Connector Policy Demo.
Open Policy Agent
24
star
98

dialogflow

The best way to create Dialogflow webhooks in Go.
Go
23
star
99

functions

Google Cloud Functions Helpers
Go
23
star
100

terraform-kcc-demo

Terraform KCC Demo
Shell
22
star