kubernetes

Kubernetes Part 5 of n : Config Maps and Secrets

 

So this post will continue to build upon our example pod/deployment/service that we have been using for the entire series of posts. Just a reminder the rough outline is as follows:

 

  1. What is Kubernetes / Installing Minikube
  2. What are pods/labels, declaring your first pod
  3. Services
  4. Singletons, such as a DB
  5. ConfigMaps/Secrets (this post)
  6. LivenessProbe/ReadinessProbe/Scaling Deployments

 

Where is the code again?

 

 

What did we talk about last time?

Last time we continued to use services, but last time we showed how you can use service to expose a singleton, such as a database, where we expect there only to be a single pod behind the service. We also talked about DNS lookups for aiding in discovery and finally using ClusterIP : None, which allowed us to address the pod directly.

 

So what is this post about?

This time we will focus our attention to 2 more bits of Kubernetes functionality

  • Config Maps
  • Secrets

We will continue to adjust our example pod that we have been using for the entire series so far. But before we do that lets just talk about some of the concepts behind Config Maps/Secrets in Kubernetes

 

Before we Start

Lets make sure minikube is up and running by using this

cd\
.\minikube.exe start --kubernetes-version="v1.9.0" --vm-driver="hyperv" --memory=1024 --hyperv-virtual-switch="Minikube Switch" --v=7 --alsologtostderr 

 

 

What is a ConfigMap?

This is what the official docs say

 

ConfigMaps allow you to decouple configuration artifacts from image content to keep containerized applications portable. This page provides a series of usage examples demonstrating how to create ConfigMaps and configure Pods using data stored in ConfigMaps.

 

From https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/ up on date 29/03/18

 

There are many ways to create config files, such as

 

I am just going to concentrate on “Create ConfigMaps from files” as that fitted the bill of what I wanted to do with the pod that I have been altering for this series of posts. So lets have a look at that shall we.

 

Lets say I had a file called this “sachaserver-properties”, which held this content:

 

{
    "K8sConfigSetting1": "**** Config from K8s!!! ****"
}

 

I could easily try and create a config map from this file as follows:

 

.\kubectl.exe create configmap server-config --from-file=C:\Users\sacha\Desktop\KubernetesExamples\Post5_SimpleServiceStackPod_ConfigMapsSecrets\configmap_secrets\sachaserver-properties

So lets see what happens when I run that in PowerShell

 

image

 

Mmm was not expecting that. So the filename is important and has a regex associated with it of [-._a-zA-Z0-9]+

 

But hang on my file is called “sachaserver-properties“, so this should match the regex required by Kubernetes. Can you spot what’s wrong. That right the path is being used as part of the filename, which Kubernetes doesn’t like. We will see why in just a minute.

 

So the answer is to just copy the file to the same folder as kubctl.exe and then lets try this command

 

.\kubectl.exe create configmap server-config --from-file=C:\sachaserver-properties

This seems to go better

image

Lets have a closer look at the config map that we created here

.\kubectl.exe describe configmaps server-config

image

 

.\kubectl.exe get configmaps server-config -o yaml

image

 

There are a couple of things to note here:

  • That the ConfigMap has a Data section which is really just a key-value store
  • What’s really interesting is that the original file name (and we could have used multiple files so would have ended up with multiple keys in the Data section) that we used is used as the name of the key inside this ConfigMap Data section. This is WHY Kubernetes baulked at us earlier where we were using the FULL path to try and create the ConfigMap. It needs to be a simple key, that will end up being a key in this Data section
  • The other interesting thing is what happens with the original file(s) content. The content from the file/files is used as the value for the key (representing the file) inside of the Data section. As you can see this “sachaserver-properties” key does indeed contain all the original contents of the file that I showed above.

 

So that’s pretty cool. But what can I do with this ConfigMap?

Well now that we have a ConfigMap we need to think about how to use it inside our own pods. Again there are several different ways, where I will concentrate on one of them

 

Can we test this out before we move onto changing our main pod?

It’s not a lot of work to upload a new image to Docker Cloud, but I am the sort of guy that likes to know things work before I upload it somewhere, and then have to tear it down, and redo it again. So is there a way that I can check this ConfigMap stuff is working as expected locally using some existing Docker image before I change the code for the pod that we have been using to date for this series of posts?

 

Well actually yes there is, there is our old friend busybox (the swiss army knife of containers). We can use a busybox pod in a couple of ways to verify the config map is working as expected

  • We can check the mount works ok
  • We can check that the data contents of the ConfigMap is as expected

 

