Knative Secrets - Go

A simple web app written in Go that you can use for testing. It demonstrates how to use a Kubernetes secret as a Volume with Knative. We will create a new Google Service Account and place it into a Kubernetes secret, then we will mount it into a container as a Volume.

Follow the steps below to create the sample code and then deploy the app to your cluster. You can also download a working copy of the sample, by running the following commands:

  1. git clone -b "{{< branch >}}" https://github.com/knative/docs knative-docs
  2. cd knative-docs/docs/serving/samples/secrets-go

Before you begin

  • A Kubernetes cluster with Knative installed. Follow the installation instructions if you need to create one.
  • Docker installed and running on your local machine, and a Docker Hub account configured (we’ll use it for a container registry).
  • Create a Google Cloud project and install the gcloud CLI and run gcloud auth login. This sample will use a mix of gcloud and kubectl commands. The rest of the sample assumes that you’ve set the $PROJECT_ID environment variable to your Google Cloud project id, and also set your project ID as default using gcloud config set project $PROJECT_ID.

Recreating the sample code

  1. Create a new file named secrets.go and paste the following code. This code creates a basic web server which listens on port 8080:

    1. package main
    2. import (
    3. "context"
    4. "fmt"
    5. "log"
    6. "net/http"
    7. "os"
    8. "cloud.google.com/go/storage"
    9. )
    10. func main() {
    11. log.Print("Secrets sample started.")
    12. // This sets up the standard GCS storage client, which will pull
    13. // credentials from GOOGLE_APPLICATION_CREDENTIALS if specified.
    14. ctx := context.Background()
    15. client, err := storage.NewClient(ctx)
    16. if err != nil {
    17. log.Fatalf("Unable to initialize storage client: %v", err)
    18. }
    19. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    20. // This GCS bucket has been configured so that any authenticated
    21. // user can access it (Read Only), so any Service Account can
    22. // run this sample.
    23. bkt := client.Bucket("knative-secrets-sample")
    24. // Access the attributes of this GCS bucket, and write it back to the
    25. // user. On failure, return a 500 and the error message.
    26. attrs, err := bkt.Attrs(ctx)
    27. if err != nil {
    28. http.Error(w, err.Error(), http.StatusInternalServerError)
    29. return
    30. }
    31. fmt.Fprintln(w,
    32. fmt.Sprintf("bucket %s, created at %s, is located in %s with storage class %s\n",
    33. attrs.Name, attrs.Created, attrs.Location, attrs.StorageClass))
    34. })
    35. port := os.Getenv("PORT")
    36. if port == "" {
    37. port = "8080"
    38. }
    39. log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
    40. }
  2. In your project directory, create a file named Dockerfile and copy the code block below into it. For detailed instructions on dockerizing a Go app, see Deploying Go servers with Docker.

    1. # Use the official Golang image to create a build artifact.
    2. # This is based on Debian and sets the GOPATH to /go.
    3. # https://hub.docker.com/_/golang
    4. FROM golang as builder
    5. # Copy local code to the container image.
    6. WORKDIR /go/src/github.com/knative/docs/hellosecrets
    7. COPY . .
    8. # Build the output command inside the container.
    9. RUN CGO_ENABLED=0 GOOS=linux go build -v -o hellosecrets
    10. # Use a Docker multi-stage build to create a lean production image.
    11. # https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-builds
    12. FROM alpine
    13. # Enable the use of outbound https
    14. RUN apk add --no-cache ca-certificates
    15. # Copy the binary to the production image from the builder stage.
    16. COPY --from=builder /go/src/github.com/knative/docs/hellosecrets/hellosecrets /hellosecrets
    17. # Service must listen to $PORT environment variable.
    18. # This default value facilitates local development.
    19. ENV PORT 8080
    20. # Run the web service on container startup.
    21. CMD ["/hellosecrets"]
  3. Create a new Google Service Account. This Service Account doesn’t need any privileges, the GCS bucket has been configured so that any authenticated identity may read it.

    1. gcloud iam service-accounts create knative-secrets
  4. Create a new JSON key for this account

    1. gcloud iam service-accounts keys create robot.json \
    2. --iam-account=knative-secrets@$PROJECT_ID.iam.gserviceaccount.com
  5. Create a new Kubernetes secret from this JSON key:

    1. kubectl create secret generic google-robot-secret --from-file=./robot.json

    You can achieve a similar result by editting secret.yaml, copying the contents of robot.json as instructed there, and running kubectl apply --filename secret.yaml.

  6. Create a new file, service.yaml and copy the following service definition into the file. Make sure to replace {username} with your Docker Hub username.

    1. apiVersion: serving.knative.dev/v1
    2. kind: Service
    3. metadata:
    4. name: secrets-go
    5. namespace: default
    6. spec:
    7. template:
    8. spec:
    9. containers:
    10. # Replace {username} with your DockerHub username
    11. - image: docker.io/{username}/secrets-go
    12. env:
    13. # This directs the Google Cloud SDK to use the identity and project
    14. # defined by the Service Account (aka robot) in the JSON file at
    15. # this path.
    16. # - `/var/secret` is determined by the `volumeMounts[0].mountPath`
    17. # below. This can be changed if both places are changed.
    18. # - `robot.json` is determined by the "key" that is used to hold the
    19. # secret content in the Kubernetes secret. This can be changed
    20. # if both places are changed.
    21. - name: GOOGLE_APPLICATION_CREDENTIALS
    22. value: /var/secret/robot.json
    23. # This section specified where in the container we want the
    24. # volume containing our secret to be mounted.
    25. volumeMounts:
    26. - name: robot-secret
    27. mountPath: /var/secret
    28. # This section attaches the secret "google-robot-secret" to
    29. # the Pod holding the user container.
    30. volumes:
    31. - name: robot-secret
    32. secret:
    33. secretName: google-robot-secret

Building and deploying the sample

Once you have recreated the sample code files (or used the files in the sample folder) you’re ready to build and deploy the sample app.

  1. Use Docker to build the sample code into a container. To build and push with Docker Hub, run these commands replacing {username} with your Docker Hub username:

    1. # Build the container on your local machine
    2. docker build -t {username}/secrets-go .
    3. # Push the container to docker registry
    4. docker push {username}/secrets-go
  2. After the build has completed and the container is pushed to docker hub, you can deploy the app into your cluster. Ensure that the container image value in service.yaml matches the container you built in the previous step. Apply the configuration using kubectl:

    1. kubectl apply --filename service.yaml
  3. Now that your service is created, Knative will perform the following steps:

    • Create a new immutable revision for this version of the app.
    • Network programming to create a route, ingress, service, and load balance for your app.
    • Automatically scale your pods up and down (including to zero active pods).
  4. Run the following command to find the domain URL for your service:

    1. kubectl get ksvc secrets-go --output=custom-columns=NAME:.metadata.name,URL:.status.url

    Example:

    1. NAME URL
    2. secrets-go http://secrets-go.default.1.2.3.4.xip.io
  5. Now you can make a request to your app and see the result. Replace the URL below with the URL returned in the previous command.

    1. curl http://secrets-go.default.1.2.3.4.xip.io
    2. bucket knative-secrets-sample, created at 2019-02-01 14:44:05.804 +0000 UTC, is located in US with storage class MULTI_REGIONAL

    Note: Add -v option to get more detail if the curl command failed.

Removing the sample app deployment

To remove the sample app from your cluster, delete the service record:

  1. kubectl delete --filename service.yaml
  2. kubectl delete secret google-robot-secret