---
# System prepended metadata

title: Kubernetes - ConfigMap
tags: [Kubernetes]

---

# Kubernetes - ConfigMap
###### tags: `Kubernetes`
## Foreword
> When you are developing, you don't want to deliver your code of the deployment environment with your code together. The ConfigMap is the useful object to help you.
>  
> Once you deliver your code of the deployment environment with your code together, it will let your service expose in danger. 
> 
## ConfigMap
### Definition
> A ConfigMap is an API object used to store non-confidential data in key-value pairs. Pods can consume ConfigMaps as environment variables, command-line arguments, or as configuration files in a volume.
> 
### Secret V.S. ConfigMap
> Somebody will have question between Secret and ConfigMap. 
> Usually, we save the data need to be encrypted in Secret such like password of database or password of API. 
> However, in the ConfigMap we usually save the port number or  config file of Redis.
> 
### Feature of ConfigMap
- We don't need to modify the container, we can change the different enviroment.
- A ConfigMap can save whole configuration, ex webserver config file, Nginx config file.
- ConfigMap can save all of our configuration.
## Practice
### Create ConfigMap
#### From literal
> We can use the literal to create the ConfigMap.
>
```linux
$ kubectl create configmap myconfig --from-literal=k1=v1 --from-literal=k2=v2
configmap "myconfig" created
```
> Use `kubectl get` to check our ConfigMap.
> 
`kubectl get configmap myconfig -o yaml`

![](https://i.imgur.com/pu5C8Xc.png)

#### From yaml file
> We can use yaml file to create ConfigMap.
> 
```yaml=1
apiVersion: v1
kind: ConfigMap
metadata:
  name: myconfigyaml
data:
  k1: v1 
  k2: v2
```
> Then create ConfigMap.
> 
`kubectl apply -f ./myconfig.yaml`

> Or you use file to create ConfigMap.
> First, create a file and write the value.
> 
```=1
fromkey1=v1
fromkey2=v2
fromkey3=v3
```
> And, use `kubectl create configmap myconfigfromkey --from-key=[key]=[file path]` to create ConfigMap.
> 
`$ kubectl create configmap myconfigfromkey --from-file=fromfilekey=from-key`
### Use ConfigMap
> Create a Pod let ConfigMap as environment varible. 
> 
```yaml=1
apiVersion: v1
kind: Pod
metadata:
  name: config-pod
spec:
  containers:
  - name: config-pod
    image: gcr.io/google_containers/busybox
    command: ["/bin/sh", "-c", "env"]
    env:
    - name: MY_CONFIG_KEY
      valueFrom:
        configMapKeyRef:
          name: myconfig
          key: k1
  restartPolicy: Never
```
> We can see the log of Pod. We will see like this.
> 
```
$ kubectl logs config-pod
...
MY_CONFIG_KEY=v1
```
> We can see `MY_CONFIG_KEY=v1`. It is which we define in the yaml file.
> 

## Reference
> https://kubernetes.io/docs/concepts/configuration/configmap/
> 

>https://ithelp.ithome.com.tw/articles/10193935
>

>https://ithelp.ithome.com.tw/articles/10196153
>