Lets see how

 

Checking the mount works ok

So lets say we have a busybox pod that looks like this (this is busybox-ls-pod.yaml in source code)

apiVersion: v1
kind: Pod
metadata:
  name: busybox-ls-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "ls /k8s/config" ]
      volumeMounts:
      - name: config-volume
        mountPath: /k8s/config
  volumes:
    - name: config-volume
      configMap:
        # Provide the name of the ConfigMap containing the files you want
        # to add to the container
        name: server-config
  restartPolicy: Never

 

We can then run this like

.\kubectl.exe apply -f C:\Users\sacha\Desktop\KubernetesExamples\Post5_SimpleServiceStackPod_ConfigMapsSecrets\configmap\busybox-ls-pod.yaml

And check its logs like this

.\kubectl logs busybox-ls-pod

Which gives us output like this

image

Ok, so that is good looks like the mount is working ok.

 

Checking the data contents is ok

So now that we know the mount is ok, how about the data contents from the mounted config map. Lets see an example of how we can check that using another busybox pod (this is busybox-cat-pod.yaml in source code)

apiVersion: v1
kind: Pod
metadata:
  name: busybox-cat-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh","-c","cat /k8s/config/sachaserver-properties" ]
      volumeMounts:
      - name: config-volume
        mountPath: /k8s/config
  volumes:
    - name: config-volume
      configMap:
        # Provide the name of the ConfigMap containing the files you want
        # to add to the container
        name: server-config
  restartPolicy: Never

 

We can then run this like

.\kubectl.exe apply -f C:\Users\sacha\Desktop\KubernetesExamples\Post5_SimpleServiceStackPod_ConfigMapsSecrets\configmap\busybox-cat-pod.yaml

And check its logs like this

.\kubectl logs busybox-cat-pod

Where we get output like this

image

Cool this looks to be working as expected as well

 

 

What is a Secret?

Right now there is not much difference between secretes and ConfigMaps in Kubernetes. The only real difference is how you create the data that you want to be stored in the first place, where the recommendation is to use Base64 encoded values for your secrets

 

There is a slightly different command like to run, and the way you mount the volume in your pod is also slightly different, but conceptually its not that different (right now, but I would imagine this might change to use some other mechanism over time).

 

Base64 Encoding

So the recommendation is to base64 encode our secret values, and if you are a linux/bash user this is how you can do it

image

 

Or you could just use one of the many base64 encoding/decoding sites on line such as : https://www.base64decode.org/

 

So once you have done that for whatever you want to keep as a secret we can put them in a file such as this one (this is the sachaserver-secrets-properties file in the demo source code)

{
    "K8sSecret1": "KioqKiBTZWNyZXQgZnJvbSBLOHMgKioqKg=="
}


In here the base64 encoded string is really “**** Secret from K8s ****

 

As before the secrets file must not contain any \\ or \ characters which means moving it to the C:\ for me (at least on Windows anyway). So here is the code that copies the file and also creates the secret from the input secret file sachaserver-secrets-properties

 

Remove-Item c:\sachaserver-secrets-properties
Copy-Item C:\Users\sacha\Desktop\KubernetesExamples\Post5_SimpleServiceStackPod_ConfigMapsSecrets\secrets\sachaserver-secrets-properties -Destination c:\sachaserver-secrets-properties
.\kubectl.exe create secret generic server-secrets --from-file=sachaserver-secrets-properties

 

We can do some simple tests to make sure it looks ok, but we will also use our favorite busybox pod to really check it out. For now lets run some rudimentary tests

.\kubectl.exe describe secrets server-secrets
.\kubectl.exe get secrets server-secrets -o yaml

 

But as we just said we can/should use busybox to confirm everything is ok before we start to make adjustments to our own pod. Lets move on to see what the busybox stuff looks like for this secrets stuff

 

We can use a busybox pod in the same way we used it with the configmap stuff, to verify the secrets we just crested is working as expected

  • We can check the mount works ok
  • We can check that the data contents of the secrets is as expected

 

Lets see how

 

Checking the mount works ok

So lets say we have a busybox pod that looks like this (this is busybox-secrets-ls-pod.yaml in source code)

apiVersion: v1
kind: Pod
metadata:
  name: busybox-secrets-ls-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh", "-c", "ls /k8s/secrets" ]
      volumeMounts:
      - name: secrets-volume
        mountPath: /k8s/secrets
  volumes:
    - name: secrets-volume
      secret:
        # Provide the name of the Secret containing the files you want
        # to add to the container
        secretName: server-secrets
  restartPolicy: Never

 

We can then run this like

.\kubectl.exe apply -f C:\Users\sacha\Desktop\KubernetesExamples\Post5_SimpleServiceStackPod_ConfigMapsSecrets\secrets\busybox-secrets-ls-pod.yaml

And check its logs like this

.\kubectl logs busybox-secrets-ls-pod

Which gives us output like this

image

 

Ok, so that is good looks like the mount is working ok.

 

Checking the data contents is ok

So now that we know the mount is ok, how about the data contents from the mounted secretes. Lets see an example of how we can check that using another busybox pod (this is busybox-secrets-cat-pod.yaml in source code)

apiVersion: v1
kind: Pod
metadata:
  name: busybox-secrets-cat-pod
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "/bin/sh","-c","cat /k8s/secrets/sachaserver-secrets-properties" ]
      volumeMounts:
      - name: secrets-volume
        mountPath: /k8s/secrets
  volumes:
    - name: secrets-volume
      secret:
        # Provide the name of the Secret containing the files you want
        # to add to the container
        secretName: server-secrets
  restartPolicy: Never

 

We can then run this like

.\kubectl.exe apply -f C:\Users\sacha\Desktop\KubernetesExamples\Post5_SimpleServiceStackPod_ConfigMapsSecrets\secrets\busybox-secrets-cat-pod.yaml

And check its logs like this

.\kubectl logs busybox-secrets-cat-pod

Where we get output like this

image

 

Cool this looks to be working as expected as well

 

 

What’s changed in the demo app?

Ok so far no blockers, what have we got working so far?

Well we now have this working

  • A working configmap
  • A correctly proved out volume mapping for the configmap
  • The ability to confirm the configmap file is present in the mapped volume for the configmap
  • The ability to read the contents of the configmap file within the mapped volume for the configmap
  • A working secret
  • A correctly proved out volume mapping for the secret
  • The ability to confirm the secret file is present in the mapped volume for the secret
  • The ability to read the contents of the secret file within the mapped volume for the secret

I demonstrated ALL of this above. So now we should be in a good place to adjust our pod / deployment that we have been working on for this entire series. Just to remind ourselves of what the demo pod did here is what we have working so far

 

 

So what do we need to change to support the configmap/secret stuff that we are trying to demo for this post.

 

Change The Deployment For The Pod

We obviously need to make changes to the demo deployment/pod definition to support the configmap/secrets stuff, so this is the new deployment file for this post

 

Post5_SimpleServiceStackPod_ConfigMapsSecrets\sswebapp\deployment.yaml

 

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: simple-sswebapi-pod-v1
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: run=sswebapi-pod-v1
    spec:
      containers:
      - name: sswebapi-pod-v1
        image: sachabarber/sswebapp-post-5:v1
        ports:
        - containerPort: 5000
        volumeMounts:
        - name: config-volume
          mountPath: /k8s/config
        - name: secrets-volume
          mountPath: /k8s/secrets          
      volumes:
        - name: config-volume
          configMap:
            # Provide the name of the ConfigMap containing the files you want
            # to add to the container
            name: server-config
        - name: secrets-volume
          secret:
            # Provide the name of the Secret containing the files you want
            # to add to the container
            secretName: server-secrets            

 

Something That Reads The Input Files

So we established above that once we have some mapped volumes that the configmap/secret files should be available at the mounts specified above. So how do we read these files? Previously we were using busybox and using cat, and now we are in .NET Core land. Mmmm

 

Luckily the .NET Core configuration system working just fine reading these files, here is how we do it in the adjusted Startup.cs class

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Funq;
using ServiceStack;
using ServiceStack.Configuration;
using sswebapp.ServiceInterface;
using ServiceStack.Api.Swagger;
using System.Text;

namespace sswebapp
{
    public class Startup
    {
        public static IConfiguration Configuration { get; set; }

        public Startup(IConfiguration configuration) => Configuration = configuration;

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddJsonFile("/k8s/config/sachaserver-properties", optional: true, reloadOnChange: true)
                .AddJsonFile("/k8s/secrets/sachaserver-secrets-properties", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();

            Configuration = builder.Build();

            //Set the Static on MyServices, which is very poor design, but it is just for a
            //demo so I am letting it slide
            MyServices.AllVariablesFromStartup = Configuration.AsEnumerable();

            app.UseServiceStack(new AppHost
            {
                AppSettings = new NetCoreAppSettings(Configuration)
            });
        }
    }

    public class AppHost : AppHostBase
    {
       .....
    }
}

The most important lines being these ones where it can be seen that we read from the mapped configmap/secret mounted files

var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .....
	.....
	.AddJsonFile("/k8s/config/sachaserver-properties", optional: true, reloadOnChange: true)
    .AddJsonFile("/k8s/secrets/sachaserver-secrets-properties", optional: true, reloadOnChange: true)
    .AddEnvironmentVariables();

Configuration = builder.Build();

//Set the Static on MyServices, which is very poor design, but it is just for a
//demo so I am letting it slide
MyServices.AllVariablesFromStartup = Configuration.AsEnumerable();

 

 

A New Route

Ok so now that we are reading in these file values, we obviously want to ensure it is all working, so lets have a new route to expose all the settings that have been read in by the .NET Core configuration system. Where we are obviously expecting our configmap/secrets items to be part of that.

 

Since we are using ServiceStack this is what our new route looks like

using ServiceStack;
using System.Collections.Generic;

namespace sswebapp.ServiceModel
{
    [Route("/showsettings","GET")]
    public class ShowSettingRequest : IReturn<ShowSettingResponse>
    {
        
    }

    public class ShowSettingResponse
    {
        public IEnumerable<string> Results { get; set; }
    }
    
}

 

 

A New Method To Support The New Route

Ok so we now have a new route, but we need some service code to support this new route. So here we have it

using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using ServiceStack;
using sswebapp.ServiceModel;

namespace sswebapp.ServiceInterface
{
    public class MyServices : Service
    {
        /// <summary>
        /// Set in <c>sswebapp.Startup.cs</c>. This is just for demo purposes only
        /// this is not a great design, but for this quick and dirty demo it does the job
        /// </summary>
        public static IEnumerable<KeyValuePair<string,string>> AllVariablesFromStartup { get; set; }

		....
		....
		....
		....
		....
		

        public object Get(ShowSettingRequest request)
        {
            try
            {
                var allVars = new List<string>();
                foreach (var kvp in AllVariablesFromStartup)
                {
                    allVars.Add($"Key: {kvp.Key}, Value: {kvp.Value}");
                }

                return new ShowSettingResponse { Results = allVars };
            }
            catch(Exception ex)
            {
                return new ShowSettingResponse { Results = new List<string>() {ex.Message } };
            }
        }
    }
}

 

Testing It Out

So we have talked about creating the configmap/secrets and how to test them out using our friend, busybox. We have also talked about how we modified the ongoing pod/deployment that this series of post has worked with from the beginning, where we have exposed a new route to allow us to grab all the settings the .NET Core configuration sub system can see.

 

So we should be in a good position to test it out for real, lets proceed

 

As usual we expect minikube to be running

c:\
cd\
.\minikube.exe start --kubernetes-version="v1.9.0" --vm-driver="hyperv" --memory=1024 --hyperv-virtual-switch="Minikube Switch" --v=7 --alsologtostderr 

Ok so now lets create the pod/deployment

\kubectl.exe apply -f C:\Users\sacha\Desktop\KubernetesExamples\Post5_SimpleServiceStackPod_ConfigMapsSecrets\sswebapp\deployment.yaml

 

And then the service

.\kubectl.exe apply -f C:\Users\sacha\Desktop\KubernetesExamples\Post5_SimpleServiceStackPod_ConfigMapsSecrets\sswebapp\service.yaml

Then lets grab the url for the service

.\minikube service simple-sswebapi-service --url 

 

So for me this would allow me to use this url for the running service, which should show ALL the settings that the ServiceStack app read in when using the new showsettings route, including the Kubernetes configmap/secret values we looked at above

 

 

http://192.168.0.29:32383/showsettings?format=json

 

image

 

Not the best formatting, I give you that, so lets just take that JSON into http://jsonprettyprint.com/json-pretty-printer.php which tidies it up into this

 

image

 

Aha our configmap and secret values are there. Superb its all working. Obviously for the secrets we would still need to decode this from this base64 string to get our original value. But this does show everything is working just fine.

 

Conclusion

As with most of the post in this series so far, I have found Kubernetes to be most intuitive, and it just kind of works to be honest, this post has been particularly straight forward where I just wrote the YAML for the config map, and then wrote a test busybox pod, and it just worked. Doesn’t happen that often…..so yay

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s