Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
Prochaine révision
Révision précédente
elearning:workbooks:kubernetes:k8s07 [2020/12/13 14:45] adminelearning:workbooks:kubernetes:k8s07 [2024/12/15 06:55] (Version actuelle) admin
Ligne 1: Ligne 1:
 ~~PDF:LANDSCAPE~~ ~~PDF:LANDSCAPE~~
  
-Version - **2020.02**+Version - **2024.01**
  
 Dernière mise-à-jour : ~~LASTMOD~~ Dernière mise-à-jour : ~~LASTMOD~~
  
-======DOF308 - Utilisation de la Commande kubectl======+ 
 +======DOF308 - Introduction à la Sécurisation de K8s======
  
 =====Contenu du Module===== =====Contenu du Module=====
  
-  * **DOF308 - Utilisation de la Commande kubectl**+  * **DOF308 - Introduction à la Sécurisation de K8s**
     * Contenu du Module     * Contenu du Module
-    * LAB #1 - Travailler avec kubectl +    * LAB #1 - Role Based Acces Control et Certificats TLS 
-      * 1.1 - Équivalences entre la commande docker et la commande kubectl +      * 1.1 - Présentation 
-      * 1.2 - Obtenir de l'Aide sur les Commandes de kubectl +      * 1.2 - Le Fichier /etc/kubernetes/manifests/kube-apiserver.yaml 
-      * 1.3 - Obtenir de l'Information sur le Cluster +      * 1.3 - Création d'un serviceAccount 
-        * La Commande version +      * 1.4 - Création d'un Utilisateur 
-        * La Commande cluster-info +      * 1.5 - Certificats TLS 
-        * La Commande api-versions +    LAB #2 - Implémentation de la Sécurité au niveau des Pods 
-        * La Commande api-resources +      2.1 - Présentation 
-      * 1.4 - Travailler avec les Nœuds +      * 2.Kubernetes Security Context 
-        * La Commande describe +        * ReadOnlyRootFilesystem 
-        * La Commande top +        * drop 
-        * Les Commandes cordon et uncordon +      * 2.Kubernetes Network Policies 
-        * La Commande drain +      * 2.Kubernetes Resource Allocation Management
-        * La Commande delete +
-      * 1.5 - Gestion des Applications +
-        La Commande expose +
-        La Commande get +
-        * La Commande set +
-        * La Commande rollout  +
-      * 1.Déboguer une Application +
-        * La Commande logs +
-        * La Commande exec +
-      * 1.Gérer les Plugins de kubectl +
-        * La Commande krew +
-      * 1.Gérer des patchs +
-        * La Commande kustomize +
-      * 1.9 - Alias utile +
-        * L'Alias kg +
-        * L'Alias kd +
-        * L'Alias kga +
-        * L'Alias kp +
-        * L'Alias kap +
-        * L'Alias kei +
-        * L'Alias ke +
-        * L'Alias kpf +
-        * L'Alias kl+
  
-=====Préparation=====+=====Ressources=====
  
-====Présentation de kind====+====Lab #1====
  
-kind est un outil utilisé pour exécuter un cluster Kubernetes localement en utilisant des conteneurs Docker en tant que nœudskind a été développé pour tester Kubernetes lui-même mais peut aussi être utilisé pour du développement local.+  * https://www.dropbox.com/scl/fi/ttklc9ejfhpuyq3eh7wbo/flask.yaml?rlkey=gt1fxvfd8a1vxh75e8y8bz6yw&dl=0 
 +  * https://www.dropbox.com/scl/fi/ujyzyh5ixqibqtychuyzr/deployment.yaml?rlkey=u4tnbrh2f0b6ewk1mt15y6y63&dl=0
  
-Le site web de kind est **[[https://kind.sigs.k8s.io/docs/user/quick-start/]]**. Le lien du projet sur **github** est **[[https://github.com/kubernetes-sigs/kind]]**.+====Lab #2====
  
-====Installation de Docker-CE dans la VM Debian_10====+  * https://www.dropbox.com/scl/fi/sbzoft6ioo6gmo5n56035/readonly.yaml?rlkey=xsqnve5dvkg3l3nbuep06j0tj&dl=
 +  * https://www.dropbox.com/scl/fi/enbctxxwp95s10ssw3l13/drop.yaml?rlkey=pfo8r09cv9zk2xrxohyies9ki&dl=
 +  * https://www.dropbox.com/scl/fi/qptbh81o3gtl8bnii91er/guestbook-all-in-one.yaml?rlkey=5g3cr8a5llggdrme0le254pip&dl=
 +  * https://www.dropbox.com/scl/fi/664obj0d9d0y95kj3czsd/guestbook-network-policy.yaml?rlkey=u3o8yrgpgratq30jgk12rtj90&dl=0 
 +  * https://www.dropbox.com/scl/fi/f4f3mb8epcy7xr9cgmj1m/flask-resources.yaml?rlkey=l9gptrnet3mh4x5p2v09xvu06&dl=0
  
-Commencez par augmenter la RAM de la machine virtuelle Debian_10 :+=====LAB #1 - Role Based Acces Control et Certificats TLS=====
  
-<code> +====1.1 Présentation====
-desktop@serverXX:~$ VBoxManage modifyvm Debian_10 --memory 8192 +
-</code>+
  
-Configurez ensuite la redirection de port pour le service ssh :+Un objet Kubernetes est soit lié à un Namespace soit non-lié à un Namespace.
  
-<code> +Kubernetes utilise l'API **rbac.authorization.k8s.io** pour gérer les autorisations. Les acteurs jouant un rôle dans cette API sont :
-desktop@serverXX:~$ VBoxManage modifyvm "Debian_10" --natpf1 "Debian_10,tcp,,9022,,22" +
-</code>+
  
-Démarrez la machine virtuelle Debian_10 :+  * **Namespaces**, 
 +    * peuvent être considérées comme des clusters virtuels, 
 +    * permettent l'isolation et la segmentation logique, 
 +    * permettent le regroupement d'utilisateurs, de rôles et de ressources, 
 +    * sont utilisés avec des applications, des clients, des projets ou des équipes.
  
-<code> +  * **Subjects**, 
-desktop@serverXX:~$ VBoxManage startvm Debian_10 --type headless +    //Regular Users// - permettent la gestion des accès autorisés depuis l'extérieur du cluster que cela soit par un utilisateur physique ou sous une autre formeLa gestion des utilisateurs est la responsabilité de l'Administrateur du cluster
-Waiting for VM "Debian_10" to power on... +    * //ServiceAccounts// - permettent la mise en place de permissions au niveau des entités logicielsKubernetes crée un certain nombre de serviceAccounts automatiquement mais l'Administrateur peut en créer d'autresChaque pod a un serviceAccount qui gère les privilèges accordés au processus et aux conteneurs du pod
-VM "Debian_10" has been successfully started. +    * //User Groups// - Kubernetes regroupe des utilisateurs en utilisant des propriétés communes telles le préfixe d'un serviceAccount ou le champ de l'organisation dans un certificatIl est ensuite possible d'accorder des privilèges de type RBAC aux groupes ainsi créés.
-</code> +
- +
-Patientez 2 minutes puis connectez-vous à la machine virtuelle : +
- +
-<code> +
-desktop@serverXX:~$ ssh -l trainee localhost -p 9022 +
-trainee@localhost's password:  +
-Linux debian10 4.19.0-6-amd64 #1 SMP Debian 4.19.67-2+deb10u2 (2019-11-11) x86_64 +
- +
-The programs included with the Debian GNU/Linux system are free software; +
-the exact distribution terms for each program are described in the +
-individual files in /usr/share/doc/*/copyright. +
- +
-Debian GNU/Linux comes with ABSOLUTELY NO WARRANTYto the extent +
-permitted by applicable law. +
-Last login: Mon Nov 30 15:50:01 2020 from 10.0.2.2 +
-</code> +
- +
-Installez ensuite Docker-CE : +
- +
-<code> +
-trainee@debian10:~$ su - +
-Password: fenestros +
-root@debian10:~#  +
- +
-root@debian10:~# apt-get update && apt-get install -y apt-transport-https ca-certificates curl software-properties-common gnupg2 +
-... +
-root@debian10:~# curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add - +
-... +
-root@debian10:~# add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable" +
-... +
-root@debian10:~# apt-get update && apt-get install -y containerd.io=1.2.13-2 docker-ce=5:19.03.11~3-0~debian-$(lsb_release -cs) docker-ce-cli=5:19.03.11~3-0~debian-$(lsb_release -cs) +
-... +
-root@debian10:~# vi /etc/docker/daemon.json +
-root@debian10:~# cat /etc/docker/daemon.json +
-+
-  "exec-opts": ["native.cgroupdriver=systemd"], +
-  "log-driver": "json-file", +
-  "log-opts": { +
-    "max-size": "100m" +
-  }, +
-  "storage-driver": "overlay2" +
-+
-root@debian10:~# mkdir -p /etc/systemd/system/docker.service.d +
-root@debian10:~# systemctl daemon-reload +
-root@debian10:~# systemctl restart docker +
-root@debian10:~# docker version +
-Client: Docker Engine - Community +
- Version:           19.03.11 +
- API version:       1.40 +
- Go version:        go1.13.10 +
- Git commit:        42e35e61f3 +
- Built:             Mon Jun  1 09:12:44 2020 +
- OS/Arch:           linux/amd64 +
- Experimental:      false +
- +
-Server: Docker Engine - Community +
- Engine: +
-  Version:          19.03.11 +
-  API version:      1.40 (minimum version 1.12) +
-  Go version:       go1.13.10 +
-  Git commit:       42e35e61f3 +
-  Built:            Mon Jun  1 09:11:17 2020 +
-  OS/Arch:          linux/amd64 +
-  Experimental:     false +
- containerd: +
-  Version:          1.2.13 +
-  GitCommit:        7ad184331fa3e55e52b890ea95e65ba581ae3429 +
- runc: +
-  Version:          1.0.0-rc10 +
-  GitCommit:        dc9208a3303feef5b3839f4323d9beb36df0a9dd +
- docker-init: +
-  Version:          0.18.0 +
-  GitCommit:        fec3683 +
-</code> +
- +
-====Installation de kubelet, kubeadm et kubectl==== +
- +
-Ajoutez la clef GPG pour le dépôt Kubernetes : +
- +
-<code> +
-root@debian10:~# curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - +
-OK +
-</code> +
- +
-Ajoutez le dépôt de Kubernetes : +
- +
-<code> +
-root@debian10:~# echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | tee -a /etc/apt/sources.list.d/kubernetes.list +
-deb https://apt.kubernetes.io/ kubernetes-xenial main +
-</code> +
- +
-Procédez à l'installation de kubeadmkubelet et kubectl : +
- +
-<code> +
-root@debian10:~# apt-get update && apt-get install -y kubeadm kubelet kubectl +
-</code> +
- +
-Bloquez les mises-à-jour de kubeadm, kubelet et kubectl : +
- +
-<code> +
-root@debian10:~# apt-mark hold kubelet kubeadm kubectl +
-kubelet set on hold. +
-kubeadm set on hold. +
-kubectl set on hold. +
-</code> +
- +
- +
- +
-====Installation de kind et Démarrage du Cluster==== +
- +
-Installez **kind** : +
- +
-<code> +
-root@debian10:~# curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.9.0/kind-linux-amd64 +
-  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current +
-                                 Dload  Upload   Total   Spent    Left  Speed +
-100    97  100    97    0        339      0 --:--:-- --:--:-- --:--:--   337 +
-100   642  100   642    0       1414      0 --:--:-- --:--:-- --:--:--  1414 +
-100 7247k  100 7247k    0      3549k      0  0:00:02  0:00:02 --:--:-- 9522k +
-root@debian10:~# chmod +x ./kind +
-root@debian10:~# mv kind /usr/local/bin/ +
-root@debian10:~# which kind +
-/usr/local/bin/kind +
-</code> +
- +
-Re-démarrez la machine virtuelle : +
- +
-<code> +
-root@debian10:~# shutdown -r now +
-</code> +
- +
-Connectez-vous à la machine virtuelle Debian_10 : +
- +
-<code> +
-desktop@serverXX:~$ ssh -trainee localhost -p 9022 +
-trainee@localhost's password: trainee +
-Linux debian10 4.19.0-6-amd64 #1 SMP Debian 4.19.67-2+deb10u2 (2019-11-11) x86_64 +
- +
-The programs included with the Debian GNU/Linux system are free software; +
-the exact distribution terms for each program are described in the +
-individual files in /usr/share/doc/*/copyright. +
- +
-Debian GNU/Linux comes with ABSOLUTELY NO WARRANTYto the extent +
-permitted by applicable law. +
-Last login: Mon Nov 30 13:47:09 2020 from 10.0.2.2 +
-</code> +
- +
-Devenez **root** et créez le fichier **config.yaml** : +
- +
-<code> +
-trainee@debian10:~$ su - +
-Password: fenestros +
-root@debian10:~# vi config.yaml +
-root@debian10:~# cat config.yaml +
-kind: Cluster +
-apiVersion: kind.x-k8s.io/v1alpha4 +
-kubeadmConfigPatches: +
-- | +
-  apiVersion: kubelet.config.k8s.io/v1beta1 +
-  kind: KubeletConfiguration +
-  evictionHard: +
-    nodefs.available: "0%" +
-kubeadmConfigPatchesJSON6902: +
-- group: kubeadm.k8s.io +
-  version: v1beta2 +
-  kind: ClusterConfiguration +
-  patch: | +
-    - op: add +
-      path: /apiServer/certSANs/- +
-      value: my-hostname +
-nodes: +
-- role: control-plane +
-- role: worker +
-- role: worker +
-- role: worker +
-</code> +
- +
-Créez un cluster avec **kind** : +
- +
-<code> +
-root@debian10:~# kind create cluster --config config.yaml +
-Creating cluster "kind" ... +
- ✓ Ensuring node image (kindest/node:v1.19.1) 🖼  +
- ✓ Preparing nodes 📦 📦 📦 📦   +
- ✓ Writing configuration 📜  +
- ✓ Starting control-plane 🕹️  +
- ✓ Installing CNI 🔌  +
- ✓ Installing StorageClass 💾  +
- ✓ Joining worker nodes 🚜  +
-Set kubectl context to "kind-kind" +
-You can now use your cluster with: +
- +
-kubectl cluster-info --context kind-kind +
- +
-Not sure what to do next? 😅  Check out https://kind.sigs.k8s.io/docs/user/quick-start/ +
-</code> +
- +
-=====LAB #1 - Travailler avec kubectl=====+
  
-====1.1 Équivalences entre la commande docker et la commande kubectl====+  * **Resources**, 
 +    * ce sont des entités auxquelles auront accès les Subjects, 
 +    * une ressource est une entité telle un pod, un deployment ou des sous-ressources telles les journaux d'un pod, 
 +    * le Pod Security Policy (PSP) est aussi considéré comme une ressource.
  
-Un pré-requis pour travailler avec Kubernetes est de bien comprendre la commande **docker**. Pour faciliter la migration de l'utilisation de la commande docker vers la commande **kubectl**, voici une liste des commandes les plus utilisées :+  * **Roles** et **ClusterRoles**, 
 +    * //Roles// - permettent de définir des règles représentant un jeu de permissions, telles GET WATCH LIST CREATE UPDATE PATCH et DELETE, qui peuvent être utilisées avec des ressources dans un Namespace, 
 +      * On ajoute des permissions, on ne les retire pas. Il n'y a pas donc des règles de type **deny**
 +    * //ClusterRoles// - n'est pas lié à un Namespace. Un ClusterRole est utilisé pour :  
 +      * définir des permissions pour des ressources à être utilisées dans un Namespace 
 +      * définir des permissions pour des ressources à être utilisées dans tous les Namespaces 
 +      * définir des permissions pour des ressources du cluster.
  
-Pour obtenir de l'information concernant le cluster la commande docker :+Un exemple d'un Role pour accorder les permissions dans le Namespace default est :
  
 <file> <file>
-# docker info+apiVersion: rbac.authorization.k8s.io/v1 
 +kind: Role 
 +metadata: 
 +  namespace: default 
 +  name: pod-reader 
 +rules: 
 +- apiGroups: [""
 +  resources: ["pods"
 +  verbs: ["get", "watch", "list"]
 </file> </file>
  
-devient : +<WRAP center round important
- +**Important** apiGroups["""" indique le groupe api core ou legacy. Ce groupe se trouve au chemin REST /api/v1Ce groupe n'est jamais spécifié dans un champs apiVersion, d'où la raison pour laquelle on écrit apiVersion: v1 et non apiVersion api/v1.
-<file+
-# kubectl cluster-info +
-</file> +
- +
-Pour obtenir l'information concernant la version de la commande docker : +
- +
-<file> +
-# docker version +
-</file> +
- +
-devient  +
- +
-<file> +
-# kubectl info +
-</file> +
- +
-Pour lancer un conteneur nginx en exposant le port 80, la commande docker : +
- +
-<file> +
-# docker run -d --restart=always --name nginx -p 80:80 nginx +
-</file> +
- +
-devient deux commandes : +
- +
-<file> +
-# kubectl create deployment --image=nginx nginx +
-</file> +
- +
-et : +
- +
-<file> +
-# kubectl expose deployment nginx --port=80 --name=nginx +
-</file> +
- +
-Pour voir les traces en continue des logs du conteneur nginx, la commande docker : +
- +
-<file> +
-# docker logs -f nginx +
-</file> +
- +
-où nginx est le nom du conteneur, +
- +
-devient : +
- +
-<file> +
-# kubectl logs -f nginx +
-</file> +
- +
-où nginx est le nom du pod. +
- +
-<WRAP center round tip 40%> +
-Un POD est un objet qui encapsule un conteneur. Le conteneur est un instance d'une application. La relation entre un POD et un conteneur d'application est en règle générale 1:1c'est-à-dire que dans le cas d'une augmentation de la charge, des PODs additionnels sont créés, chacun contenant un conteneur d'application au lieu de créer plusieurs conteneurs dans le même POD+
 </WRAP> </WRAP>
  
-Pour se place dans le conteneur nginx, la commande docker :+Un example d'un ClusterRole pour accorder des permissions de lecture des secrets dans un Namespace spécifique ou dans tous les Namespaces est :
  
 <file> <file>
-# docker exec -it nginx /bin/bash+apiVersion: rbac.authorization.k8s.io/v1 
 +kind: ClusterRole 
 +metadata: 
 +  name: secret-reader 
 +rules: 
 +- apiGroups: [""
 +  resources: ["secrets"
 +  verbs: ["get", "watch", "list"]
 </file> </file>
  
-où nginx est le nom du conteneur,+  * **RoleBindings** et **ClusterRoleBindings**, 
 +    * permettent d'accorder des permissions définies dans des Roles ou ClusterRoles à des Subjects, 
 +    * **RoleBindings** sont spécifiques à un NameSpace, 
 +    * **ClusterRoleBindings** s'appliquent au niveau du Cluster.
  
-devient :+====1.2 - Le Fichier /etc/kubernetes/manifests/kube-apiserver.yaml====
  
-<file> +L'utilisation de RBAC est définie par la valeur de la directive **--authorization-mode** dans le fichier **/etc/kubernetes/manifests/kube-apiserver.yaml** :
-# kubectl exec -it nginx +
-</file> +
- +
-où nginx est le nom du pod. +
- +
-Pour obtenir la liste des conteneurs, la commande docker : +
- +
-<file> +
-# docker ps -+
-</file> +
- +
-devient : +
- +
-<file> +
-# kubectl get pods +
-</file> +
- +
-Pour arrêter et supprimer le conteneur nginx, les commandes docker : +
- +
-<file> +
-# docker stop nginx +
-# docker rm nginx +
-</file> +
- +
-deviennent : +
- +
-<file> +
-# kubectl delete deployment nginx +
-</file> +
- +
-où nginx est le nom de déploiement et, +
- +
-<file> +
-# kubectl delete pod nginx +
-</file> +
- +
-<WRAP center round tip 40%> +
-Un Deployment sous Kubernetes est un objet hiérarchiquement supérieur à un ReplicaSet. Un ReplicaSet remplit la même fonction qu'un Contrôleur de Réplication. ReplicaSets sont la façon la plus récente de gérer la réplication. Un Contrôleur de Réplication permet d'exécuter plusieurs instances du même POD de façon à offrir de la haute disponibilité au cas où l'application crash et le POD se met en échec. Même dans le cas où il n'y a qu'un seul POD, le Contrôleur de Réplication peut démarrer automatiquement un autre POD contenant l'application. +
-</WRAP> +
- +
-====1.2 - Obtenir de l'Aide sur les Commandes de kubectl==== +
- +
-Les commandes de **kubectl** sont regroupées par catégorie :+
  
 <code> <code>
-root@debian10:~# kubectl --help +root@kubemaster:~# cat /etc/kubernetes/manifests/kube-apiserver.yaml 
-kubectl controls the Kubernetes cluster manager+apiVersion: v1 
- +kindPod 
- Find more information athttps://kubernetes.io/docs/reference/kubectl/overview/ +metadata: 
- +  annotations: 
-Basic Commands (Beginner): +    kubeadm.kubernetes.io/kube-apiserver.advertise-address.endpoint192.168.56.2:6443 
-  create        Create a resource from a file or from stdin+  creationTimestamp: null 
-  expose        Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service +  labels: 
-  run           Run a particular image on the cluster +    component: kube-apiserver 
-  set           Set specific features on objects +    tiercontrol-plane 
- +  name: kube-apiserver 
-Basic Commands (Intermediate)+  namespace: kube-system 
-  explain       Documentation of resources +spec: 
-  get           Display one or many resources +  containers: 
-  edit          Edit a resource on the server +  - command: 
-  delete        Delete resources by filenamesstdin, resources and names, or by resources and label selector +    - kube-apiserver 
- +    - --advertise-address=192.168.56.2 
-Deploy Commands+    - --allow-privileged=true 
-  rollout       Manage the rollout of a resource +    - --authorization-mode=Node,RBAC 
-  scale         Set a new size for a Deployment, ReplicaSet or Replication Controller +    - --client-ca-file=/etc/kubernetes/pki/ca.crt 
-  autoscale     Auto-scale a DeploymentReplicaSetor ReplicationController +    - --enable-admission-plugins=NodeRestriction 
- +    - --enable-bootstrap-token-auth=true 
-Cluster Management Commands: +    - --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt 
-  certificate   Modify certificate resources+    - --etcd-certfile=/etc/kubernetes/pki/apiserver-etcd-client.crt 
-  cluster-info  Display cluster info +    - --etcd-keyfile=/etc/kubernetes/pki/apiserver-etcd-client.key 
-  top           Display Resource (CPU/Memory/Storage) usage+    - --etcd-servers=https://127.0.0.1:2379 
-  cordon        Mark node as unschedulable +    - --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt 
-  uncordon      Mark node as schedulable +    - --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key 
-  drain         Drain node in preparation for maintenance +    --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname 
-  taint         Update the taints on one or more nodes +    - --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.crt 
- +    - --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client.key 
-Troubleshooting and Debugging Commands+    - --requestheader-allowed-names=front-proxy-client 
-  describe      Show details of a specific resource or group of resources +    - --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt 
-  logs          Print the logs for a container in a pod +    - --requestheader-extra-headers-prefix=X-Remote-Extra- 
-  attach        Attach to a running container +    - --requestheader-group-headers=X-Remote-Group 
-  exec          Execute a command in a container +    - --requestheader-username-headers=X-Remote-User 
-  port-forward  Forward one or more local ports to a pod +    - --secure-port=6443 
-  proxy         Run a proxy to the Kubernetes API server +    - --service-account-issuer=https://kubernetes.default.svc.cluster.local 
-  cp            Copy files and directories to and from containers. +    - --service-account-key-file=/etc/kubernetes/pki/sa.pub 
-  auth          Inspect authorization +    - --service-account-signing-key-file=/etc/kubernetes/pki/sa.key 
- +    - --service-cluster-ip-range=10.96.0.0/12 
-Advanced Commands+    - --tls-cert-file=/etc/kubernetes/pki/apiserver.crt 
-  diff          Diff live version against would-be applied version +    - --tls-private-key-file=/etc/kubernetes/pki/apiserver.key 
-  apply         Apply a configuration to a resource by filename or stdin +    image: k8s.gcr.io/kube-apiserver:v1.24.2 
-  patch         Update field(s) of a resource using strategic merge patch +    imagePullPolicy: IfNotPresent 
-  replace       Replace a resource by filename or stdin +    livenessProbe: 
-  wait          ExperimentalWait for a specific condition on one or many resources. +      failureThreshold:
-  convert       Convert config files between different API versions +      httpGet: 
-  kustomize     Build a kustomization target from a directory or a remote url. +        host: 192.168.56.2 
- +        path: /livez 
-Settings Commands+        port: 6443 
-  label         Update the labels on a resource +        scheme: HTTPS 
-  annotate      Update the annotations on a resource +      initialDelaySeconds: 10 
-  completion    Output shell completion code for the specified shell (bash or zsh) +      periodSeconds: 10 
- +      timeoutSeconds: 15 
-Other Commands+    name: kube-apiserver 
-  alpha         Commands for features in alpha +    readinessProbe
-  api-resources Print the supported API resources on the server +      failureThreshold:
-  api-versions  Print the supported API versions on the server, in the form of "group/version" +      httpGet: 
-  config        Modify kubeconfig files +        host: 192.168.56.2 
-  plugin        Provides utilities for interacting with plugins. +        path: /readyz 
-  version       Print the client and server version information +        port: 6443 
- +        scheme: HTTPS 
-Usage+      periodSeconds:
-  kubectl [flags] [options] +      timeoutSeconds: 15 
- +    resources: 
-Use "kubectl <command> --help" for more information about a given command. +      requests: 
-Use "kubectl options" for a list of global command-line options (applies to all commands).+        cpu: 250m 
 +    startupProbe: 
 +      failureThreshold: 24 
 +      httpGet: 
 +        host: 192.168.56.2 
 +        path: /livez 
 +        port: 6443 
 +        scheme: HTTPS 
 +      initialDelaySeconds: 10 
 +      periodSeconds: 10 
 +      timeoutSeconds: 15 
 +    volumeMounts: 
 +    mountPath: /etc/ssl/certs 
 +      name: ca-certs 
 +      readOnly: true 
 +    - mountPath: /etc/ca-certificates 
 +      name: etc-ca-certificates 
 +      readOnlytrue 
 +    mountPath: /etc/kubernetes/pki 
 +      name: k8s-certs 
 +      readOnly: true 
 +    - mountPath: /usr/local/share/ca-certificates 
 +      name: usr-local-share-ca-certificates 
 +      readOnly: true 
 +    - mountPath: /usr/share/ca-certificates 
 +      name: usr-share-ca-certificates 
 +      readOnly: true 
 +  hostNetworktrue 
 +  priorityClassName: system-node-critical 
 +  securityContext: 
 +    seccompProfile: 
 +      typeRuntimeDefault 
 +  volumes: 
 +  - hostPath: 
 +      path: /etc/ssl/certs 
 +      type: DirectoryOrCreate 
 +    name: ca-certs 
 +  - hostPath: 
 +      path/etc/ca-certificates 
 +      type: DirectoryOrCreate 
 +    name: etc-ca-certificates 
 +  - hostPath: 
 +      path: /etc/kubernetes/pki 
 +      type: DirectoryOrCreate 
 +    name: k8s-certs 
 +  - hostPath: 
 +      path: /usr/local/share/ca-certificates 
 +      typeDirectoryOrCreate 
 +    name: usr-local-share-ca-certificates 
 +  - hostPath: 
 +      path: /usr/share/ca-certificates 
 +      type: DirectoryOrCreate 
 +    name: usr-share-ca-certificates 
 +status: {}
 </code> </code>
  
-Plus d'informations sur chaque commande peut être obtenue en passant l'option **--help**, par exemple :+====1.3 - Création d'un serviceAccount====
  
-<code> +Il est préférable de créer un serviceAccount par service. Ceci permet une configuration plus fine de la sécurité concernant le service. Si un serviceAccount n'est pas spécifié lors de la création des pods, ces pods se verront attribués le serviceAccount par défaut du Namespace.
-root@debian10:~# kubectl create --help +
-Create a resource from a file or from stdin.+
  
- JSON and YAML formats are accepted. +Imaginons que vous souhaitez que votre application interagisse avec l'API de Kubernetes afin d'obtenir des informations sur les pods dans un Namespacele serviceAccount par défaut dasn le Namespace **default** ne peut pas accomplir cette tâche :
- +
-Examples: +
-  # Create a pod using the data in pod.json. +
-  kubectl create -f ./pod.json +
-   +
-  # Create a pod based on the JSON passed into stdin. +
-  cat pod.json | kubectl create -f - +
-   +
-  # Edit the data in docker-registry.yaml in JSON then create the resource using the edited data. +
-  kubectl create -f docker-registry.yaml --edit -o json +
- +
-Available Commands: +
-  clusterrole         Create a ClusterRole. +
-  clusterrolebinding  Create a ClusterRoleBinding for a particular ClusterRole +
-  configmap           Create a configmap from a local file, directory or literal value +
-  cronjob             Create a cronjob with the specified name. +
-  deployment          Create a deployment with the specified name. +
-  job                 Create a job with the specified name. +
-  namespace           Create a namespace with the specified name +
-  poddisruptionbudget Create a pod disruption budget with the specified name. +
-  priorityclass       Create a priorityclass with the specified name. +
-  quota               Create a quota with the specified name. +
-  role                Create a role with single rule. +
-  rolebinding         Create a RoleBinding for a particular Role or ClusterRole +
-  secret              Create a secret using specified subcommand +
-  service             Create a service using specified subcommand. +
-  serviceaccount      Create a service account with the specified name +
- +
-Options: +
-      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in +
-the template. Only applies to golang and jsonpath output formats. +
-      --dry-run='none': Must be "none", "server", or "client". If client strategy, only print the object that would be +
-sent, without sending it. If server strategy, submit server-side request without persisting the resource. +
-      --edit=false: Edit the API resource before creating +
-      --field-manager='kubectl-create': Name of the manager used to track field ownership. +
-  -f, --filename=[]: Filename, directory, or URL to files to use to create the resource +
-  -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R. +
-  -o, --output='': Output format. One of: +
-json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file. +
-      --raw='': Raw URI to POST to the server.  Uses the transport specified by the kubeconfig file. +
-      --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the +
-command. If set to true, record the command. If not set, default to updating the existing annotation value only if one +
-already exists. +
-  -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage +
-related manifests organized within the same directory. +
-      --save-config=false: If true, the configuration of current object will be saved in its annotation. Otherwise, the +
-annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. +
-  -l, --selector='': Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2) +
-      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The +
-template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview]. +
-      --validate=true: If true, use a schema to validate the input before sending it +
-      --windows-line-endings=false: Only relevant if --edit=true. Defaults to the line ending native to your platform. +
- +
-Usage: +
-  kubectl create -f FILENAME [options] +
- +
-Use "kubectl <command> --help" for more information about a given command. +
-Use "kubectl options" for a list of global command-line options (applies to all commands). +
-</code> +
- +
-Dernièrement les commandes kubectl peuvent recevoir des options. Pour visualiser les options qui peuvent être passées à toutes les commandes kubectl, saisissez la commande suivante :+
  
 <code> <code>
-root@debian10:~# kubectl options +root@kubemaster:~# kubectl auth can-i list pods -n default --as=system:serviceaccount:default:default 
-The following options can be passed to any command: +no
- +
-      --add-dir-header=false: If true, adds the file directory to the header of the log messages +
-      --alsologtostderr=false: log to standard error as well as files +
-      --as=''Username to impersonate for the operation +
-      --as-group=[]Group to impersonate for the operation, this flag can be repeated to specify multiple groups. +
-      --cache-dir='/root/.kube/cache'Default cache directory +
-      --certificate-authority='': Path to a cert file for the certificate authority +
-      --client-certificate='': Path to a client certificate file for TLS +
-      --client-key='': Path to a client key file for TLS +
-      --cluster='': The name of the kubeconfig cluster to use +
-      --context='': The name of the kubeconfig context to use +
-      --insecure-skip-tls-verify=false: If true, the server's certificate will not be checked for validity. This will +
-make your HTTPS connections insecure +
-      --kubeconfig='': Path to the kubeconfig file to use for CLI requests. +
-      --log-backtrace-at=:0: when logging hits line file:N, emit a stack trace +
-      --log-dir='': If non-empty, write log files in this directory +
-      --log-file='': If non-empty, use this log file +
-      --log-file-max-size=1800: Defines the maximum size a log file can grow to. Unit is megabytes. If the value is 0, +
-the maximum file size is unlimited. +
-      --log-flush-frequency=5s: Maximum number of seconds between log flushes +
-      --logtostderr=true: log to standard error instead of files +
-      --match-server-version=false: Require server version to match client version +
-  -n, --namespace='': If present, the namespace scope for this CLI request +
-      --password='': Password for basic authentication to the API server +
-      --profile='none': Name of profile to capture. One of (none|cpu|heap|goroutine|threadcreate|block|mutex) +
-      --profile-output='profile.pprof': Name of the file to write the profile to +
-      --request-timeout='0': The length of time to wait before giving up on a single server request. Non-zero values +
-should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests. +
-  -s, --server='': The address and port of the Kubernetes API server +
-      --skip-headers=false: If true, avoid header prefixes in the log messages +
-      --skip-log-headers=false: If true, avoid headers when opening log files +
-      --stderrthreshold=2: logs at or above this threshold go to stderr +
-      --tls-server-name='': Server name to use for server certificate validation. If it is not provided, the hostname +
-used to contact the server is used +
-      --token='': Bearer token for authentication to the API server +
-      --user='': The name of the kubeconfig user to use +
-      --username='': Username for basic authentication to the API server +
-  -v, --v=0: number for the log level verbosity +
-      --vmodule=: comma-separated list of pattern=N settings for file-filtered logging +
-      --warnings-as-errors=false: Treat warnings received from the server as errors and exit with a non-zero exit code+
 </code> </code>
  
-====1.3 - Obtenir de l'Information sur le Cluster==== +<WRAP center round important
- +**Important** : le format de la valeur de l'option **--as** est **system:serviceaccount:namespace:Nom_du_serviceaccount**.
-===La Commande version=== +
- +
-Commencez par obtenir l'information concernant la version du client et du serveur : +
- +
-<code+
-root@debian10:~# kubectl version --short +
-Client Version: v1.20.0 +
-Server Version: v1.19.1 +
-</code> +
- +
-===La Commande cluster-info=== +
- +
-Consultez ensuite les informations concernant le cluster : +
- +
-<code> +
-root@debian10:~# kubectl cluster-info +
-Kubernetes control plane is running at https://127.0.0.1:46537 +
-KubeDNS is running at https://127.0.0.1:46537/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy +
- +
-To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'+
-</code> +
- +
-===La Commande api-versions=== +
- +
-Afin de connaître les versions des API compatibles avec la version de Kubernetes installée, exécutez la commande **api-versions** : +
- +
-<code> +
-root@debian10:~# kubectl api-versions +
-admissionregistration.k8s.io/v1 +
-admissionregistration.k8s.io/v1beta1 +
-apiextensions.k8s.io/v1 +
-apiextensions.k8s.io/v1beta1 +
-apiregistration.k8s.io/v1 +
-apiregistration.k8s.io/v1beta1 +
-apps/v1 +
-authentication.k8s.io/v1 +
-authentication.k8s.io/v1beta1 +
-authorization.k8s.io/v1 +
-authorization.k8s.io/v1beta1 +
-autoscaling/v1 +
-autoscaling/v2beta1 +
-autoscaling/v2beta2 +
-batch/v1 +
-batch/v1beta1 +
-certificates.k8s.io/v1 +
-certificates.k8s.io/v1beta1 +
-coordination.k8s.io/v1 +
-coordination.k8s.io/v1beta1 +
-discovery.k8s.io/v1beta1 +
-events.k8s.io/v1 +
-events.k8s.io/v1beta1 +
-extensions/v1beta1 +
-networking.k8s.io/v1 +
-networking.k8s.io/v1beta1 +
-node.k8s.io/v1beta1 +
-policy/v1beta1 +
-rbac.authorization.k8s.io/v1 +
-rbac.authorization.k8s.io/v1beta1 +
-scheduling.k8s.io/v1 +
-scheduling.k8s.io/v1beta1 +
-storage.k8s.io/v1 +
-storage.k8s.io/v1beta1 +
-v1 +
-</code> +
- +
-===La Commande api-resources=== +
- +
-La commande **api-resources** permet de consulter la liste des ressources du cluster, à savoir : +
- +
-  * le nom de la ressource - **NAME**, +
-  * le nom court à utiliser avec kubectl - **SHORTNAMES**, +
-  * le groupe API auquel la ressource appartient - **APIGROUP**, +
-  * si oui ou non la ressource est liée à un namespace - **NAMESPACED**, +
-  * le type KIND de la ressource - **KIND**. +
- +
-<code> +
-root@debian10:~# kubectl api-resources +
-NAME                              SHORTNAMES   APIVERSION                        NAMESPACED   KIND +
-bindings                                       v1                                true         Binding +
-componentstatuses                 cs           v1                                false        ComponentStatus +
-configmaps                        cm           v1                                true         ConfigMap +
-endpoints                         ep           v1                                true         Endpoints +
-events                            ev           v1                                true         Event +
-limitranges                       limits       v1                                true         LimitRange +
-namespaces                        ns           v1                                false        Namespace +
-nodes                             no           v1                                false        Node +
-persistentvolumeclaims            pvc          v1                                true         PersistentVolumeClaim +
-persistentvolumes                 pv           v1                                false        PersistentVolume +
-pods                              po           v1                                true         Pod +
-podtemplates                                   v1                                true         PodTemplate +
-replicationcontrollers            rc           v1                                true         ReplicationController +
-resourcequotas                    quota        v1                                true         ResourceQuota +
-secrets                                        v1                                true         Secret +
-serviceaccounts                   sa           v1                                true         ServiceAccount +
-services                          svc          v1                                true         Service +
-mutatingwebhookconfigurations                  admissionregistration.k8s.io/v1   false        MutatingWebhookConfiguration +
-validatingwebhookconfigurations                admissionregistration.k8s.io/v1   false        ValidatingWebhookConfiguration +
-customresourcedefinitions         crd,crds     apiextensions.k8s.io/v1           false        CustomResourceDefinition +
-apiservices                                    apiregistration.k8s.io/v1         false        APIService +
-controllerrevisions                            apps/v1                           true         ControllerRevision +
-daemonsets                        ds           apps/v1                           true         DaemonSet +
-deployments                       deploy       apps/v1                           true         Deployment +
-replicasets                       rs           apps/v1                           true         ReplicaSet +
-statefulsets                      sts          apps/v1                           true         StatefulSet +
-tokenreviews                                   authentication.k8s.io/v1          false        TokenReview +
-localsubjectaccessreviews                      authorization.k8s.io/v1           true         LocalSubjectAccessReview +
-selfsubjectaccessreviews                       authorization.k8s.io/v1           false        SelfSubjectAccessReview +
-selfsubjectrulesreviews                        authorization.k8s.io/v1           false        SelfSubjectRulesReview +
-subjectaccessreviews                           authorization.k8s.io/v1           false        SubjectAccessReview +
-horizontalpodautoscalers          hpa          autoscaling/v1                    true         HorizontalPodAutoscaler +
-cronjobs                          cj           batch/v1beta1                     true         CronJob +
-jobs                                           batch/v1                          true         Job +
-certificatesigningrequests        csr          certificates.k8s.io/v1            false        CertificateSigningRequest +
-leases                                         coordination.k8s.io/v1            true         Lease +
-endpointslices                                 discovery.k8s.io/v1beta1          true         EndpointSlice +
-events                            ev           events.k8s.io/v1                  true         Event +
-ingresses                         ing          extensions/v1beta1                true         Ingress +
-ingressclasses                                 networking.k8s.io/v1              false        IngressClass +
-ingresses                         ing          networking.k8s.io/v1              true         Ingress +
-networkpolicies                   netpol       networking.k8s.io/v1              true         NetworkPolicy +
-runtimeclasses                                 node.k8s.io/v1beta1               false        RuntimeClass +
-poddisruptionbudgets              pdb          policy/v1beta1                    true         PodDisruptionBudget +
-podsecuritypolicies               psp          policy/v1beta1                    false        PodSecurityPolicy +
-clusterrolebindings                            rbac.authorization.k8s.io/v1      false        ClusterRoleBinding +
-clusterroles                                   rbac.authorization.k8s.io/v1      false        ClusterRole +
-rolebindings                                   rbac.authorization.k8s.io/v1      true         RoleBinding +
-roles                                          rbac.authorization.k8s.io/v1      true         Role +
-priorityclasses                   pc           scheduling.k8s.io/v1              false        PriorityClass +
-csidrivers                                     storage.k8s.io/v1                 false        CSIDriver +
-csinodes                                       storage.k8s.io/v1                 false        CSINode +
-storageclasses                    sc           storage.k8s.io/v1                 false        StorageClass +
-volumeattachments                              storage.k8s.io/v1                 false        VolumeAttachment +
-</code> +
- +
-====1.4 -Travailler avec les Nœuds==== +
- +
-Pour consulter les nœuds du cluster utilisez la commande **get nodes** : +
- +
-<code> +
-root@debian10:~# kubectl get nodes +
-NAME                 STATUS   ROLES    AGE     VERSION +
-kind-control-plane   Ready    master   4m56s   v1.19.1 +
-kind-worker          Ready    <none>   4m16s   v1.19.1 +
-kind-worker2         Ready    <none>   4m17s   v1.19.1 +
-kind-worker3         Ready    <none>   4m18s   v1.19.1 +
-</code> +
- +
-===La Commande describe node=== +
- +
-De l'information sur le nœud peut être obtenue grâce à la commande **describe node**. Dans la première partie de la sortie de la commande on peut constater : +
- +
-  * la section **Labels:**. Les Labels peuvent être utilisés pour gérer l'affinité d'un pod, autrement dit sur quel nœud un pod peut être schedulé en fonction des étiquettes associées au pod,  +
-  * la ligne **Unschedulable:      false** qui indique que le nœud accepte des pods. +
- +
-<code> +
-root@debian10:~# kubectl describe node kind-control-plane +
-Name:               kind-control-plane +
-Roles:              master +
-Labels:             beta.kubernetes.io/arch=amd64 +
-                    beta.kubernetes.io/os=linux +
-                    kubernetes.io/arch=amd64 +
-                    kubernetes.io/hostname=kind-control-plane +
-                    kubernetes.io/os=linux +
-                    node-role.kubernetes.io/master= +
-Annotations:        kubeadm.alpha.kubernetes.io/cri-socket: unix:///run/containerd/containerd.sock +
-                    node.alpha.kubernetes.io/ttl:+
-                    volumes.kubernetes.io/controller-managed-attach-detach: true +
-CreationTimestamp:  Fri, 11 Dec 2020 12:08:17 +0100 +
-Taints:             node-role.kubernetes.io/master:NoSchedule +
-Unschedulable:      false +
-Lease: +
-  HolderIdentity:  kind-control-plane +
-  AcquireTime:     <unset> +
-  RenewTime:       Fri, 11 Dec 2020 12:13:33 +0100 +
-Conditions: +
-  Type             Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message +
-  ----             ------  -----------------                 ------------------                ------                       ------- +
-  MemoryPressure   False   Fri, 11 Dec 2020 12:09:12 +0100   Fri, 11 Dec 2020 12:08:11 +0100   KubeletHasSufficientMemory   kubelet has sufficient memory available +
-  DiskPressure     False   Fri, 11 Dec 2020 12:09:12 +0100   Fri, 11 Dec 2020 12:08:11 +0100   KubeletHasNoDiskPressure     kubelet has no disk pressure +
-  PIDPressure      False   Fri, 11 Dec 2020 12:09:12 +0100   Fri, 11 Dec 2020 12:08:11 +0100   KubeletHasSufficientPID      kubelet has sufficient PID available +
-  Ready            True    Fri, 11 Dec 2020 12:09:12 +0100   Fri, 11 Dec 2020 12:09:12 +0100   KubeletReady                 kubelet is posting ready status +
-... +
-</code> +
- +
-Dans la deuxième partie de la sortie, on peut constater : +
- +
-  la section **Addresses:** contenant l'adresse IP ainsi que le nom d'hôte du nœud. +
- +
-<code> +
-... +
-Addresses: +
-  InternalIP:  172.18.0.3 +
-  Hostname:    kind-control-plane +
-Capacity: +
-  cpu:                1 +
-  ephemeral-storage:  19478160Ki +
-  hugepages-2Mi:      0 +
-  memory:             8170464Ki +
-  pods:               110 +
-Allocatable: +
-  cpu:                1 +
-  ephemeral-storage:  19478160Ki +
-  hugepages-2Mi:      0 +
-  memory:             8170464Ki +
-  pods:               110 +
-... +
-</code> +
- +
-Dans la troisième partie de la sortie, on peut constater : +
- +
-  * la section **System Info:** contenant de l'information sur le système d'exploitation ainsi que les versions de Docker et de Kubernetes, +
-  * la section **Non-terminated Pods** contenant de l'information sur les limites du CPU et de la mémoire de chaque POD en cours d'exécution. +
- +
-<code> +
-... +
-System Info: +
-  Machine ID:                 5fd4d39b652b43ce9feba503c0c53d17 +
-  System UUID:                734424d3-5513-4e2d-a7e3-7f4429493214 +
-  Boot ID:                    05357148-f589-4478-b096-5b18c0ddc66f +
-  Kernel Version:             4.19.0-6-amd64 +
-  OS Image:                   Ubuntu Groovy Gorilla (development branch) +
-  Operating System:           linux +
-  Architecture:               amd64 +
-  Container Runtime Version:  containerd://1.4.0 +
-  Kubelet Version:            v1.19.1 +
-  Kube-Proxy Version:         v1.19.1 +
-PodCIDR:                      10.244.0.0/24 +
-PodCIDRs:                     10.244.0.0/24 +
-ProviderID:                   kind://docker/kind/kind-control-plane +
-Non-terminated Pods:          (9 in total) +
-  Namespace                   Name                                          CPU Requests  CPU Limits  Memory Requests  Memory Limits  AGE +
-  ---------                   ----                                          ------------  ----------  ---------------  -------------  --- +
-  kube-system                 coredns-f9fd979d6-b87p7                       100m (10%)    0 (0%)      70Mi (0%)        170Mi (2%)     5m3s +
-  kube-system                 coredns-f9fd979d6-jwd68                       100m (10%)    0 (0%)      70Mi (0%)        170Mi (2%)     5m3s +
-  kube-system                 etcd-kind-control-plane                       0 (0%)        0 (0%)      0 (0%)           0 (0%)         5m9s +
-  kube-system                 kindnet-vrqzw                                 100m (10%)    100m (10%)  50Mi (0%)        50Mi (0%)      5m3s +
-  kube-system                 kube-apiserver-kind-control-plane             250m (25%)    0 (0%)      0 (0%)           0 (0%)         5m9s +
-  kube-system                 kube-controller-manager-kind-control-plane    200m (20%)    0 (0%)      0 (0%)           0 (0%)         5m9s +
-  kube-system                 kube-proxy-5zpkb                              0 (0%)        0 (0%)      0 (0%)           0 (0%)         5m3s +
-  kube-system                 kube-scheduler-kind-control-plane             100m (10%)    0 (0%)      0 (0%)           0 (0%)         5m9s +
-  local-path-storage          local-path-provisioner-78776bfc44-5rzmk       0 (0%)        0 (0%)      0 (0%)           0 (0%)         5m3s +
-... +
-</code> +
- +
-Dans la dernière partie de la sortie, on peut constater : +
- +
-  * la section **Allocated resources:** qui indique les ressources allouées au noeud. +
- +
-<code> +
-Allocated resources: +
-  (Total limits may be over 100 percent, i.e., overcommitted.) +
-  Resource           Requests    Limits +
-  --------           --------    ------ +
-  cpu                850m (85%)  100m (10%) +
-  memory             190Mi (2%)  390Mi (4%) +
-  ephemeral-storage  0 (0%)      0 (0%) +
-  hugepages-2Mi      0 (0%)      0 (0%) +
-Events: +
-  Type    Reason                   Age                    From        Message +
-  ----    ------                   ----                   ----        ------- +
-  Normal  NodeHasSufficientMemory  5m50s (x5 over 5m50s)  kubelet     Node kind-control-plane status is now: NodeHasSufficientMemory +
-  Normal  NodeHasNoDiskPressure    5m50s (x5 over 5m50s)  kubelet     Node kind-control-plane status is now: NodeHasNoDiskPressure +
-  Normal  NodeHasSufficientPID     5m50s (x4 over 5m50s)  kubelet     Node kind-control-plane status is now: NodeHasSufficientPID +
-  Normal  Starting                 5m9s                   kubelet     Starting kubelet. +
-  Normal  NodeHasSufficientMemory  5m9s                   kubelet     Node kind-control-plane status is now: NodeHasSufficientMemory +
-  Normal  NodeHasNoDiskPressure    5m9s                   kubelet     Node kind-control-plane status is now: NodeHasNoDiskPressure +
-  Normal  NodeHasSufficientPID     5m9s                   kubelet     Node kind-control-plane status is now: NodeHasSufficientPID +
-  Normal  NodeAllocatableEnforced  5m9s                   kubelet     Updated Node Allocatable limit across pods +
-  Normal  Starting                 4m44s                  kube-proxy  Starting kube-proxy. +
-  Normal  NodeReady                4m29s                  kubelet     Node kind-control-plane status is now: NodeReady +
-</code> +
- +
-===La Commande top=== +
- +
-La commande **top** nécessite à ce que l'API **Metrics** soit disponible dans le cluster. Pour déployer le serveur Metrics, téléchargez le fichier **components.yaml** : +
- +
-<code> +
-root@debian10:~# wget https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml +
---2020-12-11 12:18:04--  https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml +
-Resolving github.com (github.com)... 140.82.121.4 +
-Connecting to github.com (github.com)|140.82.121.4|:443... connected. +
-HTTP request sent, awaiting response... 302 Found +
-Location: https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.4.1/components.yaml [following] +
---2020-12-11 12:18:05--  https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.4.1/components.yaml +
-Reusing existing connection to github.com:443. +
-HTTP request sent, awaiting response... 302 Found +
-Location: https://github-production-release-asset-2e65be.s3.amazonaws.com/92132038/febd5000-290f-11eb-9fcb-f4b297446db8?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20201211%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20201211T111612Z&X-Amz-Expires=300&X-Amz-Signature=24dc37640df34082c3b89641b41443e32dbd400b013e8ec94848e5ff52483159&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=92132038&response-content-disposition=attachment%3B%20filename%3Dcomponents.yaml&response-content-type=application%2Foctet-stream [following] +
---2020-12-11 12:18:05--  https://github-production-release-asset-2e65be.s3.amazonaws.com/92132038/febd5000-290f-11eb-9fcb-f4b297446db8?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20201211%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20201211T111612Z&X-Amz-Expires=300&X-Amz-Signature=24dc37640df34082c3b89641b41443e32dbd400b013e8ec94848e5ff52483159&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=92132038&response-content-disposition=attachment%3B%20filename%3Dcomponents.yaml&response-content-type=application%2Foctet-stream +
-Resolving github-production-release-asset-2e65be.s3.amazonaws.com (github-production-release-asset-2e65be.s3.amazonaws.com)... 52.217.104.236 +
-Connecting to github-production-release-asset-2e65be.s3.amazonaws.com (github-production-release-asset-2e65be.s3.amazonaws.com)|52.217.104.236|:443... connected. +
-HTTP request sent, awaiting response... 200 OK +
-Length: 3962 (3.9K) [application/octet-stream] +
-Saving to: ‘components.yaml’ +
- +
-components.yaml     100%[===================>  3.87K  --.-KB/   in 0s       +
- +
-2020-12-11 12:18:05 (162 MB/s) - ‘components.yaml’ saved [3962/3962] +
-</code> +
- +
-Modifiez la section **containers** du fichier **components.yaml** : +
- +
-<code> +
-root@debian10:~# vi components.yaml  +
-root@debian10:~#  +
-... +
-    spec: +
-      containers: +
-      - args: +
-        - --cert-dir=/tmp +
-        - --secure-port=4443 +
-        - --kubelet-insecure-tls +
-        - --kubelet-preferred-address-types=InternalIP,Hostname,InternalDNS,ExternalDNS,ExternalIP +
-        - --kubelet-use-node-status-port +
-... +
-</code> +
- +
-Déployez le serveur Metrics : +
- +
-<code> +
-root@debian10:~# kubectl apply -f components.yaml +
-serviceaccount/metrics-server created +
-clusterrole.rbac.authorization.k8s.io/system:aggregated-metrics-reader created +
-clusterrole.rbac.authorization.k8s.io/system:metrics-server created +
-rolebinding.rbac.authorization.k8s.io/metrics-server-auth-reader created +
-clusterrolebinding.rbac.authorization.k8s.io/metrics-server:system:auth-delegator created +
-clusterrolebinding.rbac.authorization.k8s.io/system:metrics-server created +
-service/metrics-server created +
-deployment.apps/metrics-server created +
-apiservice.apiregistration.k8s.io/v1beta1.metrics.k8s.io created +
-</code> +
- +
-Vérifiez l'état du deployment : +
- +
-<code> +
-root@debian10:~# kubectl get deployments --all-namespaces +
-NAMESPACE            NAME                     READY   UP-TO-DATE   AVAILABLE   AGE +
-kube-system          coredns                  2/2                2           14m +
-kube-system          metrics-server           1/               1           41s +
-local-path-storage   local-path-provisioner   1/               1           14m +
-</code>  +
- +
-Pour connaître l'utilisation des ressources par le nœud, utilisez la commande **top nodes** : +
- +
-<code> +
-root@debian10:~# kubectl top nodes +
-NAME                 CPU(cores)   CPU%   MEMORY(bytes)   MEMORY%    +
-kind-control-plane   222m         22%    786Mi           9%         +
-kind-worker          254m         25%    159Mi           1%         +
-kind-worker2         22m          2%     146Mi           1%         +
-kind-worker3         25m          2%     143Mi           1%  +
-</code> +
- +
-Pour voir l'évolution de l'utilisation des ressources par le nœud, utilisez la commande **watch** +
- +
-<code> +
-root@debian10:~$ watch kubectl top nodes +
-Every 2.0s: kubectl top nodes                 debian10: Fri Dec 11 12:24:21 2020 +
- +
-NAME                 CPU(cores)   CPU%   MEMORY(bytes)   MEMORY% +
-kind-control-plane   110m         11%    799Mi           10% +
-kind-worker          18m          1%     170Mi           2% +
-kind-worker2         13m          1%     146Mi           1% +
-kind-worker3         14m          1%     143Mi           1% +
-... +
-^C +
-</code> +
- +
-<WRAP center round important 40%> +
-**Important** : Notez l'utilisation de **^C** pour sortir de l'écran de la commande **watch**. +
 </WRAP> </WRAP>
  
-===Les Commandes cordon et uncordon=== +Créez maintenant le fichier **flask.yaml** :
- +
-Afin d'empêcher un nœud de recevoir de nouveaux pods, utilisez la commande **cordon** :+
  
 <code> <code>
-root@debian10:~# kubectl cordon kind-worker +root@kubemaster:~# vi flask.yaml 
-node/kind-worker cordoned+root@kubemaster:~# cat flask.yaml  
 +apiVersion: v1 
 +kind: Namespace 
 +metadata: 
 +  name: flask 
 +--
 +apiVersion: v1 
 +kind: ServiceAccount 
 +metadata: 
 +  name: flask-backend 
 +  namespace: flask 
 +--- 
 +kind: Role 
 +apiVersion: rbac.authorization.k8s.io/v1 
 +metadata: 
 +  name: flask-backend-role 
 +  namespace: flask 
 +rules: 
 +  - apiGroups: [""
 +    resources: ["pods"
 +    verbs: ["get", "list", "watch"
 +--- 
 +kind: RoleBinding 
 +apiVersion: rbac.authorization.k8s.io/v1 
 +metadata: 
 +  name: flask-backend-role-binding 
 +  namespace: flask 
 +subjects: 
 +  - kind: ServiceAccount 
 +    name: flask-backend 
 +    namespace: flask 
 +roleRef: 
 +  kind: Role 
 +  name: flask-backend-role 
 +  apiGroup: rbac.authorization.k8s.io
 </code> </code>
  
-Consultez la ligne **Unschedulable:** dans la sortie de la commande **describe node** :+Ce fichier crée :
  
-<code> +  * un Namespace appelé **flask**, 
-root@debian10:~# kubectl describe node kind-worker | grep Unschedulable +  * un serviceAccount appelé **flask-backend** pour le Namespace **flask**, 
-Unschedulable:      true +  * un Role appelé **flask-backend-role** qui accorde les permissions **get**, **watch** et **list** sur les pods dans le Namespace **flask**, 
-</code>+  * un RoleBinding appelé **flask-backend-role-binding** qui accorde les permissions définies dans le Role **flask-backend-role** au Subject de type serviceAccount appelé **flask-backend**.
  
-<WRAP center round important 40%> +Appliquez le fichier :
-**Important** : Dans le cas d'un cluster à plusieurs nœuds, si le nœud concerné par la commande kubectl cordon redémarre, tous les pods seront ré-alloués aux autres nœuds.  +
-</WRAP> +
- +
-Pour autoriser de nouveau un nœud à recevoir de nouveaux pods, utilisez la commande **uncordon** :+
  
 <code> <code>
-root@debian10:~# kubectl uncordon kind-worker +root@kubemaster:~# kubectl create -f flask.yaml  
-node/kind-worker uncordoned +namespace/flask created 
-root@debian10:~# kubectl describe node kind-worker | grep Unschedulable +serviceaccount/flask-backend created 
-Unschedulable:      false+role.rbac.authorization.k8s.io/flask-backend-role created 
 +rolebinding.rbac.authorization.k8s.io/flask-backend-role-binding created
 </code> </code>
  
-===La Commande drain === +Créez maintenant le fichier **deployment.yaml** qui crée des pods qui utiliseront le serviceAccount appelé **flask-backend** :
- +
-La commande **drain** permet d'expulser les pods d'un nœud en les arrêtant. +
- +
-Commencez par constater quels pods sont sur le nœud  **kind-worker** :+
  
 <code> <code>
-root@debian10:~# kubectl get pods --all-namespaces -o wide +root@kubemaster:~# vi deployment.yaml  
-NAMESPACE            NAME                                         READY   STATUS    RESTARTS   AGE     IP           NODE                 NOMINATED NODE   READINESS GATES +root@kubemaster:~# cat deployment.yaml  
-kube-system          coredns-f9fd979d6-b87p7                      1/1     Running            3h16m   10.244.0.2   kind-control-plane   <none>           <none> +---
-kube-system          coredns-f9fd979d6-jwd68                      1/1     Running            3h16m   10.244.0.3   kind-control-plane   <none>           <none> +
-kube-system          etcd-kind-control-plane                      1/1     Running            3h16m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kindnet-5dk8c                                1/1     Running            3h15m   172.18.0.2   kind-worker          <none>           <none> +
-kube-system          kindnet-7jqqb                                1/1     Running            3h15m   172.18.0.5   kind-worker3         <none>           <none> +
-kube-system          kindnet-t8t9q                                1/1     Running            3h15m   172.18.0.4   kind-worker2         <none>           <none> +
-kube-system          kindnet-vrqzw                                1/1     Running            3h16m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kube-apiserver-kind-control-plane            1/1     Running            3h16m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kube-controller-manager-kind-control-plane   1/    Running            3h16m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kube-proxy-5zpkb                             1/    Running            3h16m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kube-proxy-8pp5m                             1/    Running            3h15m   172.18.0.4   kind-worker2         <none>           <none> +
-kube-system          kube-proxy-ltx6c                             1/    Running            3h15m   172.18.0.5   kind-worker3         <none>           <none> +
-kube-system          kube-proxy-nrkql                             1/    Running            3h15m   172.18.0.2   kind-worker          <none>           <none> +
-kube-system          kube-scheduler-kind-control-plane            1/1     Running            3h16m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          metrics-server-594b87569-9fcsq               1/    Running            3h2m    10.244.3.2   kind-worker          <none>           <none> +
-local-path-storage   local-path-provisioner-78776bfc44-5rzmk      1/1     Running            3h16m   10.244.0.4   kind-control-plane   <none>           <none> +
-</code> +
- +
-<WRAP center round important 40%> +
-**Important** : Dans le cas ci-dessus les pods **kindnet-5dk8c**, **kube-proxy-nrkql** et **metrics-server-594b87569-9fcsq** se trouvent sur le noeud **kind-worker**.  +
-</WRAP> +
- +
-Utilisez la commande drain pour expulser les pods sur le nœud **kind-worker** : +
- +
-<code> +
-root@debian10:~# kubectl drain kind-worker --ignore-daemonsets --delete-emptydir-data --force +
-node/kind-worker cordoned +
-WARNING: ignoring DaemonSet-managed Pods: kube-system/kindnet-5dk8c, kube-system/kube-proxy-nrkql +
-evicting pod kube-system/metrics-server-594b87569-9fcsq +
-pod/metrics-server-594b87569-9fcsq evicted +
-node/kind-worker evicted +
-</code> +
- +
-Constatez de nouveau quels pods sont sur le nœud  **kind-worker** : +
- +
-<code> +
-root@debian10:~# kubectl get pods --all-namespaces -o wide +
-NAMESPACE            NAME                                         READY   STATUS    RESTARTS   AGE     IP           NODE                 NOMINATED NODE   READINESS GATES +
-kube-system          coredns-f9fd979d6-b87p7                      1/1     Running            3h24m   10.244.0.2   kind-control-plane   <none>           <none> +
-kube-system          coredns-f9fd979d6-jwd68                      1/1     Running            3h24m   10.244.0.3   kind-control-plane   <none>           <none> +
-kube-system          etcd-kind-control-plane                      1/1     Running            3h24m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kindnet-5dk8c                                1/1     Running            3h24m   172.18.0.2   kind-worker          <none>           <none> +
-kube-system          kindnet-7jqqb                                1/1     Running            3h24m   172.18.0.5   kind-worker3         <none>           <none> +
-kube-system          kindnet-t8t9q                                1/1     Running            3h24m   172.18.0.4   kind-worker2         <none>           <none> +
-kube-system          kindnet-vrqzw                                1/1     Running            3h24m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kube-apiserver-kind-control-plane            1/1     Running            3h24m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kube-controller-manager-kind-control-plane   1/    Running            3h24m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kube-proxy-5zpkb                             1/    Running            3h24m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kube-proxy-8pp5m                             1/    Running            3h24m   172.18.0.4   kind-worker2         <none>           <none> +
-kube-system          kube-proxy-ltx6c                             1/    Running            3h24m   172.18.0.5   kind-worker3         <none>           <none> +
-kube-system          kube-proxy-nrkql                             1/    Running            3h24m   172.18.0.2   kind-worker          <none>           <none> +
-kube-system          kube-scheduler-kind-control-plane            1/1     Running            3h24m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          metrics-server-594b87569-28r4s               1/    Running            4m11s   10.244.1.2   kind-worker3         <none>           <none> +
-local-path-storage   local-path-provisioner-78776bfc44-5rzmk      1/1     Running            3h24m   10.244.0.4   kind-control-plane   <none>           <none> +
-</code> +
- +
-<WRAP center round important 40%> +
-**Important** : Notez que seul le pod **metrics-server-594b87569-9fcsq** a été expulsé. En effet les deux pods **kube-proxy-nrkql** et **kindnet-5dk8c** ont été créés par des DaemonSets. Un DaemonSet ne peut pas être supprimé d'un nœud Kubernetes, d'où l'utilisation des options **--ignore-daemonsets** et **--force**. +
-</WRAP> +
- +
-Constatez maintenant l'état des nœuds : +
- +
-<code> +
-root@debian10:~# kubectl get nodes +
-NAME                 STATUS                     ROLES    AGE     VERSION +
-kind-control-plane   Ready                      master   3h26m   v1.19.1 +
-kind-worker          Ready,SchedulingDisabled   <none>   3h25m   v1.19.1 +
-kind-worker2         Ready                      <none>   3h25m   v1.19.1 +
-kind-worker3         Ready                      <none>   3h25m   v1.19.1 +
-</code> +
- +
-<WRAP center round important 40%> +
-**Important** : Notez la présence de **SchedulingDisabled** dans la colonne **STATUS**. +
-</WRAP> +
- +
-===La Commande delete === +
- +
-Pour supprimer un nœud du cluster, utilisez la commande **delete** : +
- +
-<code> +
-root@debian10:~# kubectl delete node kind-worker +
-node "kind-worker" deleted +
-</code> +
- +
-En saisissant la commande **get nodes**, vous constaterez que le nœud semble avoir été supprimé : +
- +
-<code> +
-root@debian10:~# kubectl get nodes +
-NAME                 STATUS   ROLES    AGE     VERSION +
-kind-control-plane   Ready    master   3h27m   v1.19.1 +
-kind-worker2         Ready    <none>   3h26m   v1.19.1 +
-kind-worker3         Ready    <none>   3h26m   v1.19.1 +
-</code> +
- +
-En réalité, le nœud n'est pas supprimé tant que tous les pods du nœud n'ont pas été détruits : +
- +
-<code> +
-root@debian10:~# kubectl get pods --all-namespaces -o wide +
-NAMESPACE            NAME                                         READY   STATUS    RESTARTS   AGE     IP           NODE                 NOMINATED NODE   READINESS GATES +
-kube-system          coredns-f9fd979d6-b87p7                      1/1     Running            3h27m   10.244.0.2   kind-control-plane   <none>           <none> +
-kube-system          coredns-f9fd979d6-jwd68                      1/1     Running            3h27m   10.244.0.3   kind-control-plane   <none>           <none> +
-kube-system          etcd-kind-control-plane                      1/1     Running            3h27m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kindnet-5dk8c                                1/1     Running            3h27m   172.18.0.2   kind-worker          <none>           <none> +
-kube-system          kindnet-7jqqb                                1/1     Running            3h27m   172.18.0.5   kind-worker3         <none>           <none> +
-kube-system          kindnet-t8t9q                                1/1     Running            3h27m   172.18.0.4   kind-worker2         <none>           <none> +
-kube-system          kindnet-vrqzw                                1/1     Running            3h27m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kube-apiserver-kind-control-plane            1/1     Running            3h27m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kube-controller-manager-kind-control-plane   1/    Running            3h27m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kube-proxy-5zpkb                             1/    Running            3h27m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kube-proxy-8pp5m                             1/    Running            3h27m   172.18.0.4   kind-worker2         <none>           <none> +
-kube-system          kube-proxy-ltx6c                             1/    Running            3h27m   172.18.0.5   kind-worker3         <none>           <none> +
-kube-system          kube-proxy-nrkql                             1/    Running            3h27m   172.18.0.2   kind-worker          <none>           <none> +
-kube-system          kube-scheduler-kind-control-plane            1/1     Running            3h27m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          metrics-server-594b87569-28r4s               1/    Running            7m6s    10.244.1.2   kind-worker3         <none>           <none> +
-local-path-storage   local-path-provisioner-78776bfc44-5rzmk      1/1     Running            3h27m   10.244.0.4   kind-control-plane   <none>           <none> +
-</code> +
- +
-Après la destruction des pods, le nœud est effectivement détruit : +
- +
-<code> +
-root@debian10:~# kubectl get pods --all-namespaces -o wide +
-NAMESPACE            NAME                                         READY   STATUS    RESTARTS   AGE     IP           NODE                 NOMINATED NODE   READINESS GATES +
-kube-system          coredns-f9fd979d6-b87p7                      1/1     Running            3h29m   10.244.0.2   kind-control-plane   <none>           <none> +
-kube-system          coredns-f9fd979d6-jwd68                      1/1     Running            3h29m   10.244.0.3   kind-control-plane   <none>           <none> +
-kube-system          etcd-kind-control-plane                      1/1     Running            3h29m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kindnet-7jqqb                                1/1     Running            3h29m   172.18.0.5   kind-worker3         <none>           <none> +
-kube-system          kindnet-t8t9q                                1/1     Running            3h29m   172.18.0.4   kind-worker2         <none>           <none> +
-kube-system          kindnet-vrqzw                                1/1     Running            3h29m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kube-apiserver-kind-control-plane            1/1     Running            3h29m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kube-controller-manager-kind-control-plane   1/    Running            3h29m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kube-proxy-5zpkb                             1/    Running            3h29m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          kube-proxy-8pp5m                             1/    Running            3h29m   172.18.0.4   kind-worker2         <none>           <none> +
-kube-system          kube-proxy-ltx6c                             1/    Running            3h29m   172.18.0.5   kind-worker3         <none>           <none> +
-kube-system          kube-scheduler-kind-control-plane            1/1     Running            3h29m   172.18.0.3   kind-control-plane   <none>           <none> +
-kube-system          metrics-server-594b87569-28r4s               1/    Running            9m31s   10.244.1.2   kind-worker3         <none>           <none> +
-local-path-storage   local-path-provisioner-78776bfc44-5rzmk      1/1     Running            3h29m   10.244.0.4   kind-control-plane   <none>           <none> +
-</code> +
- +
-====1.5 - Gestion des Applications==== +
- +
-===La Commande expose=== +
- +
-Créez un deployment à partir de l'image **nginx** : +
- +
-<code> +
-root@debian10:~# kubectl create deployment nginx --image=nginx +
-deployment.apps/nginx created +
-root@debian10:~# kubectl get deployment +
-NAME    READY   UP-TO-DATE   AVAILABLE   AGE +
-nginx   1/               1           22s +
-root@debian10:~# kubectl get pods +
-NAME                     READY   STATUS    RESTARTS   AGE +
-nginx-6799fc88d8-sgc8w   1/    Running            30s +
-</code> +
- +
-Exposez maintenant le port 80 du pod grâce à la commande **expose** : +
- +
-<code> +
-root@debian10:~# kubectl expose deployment nginx --port=80 --target-port=80 +
-service/nginx exposed +
-root@debian10:~# kubectl describe service nginx +
-Name:              nginx +
-Namespace:         default +
-Labels:            app=nginx +
-Annotations:       <none> +
-Selector:          app=nginx +
-Type:              ClusterIP +
-IP Families:       <none> +
-IP:                10.96.114.21 +
-IPs:               <none> +
-Port:              <unset>  80/TCP +
-TargetPort:        80/TCP +
-Endpoints:         10.244.2.2:80 +
-Session Affinity:  None +
-Events:            <none> +
-</code> +
- +
-===La Commande get=== +
- +
-Visualisez le service avec la commande **get** : +
- +
-<code> +
-root@debian10:~# kubectl get service +
-NAME         TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE +
-kubernetes   ClusterIP   10.96.0.1      <none>        443/TCP   3h47m +
-nginx        ClusterIP   10.96.114.21   <none>        80/TCP    12s +
-</code> +
- +
-La commande **get** peut être utilisée pour créer une fichier au format YAML pour une création ultérieure du service : +
- +
-<code> +
-root@debian10:~# kubectl get service nginx -o yaml > service.yaml +
-root@debian10:~# cat service.yaml +
-apiVersion: v1 +
-kind: Service +
-metadata: +
-  creationTimestamp: "2020-12-11T14:55:41Z" +
-  labels: +
-    app: nginx +
-  managedFields: +
-  apiVersion: v1 +
-    fieldsType: FieldsV1 +
-    fieldsV1: +
-      f:metadata: +
-        f:labels: +
-          .: {} +
-          f:app: {} +
-      f:spec: +
-        f:ports: +
-          .: {} +
-          k:{"port":80,"protocol":"TCP"}: +
-            .: {} +
-            f:port: {} +
-            f:protocol: {} +
-            f:targetPort: {} +
-        f:selector: +
-          .: {} +
-          f:app: {} +
-        f:sessionAffinity: {} +
-        f:type: {} +
-    manager: kubectl-expose +
-    operation: Update +
-    time: "2020-12-11T14:55:41Z" +
-  name: nginx +
-  namespace: default +
-  resourceVersion: "41428" +
-  selfLink: /api/v1/namespaces/default/services/nginx +
-  uid: 4ef7c806-d88b-43fb-b53c-2bf418583290 +
-spec: +
-  clusterIP: 10.96.114.21 +
-  ports: +
-  - port: 80 +
-    protocol: TCP +
-    targetPort: 80 +
-  selector: +
-    app: nginx +
-  sessionAffinity: None +
-  type: ClusterIP +
-status: +
-  loadBalancer: {} +
-</code> +
- +
-La commande **get** peut aussi être utilisée pour créer une fichier au format YAML pour une création ultérieure du deployment : +
- +
-<code> +
-root@debian10:~# kubectl get deployment nginx -o yaml > deployment.yaml +
-root@debian10:~# cat deployment.yaml +
 apiVersion: apps/v1 apiVersion: apps/v1
-kind: Deployment+kind: Deployment 
 metadata: metadata:
-  annotations: +  namemyapp-deployment 
-    deployment.kubernetes.io/revision: "1" +  namespaceflask
-  creationTimestamp: "2020-12-11T14:54:24Z" +
-  generation1+
   labels:   labels:
-    app: nginx +    app: myapp 
-  managedFields: +    type: front-end
-  - apiVersion: apps/v1 +
-    fieldsType: FieldsV1 +
-    fieldsV1: +
-      f:metadata: +
-        f:labels: +
-          .: {} +
-          f:app: {} +
-      f:spec: +
-        f:progressDeadlineSeconds: {} +
-        f:replicas: {} +
-        f:revisionHistoryLimit: {} +
-        f:selector: +
-          f:matchLabels: +
-            .: {} +
-            f:app: {} +
-        f:strategy: +
-          f:rollingUpdate: +
-            .: {} +
-            f:maxSurge: {} +
-            f:maxUnavailable: {} +
-          f:type: {} +
-        f:template: +
-          f:metadata: +
-            f:labels: +
-              .: {} +
-              f:app: {} +
-          f:spec: +
-            f:containers: +
-              k:{"name":"nginx"}: +
-                .: {} +
-                f:image: {} +
-                f:imagePullPolicy: {} +
-                f:name: {} +
-                f:resources: {} +
-                f:terminationMessagePath: {} +
-                f:terminationMessagePolicy: {} +
-            f:dnsPolicy: {} +
-            f:restartPolicy: {} +
-            f:schedulerName: {} +
-            f:securityContext: {} +
-            f:terminationGracePeriodSeconds: {} +
-    manager: kubectl-create +
-    operation: Update +
-    time: "2020-12-11T14:54:24Z" +
-  - apiVersion: apps/v1 +
-    fieldsType: FieldsV1 +
-    fieldsV1: +
-      f:metadata: +
-        f:annotations: +
-          .: {} +
-          f:deployment.kubernetes.io/revision: {} +
-      f:status: +
-        f:availableReplicas: {} +
-        f:conditions: +
-          .: {} +
-          k:{"type":"Available"}: +
-            .: {} +
-            f:lastTransitionTime: {} +
-            f:lastUpdateTime: {} +
-            f:message: {} +
-            f:reason: {} +
-            f:status: {} +
-            f:type: {} +
-          k:{"type":"Progressing"}: +
-            .: {} +
-            f:lastTransitionTime: {} +
-            f:lastUpdateTime: {} +
-            f:message: {} +
-            f:reason: {} +
-            f:status: {} +
-            f:type: {} +
-        f:observedGeneration: {} +
-        f:readyReplicas: {} +
-        f:replicas: {} +
-        f:updatedReplicas: {} +
-    manager: kube-controller-manager +
-    operation: Update +
-    time: "2020-12-11T14:54:44Z" +
-  name: nginx +
-  namespace: default +
-  resourceVersion: "41257" +
-  selfLink: /apis/apps/v1/namespaces/default/deployments/nginx +
-  uid: ebd84992-0957-460e-bbdb-ab9a8e80f099+
 spec: spec:
-  progressDeadlineSeconds: 600 
-  replicas: 1 
-  revisionHistoryLimit: 10 
-  selector: 
-    matchLabels: 
-      app: nginx 
-  strategy: 
-    rollingUpdate: 
-      maxSurge: 25% 
-      maxUnavailable: 25% 
-    type: RollingUpdate 
   template:   template:
 +
     metadata:     metadata:
-      creationTimestampnull+      namemyapp-pod
       labels:       labels:
-        app: nginx+        app: myapp 
 +        type: front-end
     spec:     spec:
 +      serviceAccount: flask-backend
       containers:       containers:
-      - image: nginx +      - name: nginx-container 
-        imagePullPolicy: Always +        image: nginx
-        name: nginx +
-        resources: {} +
-        terminationMessagePath: /dev/termination-log +
-        terminationMessagePolicyFile +
-      dnsPolicy: ClusterFirst +
-      restartPolicy: Always +
-      schedulerName: default-scheduler +
-      securityContext: {} +
-      terminationGracePeriodSeconds: 30 +
-status: +
-  availableReplicas:+
-  conditions: +
-  - lastTransitionTime: "2020-12-11T14:54:44Z" +
-    lastUpdateTime: "2020-12-11T14:54:44Z" +
-    message: Deployment has minimum availability. +
-    reason: MinimumReplicasAvailable +
-    status: "True" +
-    type: Available +
-  - lastTransitionTime: "2020-12-11T14:54:24Z" +
-    lastUpdateTime: "2020-12-11T14:54:44Z" +
-    message: ReplicaSet "nginx-6799fc88d8" has successfully progressed. +
-    reason: NewReplicaSetAvailable +
-    status: "True" +
-    type: Progressing +
-  observedGeneration:+
-  readyReplicas:+
-  replicas: 1 +
-  updatedReplicas:+
-</code>+
  
-Éditez le fichier **deployment.yaml** pour augmenter le nombre de replicas : 
- 
-<code> 
-root@debian10:~$ vi deployment.yaml  
-root@debian10:~$ cat deployment.yaml  
-.. 
-spec: 
-  progressDeadlineSeconds: 600 
   replicas: 3   replicas: 3
-..+  selector:  
 +    matchLabels: 
 +      type: front-end
 </code> </code>
  
-Appliquez le fichier deployment.yaml :+Exécutez kubectl :
  
 <code> <code>
-root@debian10:~# kubectl apply -f deployment.yaml +root@kubemaster:~# kubectl create -f deployment.yaml 
-Warning: resource deployments/nginx is missing the kubectl.kubernetes.io/last-applied-configuration annotation which is required by kubectl apply. kubectl apply should only be used on resources created declaratively by either kubectl create --save-config or kubectl apply. The missing annotation will be patched automatically. +deployment.apps/myapp-deployment created
-deployment.apps/nginx configured+
 </code> </code>
  
-Vérifiez ensuite le statut du deployment :+Vérifiez la présence du deployment :
  
 <code> <code>
-root@debian10:~# kubectl get deployment nginx +root@kubemaster:~# kubectl get deployment -n flask 
-NAME    READY   UP-TO-DATE   AVAILABLE   AGE +NAME               READY   UP-TO-DATE   AVAILABLE   AGE 
-nginx   3/3                3           8m10s +myapp-deployment   3/3                3           32s
-root@debian10:~# kubectl get pods +
-NAME                     READY   STATUS    RESTARTS   AGE +
-nginx-6799fc88d8-gg4gt   1/    Running            68s +
-nginx-6799fc88d8-qs8bq   1/    Running            68s +
-nginx-6799fc88d8-sgc8w   1/    Running            8m27s+
 </code> </code>
  
-===La Commande set=== +Vérifiez maintenant que le serviceAccount **flask-backend** peut lister les pods dans le Namespace **flask** :
- +
-Utilisez la commande **set** afin de mettre à jour l'application vers la version **1.19.0** de nginx :+
  
 <code> <code>
-root@debian10:~# kubectl set image deployment nginx nginx=nginx:1.19.0 --record +root@kubemaster:~# kubectl auth can-i list pods -n flask --as=system:serviceaccount:flask:flask-backend 
-deployment.apps/nginx image updated+yes
 </code> </code>
  
-Vérifiez l'utilisation de l'image nginx 1.19.0 grâce à la commande **describe** :+Notez cependant que le serviceAccount **flask-backend** n'a pas la permission **create** dans le Namespace **flask** :
  
 <code> <code>
-root@debian10:~# kubectl describe deployment nginx +root@kubemaster:~# kubectl auth can-i create pods -n flask --as=system:serviceaccount:flask:flask-backend 
-Name:                   nginx +no
-Namespace:              default +
-CreationTimestamp:      Fri, 11 Dec 2020 15:54:24 +0100 +
-Labels:                 app=nginx +
-Annotations:            deployment.kubernetes.io/revision:+
-                        kubernetes.io/change-cause: kubectl set image deployment nginx nginx=nginx:1.19.0 --record=true +
-Selector              app=nginx +
-Replicas              3 desired | 1 updated | 4 total | 3 available | 1 unavailable +
-StrategyType          RollingUpdate +
-MinReadySeconds:        0 +
-RollingUpdateStrategy:  25% max unavailable, 25% max surge +
-Pod Template: +
-  Labels:  app=nginx +
-  Containers: +
-   nginx: +
-    Image:        nginx:1.19.0 +
-    Port:         <none> +
-    Host Port:    <none> +
-    Environment:  <none> +
-    Mounts:       <none> +
-  Volumes:        <none> +
-Conditions: +
-  Type           Status  Reason +
-  ----           ------  -----+
-  Available      True    MinimumReplicasAvailable +
-  Progressing    True    ReplicaSetUpdated +
-OldReplicaSets:  nginx-6799fc88d8 (3/3 replicas created) +
-NewReplicaSet:   nginx-6d5fb79b7f (1/1 replicas created) +
-Events: +
-  Type    Reason             Age    From                   Message +
-  ----    ------             ----   ----                   ------- +
-  Normal  ScalingReplicaSet  14m    deployment-controller  Scaled up replica set nginx-6799fc88d8 to 1 +
-  Normal  ScalingReplicaSet  7m32s  deployment-controller  Scaled up replica set nginx-6799fc88d8 to 3 +
-  Normal  ScalingReplicaSet  52s    deployment-controller  Scaled up replica set nginx-6d5fb79b7f to 1 +
-  Normal  ScalingReplicaSet  31s    deployment-controller  Scaled down replica set nginx-6799fc88d8 to 2 +
-  Normal  ScalingReplicaSet  30s    deployment-controller  Scaled up replica set nginx-6d5fb79b7f to 2 +
-  Normal  ScalingReplicaSet  12s    deployment-controller  Scaled down replica set nginx-6799fc88d8 to 1 +
-  Normal  ScalingReplicaSet  12s    deployment-controller  Scaled up replica set nginx-6d5fb79b7f to 3 +
-  Normal  ScalingReplicaSet  9s     deployment-controller  Scaled down replica set nginx-6799fc88d8 to 0+
 </code> </code>
  
-<WRAP center round important 40%> +et que le serviceAccount **flask-backend** n'a pas la permission **list** dans le Namespace **default** :
-**Important** : Notez la ligne **Image:        nginx:1.19.0**+
-</WRAP> +
- +
-Comme attendu, la commande **set** n'a pas mis à jour le fichier **deployment.yaml** :+
  
 <code> <code>
-root@debian10:~$ cat deployment.yaml +root@kubemaster:~# kubectl auth can-i list pods -n default --as=system:serviceaccount:flask:flask-backend 
-... +no
-    spec: +
-      containers: +
-      image: nginx +
-        imagePullPolicy: Always +
-        name: nginx +
-        resources: {} +
-        terminationMessagePath: /dev/termination-log +
-        terminationMessagePolicy: File +
-... +
-</code> +
- +
-Mettez donc à jour le fichier : +
- +
-<code> +
-root@debian10:~$ vi deployment.yaml  +
-root@debian10:~$ cat deployment.yaml  +
-... +
-    spec: +
-      containers: +
-      imagenginx:1.19.0  +
-        imagePullPolicyAlways +
-        name: nginx +
-        resources: {} +
-        terminationMessagePath: /dev/termination-log +
-        terminationMessagePolicy: File +
-...+
 </code> </code>
  
-===La Commande rollout===+====1.4 - Création d'un Utilisateur====
  
-Vérifiez le statut du rollout :+Les utilisateurs font partis du contexte de configuration qui définit le nom du cluster et le nom du Namespace :
  
 <code> <code>
-root@debian10:~# kubectl rollout status deployment nginx +root@kubemaster:~# kubectl config get-contexts 
-deployment "nginx" successfully rolled out+CURRENT   NAME                          CLUSTER      AUTHINFO           NAMESPACE 
 +*         kubernetes-admin@kubernetes   kubernetes   kubernetes-admin
 </code> </code>
  
-Faites un roll back :+<WRAP center round important> 
 +**Important** Un contexte est un élément qui regroupe les paramètres d'accès sous un nom. Les paramètres d'accès sont au nombre de trois, à savoir le cluster, le namespace et l'utilisateur. La commande kubectl utilise les paramètres du contexte courant pour communiquer avec le cluster. 
 +</WRAP>
  
-<code> +En regardant le contexte courant, on voit que l'utilisateur **kubernetes-admin@kubernetes** a deux attributs dénommés :
-root@debian10:~# kubectl rollout undo deployment nginx +
-deployment.apps/nginx rolled back +
-</code>+
  
-Vérifiez maintenant le statut du deployment avec la commande **describe** :+  client-certificate-data: REDACTED 
 +  client-key-dataREDACTED
  
 <code> <code>
-root@debian10:~# kubectl describe deployment nginx +root@kubemaster:~# kubectl config view 
-Name                  nginx +apiVersionv1 
-Namespace             default +clusters
-CreationTimestamp     Fri, 11 Dec 2020 15:54:24 +0100 +- cluster: 
-Labels                app=nginx +    certificate-authority-dataDATA+OMITTED 
-Annotations           deployment.kubernetes.io/revision3 +    serverhttps://192.168.56.2:6443 
-Selector:               app=nginx +  namekubernetes 
-Replicas:               3 desired | 3 updated | 3 total | 3 available | 0 unavailable +contexts
-StrategyType:           RollingUpdate +- context
-MinReadySeconds:        0 +    clusterkubernetes 
-RollingUpdateStrategy:  25% max unavailable, 25% max surge +    userkubernetes-admin 
-Pod Template+  namekubernetes-admin@kubernetes 
-  Labels app=nginx +current-contextkubernetes-admin@kubernetes 
-  Containers: +kindConfig 
-   nginx+preferences{} 
-    Image       nginx +users
-    Port        <none> +name: kubernetes-admin 
-    Host Port   <none> +  user: 
-    Environment <none> +    client-certificate-dataREDACTED 
-    Mounts      <none> +    client-key-data: REDACTED
-  Volumes       <none> +
-Conditions+
-  Type           Status  Reason +
-  ----           ------  ------ +
-  Available      True    MinimumReplicasAvailable +
-  Progressing    True    NewReplicaSetAvailable +
-OldReplicaSets:  <none> +
-NewReplicaSet:   nginx-6799fc88d8 (3/3 replicas created) +
-Events+
-  Type    Reason             Age                 From                   Message +
-  ----    ------             ----                ----                   ------- +
-  Normal  ScalingReplicaSet  56m                 deployment-controller  Scaled up replica set nginx-6d5fb79b7f to 1 +
-  Normal  ScalingReplicaSet  56m                 deployment-controller  Scaled down replica set nginx-6799fc88d8 to 2 +
-  Normal  ScalingReplicaSet  56m                 deployment-controller  Scaled up replica set nginx-6d5fb79b7f to 2 +
-  Normal  ScalingReplicaSet  56m                 deployment-controller  Scaled up replica set nginx-6d5fb79b7f to 3 +
-  Normal  ScalingReplicaSet  56m                 deployment-controller  Scaled down replica set nginx-6799fc88d8 to 1 +
-  Normal  ScalingReplicaSet  56m                 deployment-controller  Scaled down replica set nginx-6799fc88d8 to 0 +
-  Normal  ScalingReplicaSet  7m9s (x2 over 70m)  deployment-controller  Scaled up replica set nginx-6799fc88d8 to 1 +
-  Normal  ScalingReplicaSet  7m6s                deployment-controller  Scaled down replica set nginx-6d5fb79b7f to 2 +
-  Normal  ScalingReplicaSet  7m6s                deployment-controller  Scaled up replica set nginx-6799fc88d8 to 2 +
-  Normal  ScalingReplicaSet  7m3s (x2 over 63m)  deployment-controller  Scaled up replica set nginx-6799fc88d8 to 3 +
-  Normal  ScalingReplicaSet  7m3s                deployment-controller  Scaled down replica set nginx-6d5fb79b7f to 1 +
-  Normal  ScalingReplicaSet  7m                  deployment-controller  Scaled down replica set nginx-6d5fb79b7f to 0+
 </code> </code>
  
-<WRAP center round important 40%+<WRAP center round important> 
-**Important** : Notez la ligne **Image:        nginx**.+**Important** : Le mot **REDACTED** indique que les valeurs sont cachées pour des raisons de sécurité.
 </WRAP> </WRAP>
  
-Consultez l'historique des révisions :+Pour créer un nouveau utilisateur il faut commencer par créer une clef privée pour l'utilisateur :
  
 <code> <code>
-root@debian10:~# kubectl rollout history deployment nginx +root@kubemaster:~# openssl genrsa -out trainee.key 2048 
-deployment.apps/nginx  +Generating RSA private key, 2048 bit long modulus 
-REVISION  CHANGE-CAUSE +....................................+++ 
-2         kubectl set image deployment nginx nginx=nginx:1.19.0 --record=true +..............+++ 
-3         <none>+e is 65537 (0x10001)
 </code> </code>
  
-Revenez à la révision numéro **2** :+Créez maintenant un CSR :
  
 <code> <code>
-root@debian10:~# kubectl rollout undo deployment nginx --to-revision=2 +root@kubemaster:~# openssl req -new -key trainee.key -out trainee.csr -subj "/CN=trainee/O=examplegroup"
-deployment.apps/nginx rolled back +
-root@debian10:~# kubectl describe deployment nginx +
-Name:                   nginx +
-Namespace:              default +
-CreationTimestamp:      Fri, 11 Dec 2020 15:54:24 +0100 +
-Labels:                 app=nginx +
-Annotations:            deployment.kubernetes.io/revision: 4 +
-                        kubernetes.io/change-cause: kubectl set image deployment nginx nginx=nginx:1.19.0 --record=true +
-Selector:               app=nginx +
-Replicas:               3 desired | 3 updated | 3 total | 3 available | 0 unavailable +
-StrategyType:           RollingUpdate +
-MinReadySeconds:        0 +
-RollingUpdateStrategy:  25% max unavailable, 25% max surge +
-Pod Template: +
-  Labels:  app=nginx +
-  Containers: +
-   nginx: +
-    Image:        nginx:1.19.0 +
-    Port:         <none> +
-    Host Port:    <none> +
-    Environment:  <none> +
-    Mounts:       <none> +
-  Volumes:        <none> +
-Conditions: +
-  Type           Status  Reason +
-  ----           ------  ------ +
-  Available      True    MinimumReplicasAvailable +
-  Progressing    True    NewReplicaSetAvailable +
-OldReplicaSets:  <none> +
-NewReplicaSet:   nginx-6d5fb79b7f (3/3 replicas created) +
-Events: +
-  Type    Reason             Age                From                   Message +
-  ----    ------             ----               ----                   ------- +
-  Normal  ScalingReplicaSet  15m (x2 over 78m)  deployment-controller  Scaled up replica set nginx-6799fc88d8 to 1 +
-  Normal  ScalingReplicaSet  14m                deployment-controller  Scaled down replica set nginx-6d5fb79b7f to 2 +
-  Normal  ScalingReplicaSet  14m                deployment-controller  Scaled up replica set nginx-6799fc88d8 to 2 +
-  Normal  ScalingReplicaSet  14m (x2 over 71m)  deployment-controller  Scaled up replica set nginx-6799fc88d8 to 3 +
-  Normal  ScalingReplicaSet  14m                deployment-controller  Scaled down replica set nginx-6d5fb79b7f to 1 +
-  Normal  ScalingReplicaSet  14m                deployment-controller  Scaled down replica set nginx-6d5fb79b7f to 0 +
-  Normal  ScalingReplicaSet  19s (x2 over 64m)  deployment-controller  Scaled up replica set nginx-6d5fb79b7f to 1 +
-  Normal  ScalingReplicaSet  16s (x2 over 64m)  deployment-controller  Scaled down replica set nginx-6799fc88d8 to 2 +
-  Normal  ScalingReplicaSet  16s (x2 over 64m)  deployment-controller  Scaled up replica set nginx-6d5fb79b7f to 2 +
-  Normal  ScalingReplicaSet  14s (x2 over 64m)  deployment-controller  Scaled down replica set nginx-6799fc88d8 to 1 +
-  Normal  ScalingReplicaSet  13s (x2 over 64m)  deployment-controller  Scaled up replica set nginx-6d5fb79b7f to 3 +
-  Normal  ScalingReplicaSet  11s (x2 over 64m)  deployment-controller  Scaled down replica set nginx-6799fc88d8 to 0+
 </code> </code>
  
-<WRAP center round important 40%+<WRAP center round important> 
-**Important** : Notez la ligne **Image:        nginx:1.19.0**.+**Important** : Notez que Kubernetes utilisera la valeur de la clef de l'organisation pour le regroupement des utilisateurs.
 </WRAP> </WRAP>
  
-===La Commande delete=== +Le CSR doit être signé par le CA racine de Kubernetes :
- +
-Supprimez maintenant le deployment nginx :+
  
 <code> <code>
-root@debian10:~# kubectl delete deployment nginx +root@kubemaster:~# ls -l /etc/kubernetes/pki/ca.* 
-deployment.apps "nginx" deleted +-rw-r--r-- 1 root root 1099 juil. 12 13:23 /etc/kubernetes/pki/ca.crt 
-root@debian10:~# kubectl get deployments +-rw------- 1 root root 1679 juil. 12 13:23 /etc/kubernetes/pki/ca.key
-No resources found in default namespace.+
 </code> </code>
  
-====1.6 - Déboguer une Application==== +Signez donc le CSR :
- +
-Vous venez de supprimer le deployment **nginx**. Créez donc un autre deployement basé sur l'image **bitnami/postgresql**. Commencez par créer le fichier **deployment-postgresql.yaml** :+
  
 <code> <code>
-root@debian10:~# vi deployment-postgresql.yaml +root@kubemaster:~# openssl x509 -req -in trainee.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out trainee.crt 
-root@debian10:~# cat deployment-postgresql.yaml +Signature ok 
-apiVersion: apps/v1 +subject=/CN=trainee/O=examplegroup 
-kind: Deployment +Getting CA Private Key
-metadata: +
-  name: postgresql +
-  labels: +
-    app: postgresql +
-spec: +
-  replicas: 1 +
-  selector: +
-    matchLabels: +
-      app: postgresql +
-  template: +
-    metadata: +
-      labels: +
-        app: postgresql +
-    spec: +
-      containers: +
-      image: bitnami/postgresql:10.12.10 +
-        imagePullPolicy: IfNotPresent +
-        name: postgresql+
 </code> </code>
  
-Deployez ensuite l'application :+Visualisez le certificat de trainee :
  
 <code> <code>
-oot@debian10:~# kubectl apply -f deployment-postgresql.yaml +root@kubemaster:~# openssl x509 -in trainee.crt -text 
-deployment.apps/postgresql created+Certificate: 
 +    Data: 
 +        Version: 1 (0x0) 
 +        Serial Number: 
 +            b6:f7:59:8f:75:19:bc:10 
 +    Signature Algorithm: sha256WithRSAEncryption 
 +        Issuer: CN = kubernetes 
 +        Validity 
 +            Not Before: Jul 14 07:49:14 2022 GMT 
 +            Not After : Aug 13 07:49:14 2022 GMT 
 +        Subject: CN = trainee, O = examplegroup 
 +        Subject Public Key Info: 
 +            Public Key Algorithm: rsaEncryption 
 +                Public-Key: (2048 bit) 
 +                Modulus: 
 +                    00:9b:2d:e8:7d:ba:e9:9f:b3:da:8f:14:13:21:83: 
 +                    64:c6:6e:7b:2c:ee:4f:e6:71:65:a7:e4:ca:6a:23: 
 +                    ee:cf:e1:43:18:e0:b0:1f:ef:ff:53:21:de:d2:e8: 
 +                    38:d1:39:ab:b0:8d:78:f4:af:7c:80:b0:1a:c3:a2: 
 +                    cb:64:b4:73:e6:a5:30:33:69:f1:6d:9a:5b:66:2e: 
 +                    58:f6:c2:51:7c:42:95:16:ac:60:0e:1d:4d:09:aa: 
 +                    06:29:51:79:f1:45:70:48:b9:1c:e2:05:fc:5c:33: 
 +                    82:d7:82:5f:a2:31:13:b5:23:4c:10:bf:a5:8a:4f: 
 +                    37:2a:d6:cc:ac:c7:c0:ad:97:71:95:9e:26:4f:60: 
 +                    b5:41:8a:7b:c5:79:38:02:28:b0:88:84:23:0b:18: 
 +                    d2:c2:f9:9f:ff:ec:ec:fb:0a:41:d7:7d:f3:90:2f: 
 +                    29:08:86:1e:e7:cb:ab:cf:56:5e:a9:ba:06:d8:83: 
 +                    c2:3c:1d:38:cc:fa:fd:69:17:4e:c3:7e:79:dd:34: 
 +                    11:9a:ff:5d:32:e4:68:a8:0f:cc:4c:bf:27:bc:2e: 
 +                    19:b7:9d:ad:68:45:d9:87:06:74:9f:e4:ad:bf:df: 
 +                    06:c8:28:c7:a4:78:f2:31:b2:6c:c7:9e:90:b8:bf: 
 +                    48:d4:ae:fd:65:e9:38:fd:8f:30:41:e9:32:f5:de: 
 +                    69:69 
 +                Exponent: 65537 (0x10001) 
 +    Signature Algorithm: sha256WithRSAEncryption 
 +         6d:c8:0d:cd:7c:34:5c:08:67:98:b6:ae:80:26:e8:73:f1:14: 
 +         3b:02:09:dd:b4:6d:f1:7f:bb:12:8a:16:86:d6:d6:be:ad:92: 
 +         99:a8:23:a1:d7:de:d4:e9:03:ec:6f:b9:19:46:2d:d8:f4:30: 
 +         71:8c:f0:6e:43:ad:d8:10:46:15:ab:9f:46:c1:56:4c:6c:81: 
 +         ab:ba:dd:5b:78:6a:57:82:d3:1a:d7:1a:5f:63:ca:4e:0f:fb: 
 +         ce:fe:f1:a5:78:64:a5:03:41:ad:c5:b7:28:45:62:31:ce:02: 
 +         09:1b:73:1d:e0:96:a4:1b:c4:09:18:a6:b1:5e:8c:88:03:75: 
 +         92:64:47:d3:0c:ce:87:91:9c:25:f7:72:a7:44:9d:36:41:87: 
 +         48:61:71:31:9a:24:ae:36:4f:40:c8:f3:08:32:f5:b1:9d:f5: 
 +         8a:0a:71:80:e6:70:d9:af:e1:96:55:81:9f:a1:95:39:53:b5: 
 +         1b:f3:37:3e:50:d5:a1:6b:d1:4b:d1:c6:75:fb:63:f0:63:06: 
 +         ce:99:fb:c3:15:c1:51:3b:ed:d9:c8:68:43:66:3c:ef:92:ba: 
 +         ae:a5:0d:02:48:8d:42:1a:70:22:13:75:47:ad:69:d5:48:11: 
 +         6b:b1:24:80:7e:d6:0d:f7:92:0c:bb:28:91:6e:d4:4c:a1:14: 
 +         c9:2d:47:2c 
 +-----BEGIN CERTIFICATE----- 
 +MIICujCCAaICCQC291mPdRm8EDANBgkqhkiG9w0BAQsFADAVMRMwEQYDVQQDEwpr 
 +dWJlcm5ldGVzMB4XDTIyMDcxNDA3NDkxNFoXDTIyMDgxMzA3NDkxNFowKTEQMA4G 
 +A1UEAwwHdHJhaW5lZTEVMBMGA1UECgwMZXhhbXBsZWdyb3VwMIIBIjANBgkqhkiG 
 +9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmy3ofbrpn7PajxQTIYNkxm57LO5P5nFlp+TK 
 +aiPuz+FDGOCwH+//UyHe0ug40TmrsI149K98gLAaw6LLZLRz5qUwM2nxbZpbZi5Y 
 +9sJRfEKVFqxgDh1NCaoGKVF58UVwSLkc4gX8XDOC14JfojETtSNMEL+lik83KtbM 
 +rMfArZdxlZ4mT2C1QYp7xXk4AiiwiIQjCxjSwvmf/+zs+wpB133zkC8pCIYe58ur 
 +z1ZeqboG2IPCPB04zPr9aRdOw3553TQRmv9dMuRoqA/MTL8nvC4Zt52taEXZhwZ0 
 +n+Stv98GyCjHpHjyMbJsx56QuL9I1K79Zek4/Y8wQeky9d5paQIDAQABMA0GCSqG 
 +SIb3DQEBCwUAA4IBAQBtyA3NfDRcCGeYtq6AJuhz8RQ7AgndtG3xf7sSihaG1ta+ 
 +rZKZqCOh197U6QPsb7kZRi3Y9DBxjPBuQ63YEEYVq59GwVZMbIGrut1beGpXgtMa 
 +1xpfY8pOD/vO/vGleGSlA0GtxbcoRWIxzgIJG3Md4JakG8QJGKaxXoyIA3WSZEfT 
 +DM6HkZwl93KnRJ02QYdIYXExmiSuNk9AyPMIMvWxnfWKCnGA5nDZr+GWVYGfoZU5 
 +U7Ub8zc+UNWha9FL0cZ1+2PwYwbOmfvDFcFRO+3ZyGhDZjzvkrqupQ0CSI1CGnAi 
 +E3VHrWnVSBFrsSSAftYN95IMuyiRbtRMoRTJLUcs 
 +-----END CERTIFICATE-----
 </code> </code>
  
-En consultant le pod créé, vous verrez qu'il y a une erreur de type **ErrImagePull** :+Créez un deuxième utilisateur dans la même Organisation :
  
 <code> <code>
-root@debian10:~# kubectl get pods +root@kubemaster:~# openssl genrsa -out stagiaire.key 2048 
-NAME                          READY   STATUS         RESTARTS   AGE +Generating RSA private key, 2048 bit long modulus 
-postgresql-586d47479b-kf24b   0/    ErrImagePull            40s +................................................................................................................................+++ 
-</code>+.................+++ 
 +e is 65537 (0x10001)
  
-Consultez la section **Events** de la sortie de la commande **describe** pour voir ce que se passe :+root@kubemaster:~# openssl req -new -key stagiaire.key -out stagiaire.csr -subj "/CN=stagiaire/O=examplegroup"
  
-<code> +root@kubemaster:~# openssl x509 -req -in stagiaire.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out stagiaire.crt 
-root@debian10:~# kubectl describe pod postgresql-586d47479b-kf24b +Signature ok 
-... +subject=/CN=stagiaire/O=examplegroup 
-Events: +Getting CA Private Key
-  Type     Reason     Age                From               Message +
-  ----     ------     ----               ----               ------- +
-  Normal   Scheduled  81s                default-scheduler  Successfully assigned default/postgresql-586d47479b-kf24b to kind-worker2 +
-  Normal   Pulling    35s (x3 over 81s)  kubelet            Pulling image "bitnami/postgresql:10.12.10" +
-  Warning  Failed     33s (x3 over 79s)  kubelet            Failed to pull image "bitnami/postgresql:10.12.10": rpc error: code = NotFound desc = failed to pull and unpack image "docker.io/bitnami/postgresql:10.12.10": failed to resolve reference "docker.io/bitnami/postgresql:10.12.10": docker.io/bitnami/postgresql:10.12.10: not found +
-  Warning  Failed     33s (x3 over 79s)  kubelet            Error: ErrImagePull +
-  Normal   BackOff    6s (x4 over 78s)   kubelet            Back-off pulling image "bitnami/postgresql:10.12.10" +
-  Warning  Failed     6s (x4 over 78s)   kubelet            Error: ImagePullBackOff+
 </code> </code>
  
-Comme vous pouvez constater, il existe trois avertissements +Créez maintenant le contexte **trainee** :
- +
-<file> +
-  Warning  Failed     33s (x3 over 79s)  kubelet            Failed to pull image "bitnami/postgresql:10.12.10": rpc error: code = NotFound desc = failed to pull and unpack image "docker.io/bitnami/postgresql:10.12.10": failed to resolve reference "docker.io/bitnami/postgresql:10.12.10": docker.io/bitnami/postgresql:10.12.10: not found +
-  Warning  Failed     33s (x3 over 79s)  kubelet            Error: ErrImagePull +
-  Normal   BackOff    6s (x4 over 78s)   kubelet            Back-off pulling image "bitnami/postgresql:10.12.10" +
-  Warning  Failed     6s (x4 over 78s)   kubelet            Error: ImagePullBackOff +
-</file> +
- +
-Le premier des trois avertissements nous dit clairement qu'il y a un problème au niveau du tag de l'image spécifié dans le fichier **deployment-postgresql.yaml** : **docker.io/bitnami/postgresql:10.12.10: not found**. +
- +
-Modifiez donc le tage dans ce fichier à ** 10.13.0** :+
  
 <code> <code>
-root@debian10:~# vi deployment-postgresql.yaml +root@kubemaster:~# kubectl config set-credentials trainee --client-certificate=trainee.crt --client-key=trainee.key 
-root@debian10:~# cat deployment-postgresql.yaml +User "trainee" set.
-apiVersion: apps/v1 +
-kind: Deployment +
-metadata: +
-  name: postgresql +
-  labels: +
-    app: postgresql +
-spec: +
-  replicas: 1 +
-  selector: +
-    matchLabels: +
-      app: postgresql +
-  template: +
-    metadata: +
-      labels: +
-        app: postgresql +
-    spec: +
-      containers: +
-      - image: bitnami/postgresql:10.13.0 +
-        imagePullPolicy: IfNotPresent +
-        name: postgresql +
-</code>+
  
-Appliquez maintenant le fichier : +root@kubemaster:~# kubectl config set-context trainee@kubernetes --cluster=kubernetes --user=trainee 
- +Context "trainee@kubernetes" created.
-<code> +
-root@debian10:~# kubectl apply -f deployment-postgresql.yaml +
-deployment.apps/postgresql configured+
 </code> </code>
  
-En consultant le deuxième Pod créé, vous verrez qu'il y a une erreur de type **CrashLoopBackOff** :+Vérifiez que le contexte soit présent :
  
 <code> <code>
-root@debian10:~# kubectl get pods +root@kubemaster:~# kubectl config get-contexts 
-NAME                          READY   STATUS              RESTARTS   AGE +CURRENT   NAME                          CLUSTER      AUTHINFO           NAMESPACE 
-postgresql-586d47479b-kf24b   0/    ImagePullBackOff    0          4m9s +*         kubernetes-admin@kubernetes   kubernetes   kubernetes-admin    
-postgresql-5cc57c477d-dr7nx   0/    ContainerCreating            29s +          trainee@kubernetes            kubernetes   trainee 
-root@debian10:~# kubectl get pods +
-NAME                          READY   STATUS             RESTARTS   AGE +
-postgresql-586d47479b-kf24b   0/1     ImagePullBackOff            4m13s +
-postgresql-5cc57c477d-dr7nx   0/    Error              1          33s +
-root@debian10:~# kubectl get pods +
-NAME                          READY   STATUS             RESTARTS   AGE +
-postgresql-586d47479b-kf24b   0/    ImagePullBackOff            4m15s +
-postgresql-5cc57c477d-dr7nx   0/    CrashLoopBackOff            35s+
 </code> </code>
  
-Consultez la section **Events** de la sortie de la commande **describe** pour voir ce que se passe avec le deuxième pod :+Utilisez le contexte de trainee :
  
 <code> <code>
-root@debian10:~# kubectl describe pod postgresql-5cc57c477d-dr7nx +root@kubemaster:~# kubectl config use-context trainee@kubernetes 
-... +Switched to context "trainee@kubernetes".
-Events: +
-  Type     Reason     Age                From               Message +
-  ----     ------     ----               ----               ------- +
-  Normal   Scheduled  89s                default-scheduler  Successfully assigned default/postgresql-5cc57c477d-dr7nx to kind-worker2 +
-  Normal   Pulling    89s                kubelet            Pulling image "bitnami/postgresql:10.13.0" +
-  Normal   Pulled     72s                kubelet            Successfully pulled image "bitnami/postgresql:10.13.0" in 16.7361756s +
-  Normal   Pulled     16s (x3 over 58s)  kubelet            Container image "bitnami/postgresql:10.13.0" already present on machine +
-  Normal   Created    15s (x4 over 60s)  kubelet            Created container postgresql +
-  Normal   Started    15s (x4 over 59s)  kubelet            Started container postgresql +
-  Warning  BackOff    1s (x6 over 57s)   kubelet            Back-off restarting failed container +
-</code>+
  
-Cette fois-ci, la section **Events** nous donne aucune indication concernant le problème ! +root@kubemaster:~# kubectl config get-contexts 
- +CURRENT   NAME                          CLUSTER      AUTHINFO           NAMESPACE 
-===La Commande logs=== +          kubernetes-admin@kubernetes   kubernetes   kubernetes-admin    
- +*         trainee@kubernetes            kubernetes   trainee   
-Pour obtenir plus d'information concernant le problème, on peut utiliser la commande **logs** : +           
- +root@kubemaster:~# kubectl get pods 
-<code> +Error from server (Forbidden)pods is forbiddenUser "trainee" cannot list resource "pods" in API group "" in the namespace "default"
-root@debian10:~# kubectl logs postgresql-5cc57c477d-dr7nx +
-postgresql 14:56:53.17  +
-postgresql 14:56:53.17 Welcome to the Bitnami postgresql container +
-postgresql 14:56:53.18 Subscribe to project updates by watching https://github.com/bitnami/bitnami-docker-postgresql +
-postgresql 14:56:53.18 Submit issues and feature requests at https://github.com/bitnami/bitnami-docker-postgresql/issues +
-postgresql 14:56:53.18  +
-postgresql 14:56:53.21 INFO  ==> ** Starting PostgreSQL setup ** +
-postgresql 14:56:53.23 INFO  ==> Validating settings in POSTGRESQL_* env vars.. +
-postgresql 14:56:53.23 ERROR ==> The POSTGRESQL_PASSWORD environment variable is empty or not set. Set the environment variable ALLOW_EMPTY_PASSWORD=yes to allow the container to be started with blank passwords. This is recommended only for development. +
-postgresql 14:56:53.23 ERROR ==> The POSTGRESQL_PASSWORD environment variable is empty or not set. Set the environment variable ALLOW_EMPTY_PASSWORD=yes to allow the container to be started with blank passwords. This is recommended only for development.+
 </code> </code>
  
-La sortie de la commande **logs** nous indique clairement que le problème est lié au contenu de la variable **POSTGRESQL_PASSWORD** qui est videElle nous indique aussi que nous pourrions fixer la valeur de la variable **ALLOW_EMPTY_PASSWORD** à **yes** pour contourner ce problème :+<WRAP center round important> 
 +**Important** : Notez que trainee ne peut pas lister les pods parce que les permissions RBAC n'ont pas été définies. 
 +</WRAP>
  
-<file> +Retournez au contexte de l'administrateur :
-... +
-postgresql 14:56:53.23 ERROR ==> The POSTGRESQL_PASSWORD environment variable is empty or not set. Set the environment variable ALLOW_EMPTY_PASSWORD=yes to allow the container to be started with blank passwords. This is recommended only for development. +
-</file> +
- +
-Mettez à jour donc le fichier **deployment-postgresql.yaml** :+
  
 <code> <code>
-root@debian10:~# vi deployment-postgresql.yaml +root@kubemaster:~# kubectl config use-context kubernetes-admin@kubernetes 
-root@debian10:~# cat deployment-postgresql.yaml +Switched to context "kubernetes-admin@kubernetes".
-apiVersion: apps/v1 +
-kind: Deployment +
-metadata: +
-  name: postgresql +
-  labels: +
-    app: postgresql +
-spec: +
-  replicas: 1 +
-  selector: +
-    matchLabels: +
-      app: postgresql +
-  template: +
-    metadata: +
-      labels: +
-        app: postgresql +
-    spec: +
-      containers: +
-      - image: bitnami/postgresql:10.13.0 +
-        imagePullPolicy: IfNotPresent +
-        name: postgresql +
-        env: +
-        - name: POSTGRESQL_PASSWORD +
-          value: "VerySecurePassword:-)" +
-</code>+
  
-Appliquez la configuration : +root@kubemaster:~# kubectl config get-contexts 
- +CURRENT   NAME                          CLUSTER      AUTHINFO           NAMESPACE 
-<code> +*         kubernetes-admin@kubernetes   kubernetes   kubernetes-admin    
-root@debian10:~# kubectl apply -f deployment-postgresql.yaml +          trainee@kubernetes            kubernetes   trainee 
-deployment.apps/postgresql configured+
 </code> </code>
  
-Constatez l'état du Pod ainsi que le deployment :+Créez maintenant un **clusterrolebinding** au groupe **examplegroup** :
  
 <code> <code>
-root@debian10:~# kubectl get pods +root@kubemaster:~# kubectl create clusterrolebinding examplegroup-admin-binding --clusterrole=cluster-admin --group=examplegroup 
-NAME                          READY   STATUS    RESTARTS   AGE +clusterrolebinding.rbac.authorization.k8s.io/examplegroup-admin-binding created
-postgresql-6c99978556-kqkp4   1/    Running            28s +
- +
-root@debian10:~# kubectl get deployments +
-NAME         READY   UP-TO-DATE   AVAILABLE   AGE +
-postgresql   1/1                1           38s+
 </code> </code>
  
-Utilisez maintenant l'option **-f** de la commande logs pour voir les traces en continu :+Utilisez de nouveau le contexte de trainee :
  
 <code> <code>
-root@debian10:~# kubectl logs postgresql-6c99978556-kqkp4 -f +root@kubemaster:~# kubectl config use-context trainee@kubernetes 
-postgresql 14:58:48.79  +Switched to context "trainee@kubernetes".
-postgresql 14:58:48.79 Welcome to the Bitnami postgresql container +
-postgresql 14:58:48.79 Subscribe to project updates by watching https://github.com/bitnami/bitnami-docker-postgresql +
-postgresql 14:58:48.79 Submit issues and feature requests at https://github.com/bitnami/bitnami-docker-postgresql/issues +
-postgresql 14:58:48.79  +
-postgresql 14:58:48.81 INFO  ==> ** Starting PostgreSQL setup ** +
-postgresql 14:58:48.83 INFO  ==> Validating settings in POSTGRESQL_* env vars.. +
-postgresql 14:58:48.84 INFO  ==> Loading custom pre-init scripts... +
-postgresql 14:58:48.85 INFO  ==> Initializing PostgreSQL database... +
-postgresql 14:58:48.87 INFO  ==> pg_hba.conf file not detected. Generating it... +
-postgresql 14:58:48.87 INFO  ==> Generating local authentication configuration +
-postgresql 14:58:53.51 INFO  ==> Starting PostgreSQL in background... +
-postgresql 14:58:53.64 INFO  ==> Changing password of postgres +
-postgresql 14:58:53.66 INFO  ==> Configuring replication parameters +
-postgresql 14:58:53.69 INFO  ==> Configuring fsync +
-postgresql 14:58:53.70 INFO  ==> Loading custom scripts... +
-postgresql 14:58:53.71 INFO  ==> Enabling remote connections +
-postgresql 14:58:53.73 INFO  ==> Stopping PostgreSQL... +
-postgresql 14:58:54.74 INFO  ==> ** PostgreSQL setup finished! **+
  
-postgresql 14:58:54.78 INFO  ==> ** Starting PostgreSQL ** +root@kubemaster:~# kubectl config get-contexts 
-2020-12-12 14:58:54.819 GMT [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432 +CURRENT   NAME                          CLUSTER      AUTHINFO           NAMESPACE 
-2020-12-12 14:58:54.820 GMT [1] LOG:  listening on IPv6 address "::", port 5432 +          kubernetes-admin@kubernetes   kubernetes   kubernetes-admin    
-2020-12-12 14:58:54.829 GMT [1] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432" +*         trainee@kubernetes            kubernetes   trainee      
-2020-12-12 14:58:54.843 GMT [106] LOG:  database system was shut down at 2020-12-12 14:58:53 GMT +        
-2020-12-12 14:58:54.850 GMT [1] LOG:  database system is ready to accept connections +root@kubemaster:~# kubectl get pods -n kube-system 
-^C+NAME                                                READY   STATUS    RESTARTS       AGE 
 +calico-kube-controllers-6766647d54-v4hrm            1/1     Running                44h 
 +calico-node-5mrjl                                   1/    Running                41h 
 +calico-node-688lw                                   1/    Running                44h 
 +calico-node-j25xd                                   1/    Running                41h 
 +coredns-6d4b75cb6d-dw4ph                            1/1     Running                44h 
 +coredns-6d4b75cb6d-ms2jm                            1/1     Running                44h 
 +etcd-kubemaster.ittraining.loc                      1/1     Running   1 (44h ago)    44h 
 +kube-apiserver-kubemaster.ittraining.loc            1/1     Running   1 (44h ago)    44h 
 +kube-controller-manager-kubemaster.ittraining.loc   1/    Running   10 (75m ago)   44h 
 +kube-proxy-bwctz                                    1/1     Running                41h 
 +kube-proxy-j89vg                                    1/1     Running                41h 
 +kube-proxy-jx76x                                    1/1     Running                44h 
 +kube-scheduler-kubemaster.ittraining.loc            1/1     Running   11 (75m ago)   44h 
 +metrics-server-7cb867d5dc-g55k5                     1/    Running                28h
 </code> </code>
  
-<WRAP center round important 40%> +====1.5 - Certificats TLS====
-**Important** : Notez l'utilisation de **^C** pour arrêter la commande **kubectl logs postgresql-6c99978556-vcfmm -f**.  +
-</WRAP> +
- +
-===La Commande exec===+
  
-La commande **exec** peut être utilisée pour exécuter une commande à l'intérieur d'un conteneur dans un pod. Imaginons que vous souhaitez vérifier le contenu du fichier de configuration de PostgreSQL, **postgresql.conf** :+Par défaut la communication entre kubectl et l'API Kubernetes est cryptée. Les certificats se trouvent dans le répertoire **/var/lib/kubelet/pki/** de chaque noeud :
  
 <code> <code>
-root@debian10:~# kubectl exec postgresql-6c99978556-vcfmm -- cat /opt/bitnami/postgresql/conf/postgresql.conf | more +root@kubemaster:~# ls -/var/lib/kubelet/pki
-root@debian10:~# kubectl logs postgresql-6c99978556-vcfmm -+total 12 
-postgresql 14:58:48.79  +-rw------- 1 root root 2851 juil. 12 13:23 kubelet-client-2022-07-12-13-23-12.pem 
-postgresql 14:58:48.79 Welcome to the Bitnami postgresql container +lrwxrwxrwx 1 root root   59 juil. 12 13:23 kubelet-client-current.pem -/var/lib/kubelet/pki/kubelet-client-2022-07-12-13-23-12.pem 
-postgresql 14:58:48.79 Subscribe to project updates by watching https://github.com/bitnami/bitnami-docker-postgresql +-rw-r--r-- 1 root root 2367 juil. 12 13:23 kubelet.crt 
-postgresql 14:58:48.79 Submit issues and feature requests at https://github.com/bitnami/bitnami-docker-postgresql/issues +-rw------- 1 root root 1675 juil12 13:23 kubelet.key
-postgresql 14:58:48.79  +
-postgresql 14:58:48.81 INFO  ==> ** Starting PostgreSQL setup ** +
-postgresql 14:58:48.83 INFO  ==> Validating settings in POSTGRESQL_* env vars.. +
-postgresql 14:58:48.84 INFO  ==> Loading custom pre-init scripts... +
-postgresql 14:58:48.85 INFO  ==> Initializing PostgreSQL database... +
-postgresql 14:58:48.87 INFO  ==> pg_hba.conf file not detected. Generating it... +
-postgresql 14:58:48.87 INFO  ==> Generating local authentication configuration +
-postgresql 14:58:53.51 INFO  ==> Starting PostgreSQL in background... +
-postgresql 14:58:53.64 INFO  ==> Changing password of postgres +
-postgresql 14:58:53.66 INFO  ==> Configuring replication parameters +
-postgresql 14:58:53.69 INFO  ==> Configuring fsync +
-postgresql 14:58:53.70 INFO  ==> Loading custom scripts... +
-postgresql 14:58:53.71 INFO  ==> Enabling remote connections +
-postgresql 14:58:53.73 INFO  ==> Stopping PostgreSQL... +
-postgresql 14:58:54.74 INFO  ==> ** PostgreSQL setup finished! ** +
- +
-postgresql 14:58:54.78 INFO  ==> ** Starting PostgreSQL ** +
-2020-12-12 14:58:54.819 GMT [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432 +
-2020-12-12 14:58:54.820 GMT [1] LOG:  listening on IPv6 address "::", port 5432 +
-2020-12-12 14:58:54.829 GMT [1] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432" +
-2020-12-12 14:58:54.843 GMT [106] LOG:  database system was shut down at 2020-12-12 14:58:53 GMT +
-2020-12-12 14:58:54.850 GMT [1] LOG:  database system is ready to accept connections +
-^C +
-root@debian10:~# kubectl exec postgresql-6c99978556-vcfmm -- cat /opt/bitnami/postgresql/conf/postgresql.conf | more +
-# ----------------------------- +
-# PostgreSQL configuration file +
------------------------------ +
-+
-# This file consists of lines of the form: +
-+
-#   name = value +
-+
-# (The "=" is optional.)  Whitespace may be used Comments are introduced with +
-# "#" anywhere on a line.  The complete list of parameter names and allowed +
-# values can be found in the PostgreSQL documentation. +
-+
-# The commented-out settings shown in this file represent the default values. +
-# Re-commenting a setting is NOT sufficient to revert it to the default value; +
-# you need to reload the server. +
-+
-# This file is read on server startup and when the server receives a SIGHUP +
-# signal.  If you edit the file on a running system, you have to SIGHUP the +
-# server for the changes to take effect, run "pg_ctl reload", or execute +
-# "SELECT pg_reload_conf()" Some parameters, which are marked below, +
-# require a server shutdown and restart to take effect. +
-+
-# Any parameter can also be given as a command-line option to the server, e.g., +
-# "postgres -c log_connections=on" Some parameters can be changed at run time +
-# with the "SET" SQL command. +
-+
-# Memory units:  kB = kilobytes        Time units:  ms  = milliseconds +
-#                MB = megabytes                       = seconds +
-#                GB = gigabytes                     min = minutes +
-#                TB = terabytes                       = hours +
-#                                                     = days +
- +
- +
-#------------------------------------------------------------------------------ +
-# FILE LOCATIONS +
-#------------------------------------------------------------------------------ +
- +
-# The default values of these variables are driven from the -D command-line +
-# option or PGDATA environment variable, represented here as ConfigDir. +
- +
-#data_directory = 'ConfigDir'           # use data in another directory +
-                                        # (change requires restart) +
---More--+
 </code> </code>
  
-La commande **exec** peut aussi être utilisé pour lancer **bash** en mode interactif :+<WRAP center round important> 
 +**Important** : Par défaut les certificats de kubelet expirent au bout d'un an. 
 +</WRAP>
  
-<code> +=====LAB #Implémentation de la Sécurité au niveau des Pods=====
-root@debian10:~kubectl exec -it postgresql-6c99978556-vcfmm -- bash +
-I have no name!@postgresql-6c99978556-vcfmm:/$ ls +
-bin  bitnami  boot  dev  docker-entrypoint-initdb.d  docker-entrypoint-preinitdb.d  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var +
-I have no name!@postgresql-6c99978556-vcfmm:/$ exit +
-exit +
-root@debian10:~#  +
-</code>+
  
-====1.Gérer les Plugins de kubectl====+==== 2.Présentation ====
  
-Les plugins de kubectl étendent ses fonctionnalités. Le gestionnaire des plugins **krew** est disponible pour macOS(tm), Windows(tm) et LinuxUn plugin est un simple exécutable écrit, par exemple, en **bash** ou en **Go**. +Un **Admission Controller** est un morceau de code qui intercepte les requêtes à destination de l'API de KubernetesL'utilisation des Admission Controllers est définie part la directive **--admission-control** du fichier **/etc/kubernetes/manifests/kube-apiserver.yaml**, par exemple :
- +
-===La Commande krew=== +
- +
-Afin d'installer la commande **krew**, il faut d'abord installer **git** : +
- +
-<code> +
-root@debian10:~# apt install git-all +
-</code> +
- +
-Installez ensuite krew avec la commande suivante :+
  
 <file> <file>
-+--admission-control=Initializers, NamespaceLifecycle, LimitRanger, ServiceAccount, PersistentVolumeLabel, DefaultStorageClass, DefaultTolerationSeconds, NodeRestriction, ResourceQuota
-  set -x; cd "$(mktemp -d)" && +
-  curl -fsSLO "https://github.com/kubernetes-sigs/krew/releases/latest/download/krew.tar.gz" && +
-  tar zxvf krew.tar.gz && +
-  KREW=./krew-"$(uname | tr '[:upper:]' '[:lower:]')_$(uname -m | sed -e 's/x86_64/amd64/' -e 's/arm.*$/arm/')" && +
-  "$KREW" install krew +
-)+
 </file> </file>
  
-<code> +Les Admission Controllers les plus importants en termes de sécurité sont :
-root@debian10:~# ( +
->   set -x; cd "$(mktemp -d)" && +
->   curl -fsSLO "https://github.com/kubernetes-sigs/krew/releases/latest/download/krew.tar.gz" && +
->   tar zxvf krew.tar.gz && +
->   KREW=./krew-"$(uname | tr '[:upper:]' '[:lower:]')_$(uname -m | sed -e 's/x86_64/amd64/' -e 's/arm.*$/arm/')" && +
->   "$KREW" install krew +
-> ) +
-</code>+
  
-A la fin de l'installationvous verrez la sortie suivante :+  * **DenyEscalatingExec**, 
 +    * interdit l'exécution des commandes avec un //escalated container// dans un pod priviligié. Les commandes concernées sont **exec** et **attach**. Un //escalated container// dans un pod priviligié n'est pas **isolé** et permet donc l'accès à l'hôte. 
 +  * **NodeRestriction**, 
 +    * limite les objets d'un nœud et d'un pod que kubectl est capable de modifier, 
 +  * **PodSecurityPolicy**, 
 +    * agit lors de la création ou de la modification d'un pod pour décider si celui-ci est admis au cluster en fonction du Contexte de Sécurité et les policies applicables, 
 +  * **ValidatingAdmissionWebhooks**, 
 +    * permet d'appeler un service externe qui implémente une politique de sécurité, tel que **[[https://grafeas.io/|Grafeas]]**.
  
-<code> +====2.Kubernetes Security Context====
-... +
-Installing plugin: krew +
-Installed plugin: krew +
-+
- | Use this plugin: +
-      kubectl krew +
- | Documentation: +
-      https://krew.sigs.k8s.io/ +
- | Caveats: +
- | \ +
-  | krew is now installed! To start using kubectl plugins, you need to add +
-  | krew's installation directory to your PATH: +
-  |  +
-  |   * macOS/Linux: +
-  |     Add the following to your ~/.bashrc or ~/.zshrc: +
-  |         export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH" +
-  |     - Restart your shell. +
-  |  +
-  |   * Windows: Add %USERPROFILE%\.krew\bin to your PATH environment variable +
-  |  +
-  | To list krew commands and to get help, run: +
-  |   $ kubectl krew +
-  | For a full list of available plugins, run: +
-  |   $ kubectl krew search +
-  |  +
-  | You can find documentation at +
-  |   https://krew.sigs.k8s.io/docs/user-guide/quickstart/+
- | / +
-+
-</code>+
  
-Ensuite ajoutez **$HOME/.krew/bin** à votre PATH :+La configuration du Contexte de Sécurité se fait du pod ou du conteneur. Voici quelques exemples.
  
-<code> +===ReadOnlyRootFilesystem===
-root@debian10:~# export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH" +
-</code>+
  
-Afin de ne pas avoir besoin de redéfinir le PATH après chaque ouverture de session, ajoutez la ligne à la fin du fichier **.bashrc** :+Créez le fichier **readonly.yaml** :
  
 <code> <code>
-root@debian10:~# echo 'export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH"' >> .bashrc +root@kubemaster:~# vi readonly.yaml 
-root@debian10:~# tail .bashrc +root@kubemaster:~# cat readonly.yaml 
-# eval "`dircolors`" +apiVersion: v1 
-# alias ls='ls $LS_OPTIONS' +kind: Pod 
-# alias ll='ls $LS_OPTIONS -l' +metadata: 
-# alias l='ls $LS_OPTIONS -lA' +  name: flask-ro 
-# +  namespace: default 
-# Some more alias to avoid making mistakes+spec
-# alias rm='rm -i' +  containers: 
-# alias cp='cp -i' +  image: mateobur/flask 
-# alias mv='mv -i' +    name: flask-ro 
-export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH"+    securityContext: 
 +      readOnlyRootFilesystemtrue
 </code> </code>
  
-Mettez à jour la liste des plugins :+Exécutez kubectl :
  
 <code> <code>
-root@debian10:~# kubectl krew update +root@kubemaster:~# kubectl create -f readonly.yaml  
-Updated the local copy of plugin index.+pod/flask-ro created
 </code> </code>
  
-Pour visualiser la liste des plugins, utiisez la commande **search** :+Vérifiez que le pod est en état de **READY** :
  
 <code> <code>
-root@debian10:~# kubectl krew search +root@kubemaster:~# kubectl get pods 
-NAME                            DESCRIPTION                                         INSTALLED +NAME                                     READY   STATUS    RESTARTS   AGE 
-access-matrix                   Show an RBAC access matrix for server resources     no +flask-ro                                 1/    Running            13m 
-advise-psp                      Suggests PodSecurityPolicies for cluster.           no +postgres-deployment-5b8bd66778-j99zz     1/1     Running            4d1h 
-allctx                          Run commands on contexts in your kubeconfig         no +redis-deployment-67d4c466c4-9wzfn        1/1     Running            4d1h 
-apparmor-manager                Manage AppArmor profiles for cluster.               no +result-app-deployment-b8f9dc967-nzbgd    1/1     Running   7          4d1h 
-auth-proxy                      Authentication proxy to a pod or service            no +result-app-deployment-b8f9dc967-r84k6    1/1     Running   7          3d22h 
-bd-xray                         Run Black Duck Image Scans                          no +result-app-deployment-b8f9dc967-zbsk2    1/1     Running            3d22h 
-bulk-action                     Do bulk actions on Kubernetes resources.            no +voting-app-deployment-669dccccfb-jpn6h   1/    Running   7          4d1h 
-ca-cert                         Print the PEM CA certificate of the current clu...  no +voting-app-deployment-669dccccfb-ktd7d   1/1     Running   7          3d22h 
-capture                         Triggers a Sysdig capture to troubleshoot the r...  no +voting-app-deployment-669dccccfb-x868p   1/    Running            3d22h 
-cert-manager                    Manage cert-manager resources inside your cluster   no +worker-app-deployment-559f7749b6-jh86r   1/    Running   19         4d1h
-change-ns                       View or change the current namespace via kubectl.   no +
-cilium                          Easily interact with Cilium agents.                 no +
-cluster-group                   Exec commands across a group of contexts.           no +
-config-cleanup                  Automatically clean up your kubeconfig              no +
-config-registry                 Switch between registered kubeconfigs               no +
-creyaml                         Generate custom resource YAML manifest              no +
-cssh                            SSH into Kubernetes nodes                           no +
-ctx                             Switch between contexts in your kubeconfig          no +
-custom-cols                     A "kubectl get" replacement with customizable c...  no +
-datadog                         Manage the Datadog Operator                         no +
-debug                           Attach ephemeral debug container to running pod     no +
-debug-shell                     Create pod with interactive kube-shell.             no +
-deprecations                    Checks for deprecated objects in a cluster          no +
-df-pv                           Show disk usage (like unix df) for persistent v...  no +
-doctor                          Scans your cluster and reports anomalies.           no +
-duck                            List custom resources with ducktype support         no +
-edit-status                     Edit /status subresources of CRs                    no +
-eksporter                       Export resources and removes a pre-defined set ...  no +
-emit-event                      Emit Kubernetes Events for the requested object     no +
-evict-pod                       Evicts the given pod                                no +
-example                         Prints out example manifest YAMLs                   no +
-exec-as                         Like kubectl exec, but offers a `user` flag to ...  no +
-exec-cronjob                    Run a CronJob immediately as Job                    no +
-fields                          Grep resources hierarchy by field name              no +
-flame                           Generate CPU flame graphs from pods                 no +
-fleet                           Shows config and resources of a fleet of clusters   no +
-fuzzy                           Fuzzy and partial string search for kubectl         no +
-gadget                          Gadgets for debugging and introspecting apps        no +
-get-all                         Like `kubectl get all` but _really_ everything      no +
-gke-credentials                 Fetch credentials for GKE clusters                  no +
-gopass                          Imports secrets from gopass                         no +
-graph                           Visualize Kubernetes resources and relationships.   no +
-grep                            Filter Kubernetes resources by matching their n...  no +
-gs                              Handle custom resources with Giant Swarm            no +
-hns                             Manage hierarchical namespaces (part of HNC)        no +
-iexec                           Interactive selection tool for `kubectl exec`       no +
-images                          Show container images used in the cluster.          no +
-ingress-nginx                   Interact with ingress-nginx                         no +
-ipick                           A kubectl wrapper for interactive resource sele...  no +
-konfig                          Merge, split or import kubeconfig files             no +
-krew                            Package manager for kubectl plugins.                yes +
-kubesec-scan                    Scan Kubernetes resources with kubesec.io.          no +
-kudo                            Declaratively build, install, and run operators...  no +
-kuttl                           Declaratively run and test operators                no +
-kyverno                         Kyverno is a policy engine for kubernetes           no +
-match-name                      Match names of pods and other API objects           no +
-minio                           Deploy and manage MinIO Operator and Tenant(s)      no +
-modify-secret                   modify secret with implicit base64 translations     no +
-mtail                           Tail logs from multiple pods matching label sel...  no +
-neat                            Remove clutter from Kubernetes manifests to mak...  no +
-net-forward                     Proxy to arbitrary TCP services on a cluster ne...  no +
-node-admin                      List nodes and run privileged pod with chroot       no +
-node-restart                    Restart cluster nodes sequentially and gracefully   no +
-node-shell                      Spawn a root shell on a node via kubectl            no +
-np-viewer                       Network Policies rules viewer                       no +
-ns                              Switch between Kubernetes namespaces                no +
-oidc-login                      Log in to the OpenID Connect provider               no +
-open-svc                        Open the Kubernetes URL(s) for the specified se...  no +
-operator                        Manage operators with Operator Lifecycle Manager    no +
-oulogin                         Login to a cluster via OpenUnison                   no +
-outdated                        Finds outdated container images running in a cl...  no +
-passman                         Store kubeconfig credentials in keychains or pa...  no +
-pod-dive                        Shows a pod's workload tree and info inside a node  no +
-pod-logs                        Display a list of pods to get logs from             no +
-pod-shell                       Display a list of pods to execute a shell in        no +
-podevents                       Show events for pods                                no +
-popeye                          Scans your clusters for potential resource issues   no +
-preflight                       Executes application preflight tests in a cluster   no +
-profefe                         Gather and manage pprof profiles from running pods  no +
-prompt                          Prompts for user confirmation when executing co...  no +
-prune-unused                    Prune unused resources                              no +
-psp-util                        Manage Pod Security Policy(PSP) and the related...  no +
-rabbitmq                        Manage RabbitMQ clusters                            no +
-rbac-lookup                     Reverse lookup for RBAC                             no +
-rbac-view                       A tool to visualize your RBAC permissions.          no +
-reap                            Delete unused Kubernetes resources.                 no +
-resource-capacity               Provides an overview of resource requests, limi...  no +
-resource-snapshot               Prints a snapshot of nodes, pods and HPAs resou...  no +
-restart                         Restarts a pod with the given name                  no +
-rm-standalone-pods              Remove all pods without owner references            no +
-rolesum                         Summarize RBAC roles for subjects                   no +
-roll                            Rolling restart of all persistent pods in a nam...  no +
-schemahero                      Declarative database schema migrations via YAML     no +
-score                           Kubernetes static code analysis.                    no +
-service-tree                    Status for ingresses, services, and their backends  no +
-shovel                          Gather diagnostics for .NET Core applications       no +
-sick-pods                       Find and debug Pods that are "Not Ready"            no +
-snap                            Delete half of the pods in a namespace or cluster   no +
-sniff                           Start a remote packet capture on pods using tcp...  no +
-sort-manifests                  Sort manifest files in a proper order by Kind       no +
-split-yaml                      Split YAML output into one file per resource.       no +
-spy                             pod debugging tool for kubernetes clusters with...  no +
-sql                             Query the cluster via pseudo-SQL                    no +
-ssh-jump                        A kubectl plugin to SSH into Kubernetes nodes u...  no +
-sshd                            Run SSH server in a Pod                             no +
-ssm-secret                      Import/export secrets from/to AWS SSM param store   no +
-starboard                       Toolkit for finding risks in kubernetes resources   no +
-status                          Show status details of a given resource.            no +
-sudo                            Run Kubernetes commands impersonated as group s...  no +
-support-bundle                  Creates support bundles for off-cluster analysis    no +
-tail                            Stream logs from multiple pods and containers u...  no +
-tap                             Interactively proxy Kubernetes Services with ease   no +
-tmux-exec                       An exec multiplexer using Tmux                      no +
-topology                        Explore region topology for nodes or pods           no +
-trace                           bpftrace programs in a cluster                      no +
-tree                            Show a tree of object hierarchies through owner...  no +
-unused-volumes                  List unused PVCs                                    no +
-view-allocations                List allocations per resources, nodes, pods.        no +
-view-cert                       View certificate information stored in secrets      no +
-view-secret                     Decode Kubernetes secrets                           no +
-view-serviceaccount-kubeconfig  Show a kubeconfig setting to access the apiserv...  no +
-view-utilization                Shows cluster cpu and memory utilization            no +
-view-webhook                    Visualize your webhook configurations               no +
-virt                            Control KubeVirt virtual machines using virtctl     no +
-warp                            Sync and execute local files in Pod                 no +
-who-can                         Shows who has RBAC permissions to access Kubern...  no +
-whoami                          Show the subject that's currently authenticated...  no+
 </code> </code>
  
-Installez les plugins **ctx**, **ns**, **view-allocations** et **pod-logs** :+Connectez-vous au conteneur :
  
 <code> <code>
-root@debian10:~# kubectl krew install ctx ns view-allocations pod-logs +root@kubemaster:~# kubectl exec -it flask-ro bash 
-Updated the local copy of plugin index. +root@flask-ro:/#
-Installing plugin: ctx +
-Installed plugin: ctx +
-+
- | Use this plugin: +
-      kubectl ctx +
- | Documentation: +
-      https://github.com/ahmetb/kubectx +
- | Caveats: +
- | \ +
-  | If fzf is installed on your machine, you can interactively choose +
-  | between the entries using the arrow keys, or by fuzzy searching +
-  | as you type. +
-  | See https://github.com/ahmetb/kubectx for customization and details. +
- | / +
-+
-WARNING: You installed plugin "ctx" from the krew-index plugin repository. +
-   These plugins are not audited for security by the Krew maintainers. +
-   Run them at your own risk. +
-Installing plugin: ns +
-Installed plugin: ns +
-+
- | Use this plugin: +
-      kubectl ns +
- | Documentation: +
-      https://github.com/ahmetb/kubectx +
- | Caveats: +
- | \ +
-  | If fzf is installed on your machine, you can interactively choose +
-  | between the entries using the arrow keys, or by fuzzy searching +
-  | as you type. +
- | / +
-+
-WARNING: You installed plugin "ns" from the krew-index plugin repository. +
-   These plugins are not audited for security by the Krew maintainers. +
-   Run them at your own risk. +
-Installing plugin: view-allocations +
-Installed plugin: view-allocations +
-+
- | Use this plugin: +
-      kubectl view-allocations +
- | Documentation: +
-      https://github.com/davidB/kubectl-view-allocations +
-+
-WARNING: You installed plugin "view-allocations" from the krew-index plugin repository. +
-   These plugins are not audited for security by the Krew maintainers. +
-   Run them at your own risk. +
-Installing plugin: pod-logs +
-Installed plugin: pod-logs +
-+
- | Use this plugin: +
-      kubectl pod-logs +
- | Documentation: +
-      https://github.com/danisla/kubefunc +
-+
-WARNING: You installed plugin "pod-logs" from the krew-index plugin repository. +
-   These plugins are not audited for security by the Krew maintainers. +
-   Run them at your own risk.+
 </code> </code>
  
-Le plugin **ctx** permet de basculer entre les **contextes** facilement. Lister les contextes dans le cluster :+Notez que le système est en lecture seule :
  
 <code> <code>
-root@debian10:~kubectl ctx +root@flask-ro:/mount | grep "/ " 
-kind-kind +overlay on / type overlay (ro,relatime,lowerdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/72/fs:/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/71/fs:/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/70/fs:/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/69/fs,upperdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/73/fs,workdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/73/work)
-</code>+
  
-<WRAP center round tip 40%> +root@flask-ro:/# touch test 
-Un contexte est un élément qui regroupe les paramètres d'accès sous un nom. Les paramètres d'accès sont au nombre de trois, à savoir le cluster, le namespace et l'utilisateur. La commande kubectl utilise les paramètres du contexte courant pour communiquer avec le cluster. +touch: cannot touch 'test': Read-only file system
-</WRAP>+
  
-Le plugin **ns** permet de basculer entre les **namespaces** facilement. Lister les namespaces dans le cluster : +root@flask-ro:/exit 
- +exit 
-<code> +command terminated with exit code 1
-root@debian10:~kubectl ns +
-default +
-kube-node-lease +
-kube-public +
-kube-system +
-local-path-storage+
 </code> </code>
  
-<WRAP center round tip 40%> +===drop===
-Les Namespaces : +
-  * peuvent être considérées comme des clusters virtuels, +
-  * permettent l'isolation et la segmentation logique, +
-  * permettent le regroupement d'utilisateurs, de rôles et de ressources, +
-  * sont utilisés avec des applications, des clients, des projets ou des équipes. +
-</WRAP>+
  
-Le plugin **view-allocations** permet de visualiser les allocations de ressources telles le CPU, la mémoire, le stockage etc +Créez le fichier **drop.yaml** :
  
 <code> <code>
-root@debian10:~# kubectl view-allocations +root@kubemaster:~# vi drop.yaml 
- Resource                                           Requested  %Requested    Limit  %Limit  Allocatable    Free  +root@kubemaster:~# cat drop.yaml 
-  cpu                                                     1.1         35%   300.0m     10%          3.0     1.9  +apiVersion: v1 
-  ├─ kind-control-plane                                850.0m         85%   100.0m     10%          1.0  150.0m  +kind: Pod 
-  │  ├─ coredns-f9fd979d6-b87p7                        100.0m                  0.0                               +metadata: 
-  │  ├─ coredns-f9fd979d6-jwd68                        100.0m                  0.0                               +  name: flask-cap 
-  │  ├─ kindnet-vrqzw                                  100.0m               100.0m                               +  namespace: default 
-  │  ├─ kube-apiserver-kind-control-plane              250.0m                  0.0                               +spec: 
-  │  ├─ kube-controller-manager-kind-control-plane     200.0m                  0.0                               +  containers: 
-  │  └─ kube-scheduler-kind-control-plane              100.0m                  0.0                               +  - image: mateobur/flask 
-  ├─ kind-worker2                                      100.0m         10%   100.0m     10%          1.0  900.0m  +    name: flask-cap 
-  │  └─ kindnet-t8t9q                                  100.0m               100.0m                               +    securityContext: 
-  └─ kind-worker3                                      100.0m         10%   100.0m     10%          1.0  900.0m  +      capabilities: 
-     └─ kindnet-7jqqb                                  100.0m               100.0m                               +        drop: 
-  ephemeral-storage                                       0.0          0%      0.0      0%       55.7Gi  55.7Gi  +          - NET_RAW 
-  ├─ kind-control-plane                                   0.0          0%      0.0      0%       18.6Gi  18.6Gi  +          - CHOWN
-  ├─ kind-worker2                                         0.0          0%      0.0      0%       18.6Gi  18.6Gi  +
-  └─ kind-worker3                                         0.0          0%      0.0      0%       18.6Gi  18.6Gi  +
-  memory                                              290.0Mi          1%  490.0Mi      2%       23.4Gi  22.9Gi  +
-  ├─ kind-control-plane                               190.0Mi          2%  390.0Mi      5%        7.8Gi   7.4Gi  +
-  │  ├─ coredns-f9fd979d6-b87p7                        70.0Mi              170.0Mi                               +
-  │  ├─ coredns-f9fd979d6-jwd68                        70.0Mi              170.0Mi                               +
-  │  └─ kindnet-vrqzw                                  50.0Mi               50.0Mi                               +
-  ├─ kind-worker2                                      50.0Mi          1%   50.0Mi      1%        7.8Gi   7.7Gi  +
-  │  └─ kindnet-t8t9q                                  50.0Mi               50.0Mi                               +
-  └─ kind-worker3                                      50.0Mi          1%   50.0Mi      1%        7.8Gi   7.7Gi  +
-     └─ kindnet-7jqqb                                  50.0Mi               50.0Mi                               +
-  pods                                                    0.0          0%      0.0      0%        330.0   330.0  +
-  ├─ kind-control-plane                                   0.0          0%      0.0      0%        110.0   110.0  +
-  ├─ kind-worker2                                         0.0          0%      0.0      0%        110.0   110.0  +
-  └─ kind-worker3                                         0.0          0%      0.0      0%        110.0   110.0+
 </code> </code>
  
-Le plugin **pod-logs** vous fourni avec une liste de pods en cours d'exécution et vous demande d'en choisir une :+Exécutez kubectl :
  
 <code> <code>
-root@debian10:~# kubectl pod-logs +root@kubemaster:~# kubectl create -f drop.yaml 
-1)   postgresql-6c99978556-vcfmm                 default             Running +pod/flask-cap created
-2)   coredns-f9fd979d6-b87p7                     kube-system         Running +
-3)   coredns-f9fd979d6-jwd68                     kube-system         Running +
-4)   etcd-kind-control-plane                     kube-system         Running +
-5)   kindnet-7jqqb                               kube-system         Running +
-6)   kindnet-t8t9q                               kube-system         Running +
-7)   kindnet-vrqzw                               kube-system         Running +
-8)   kube-apiserver-kind-control-plane           kube-system         Running +
-9)   kube-controller-manager-kind-control-plane  kube-system         Running +
-10)  kube-proxy-5zpkb                            kube-system         Running +
-11)  kube-proxy-8pp5m                            kube-system         Running +
-12)  kube-proxy-ltx6c                            kube-system         Running +
-13)  kube-scheduler-kind-control-plane           kube-system         Running +
-14)  metrics-server-594b87569-28r4s              kube-system         Running +
-15)  local-path-provisioner-78776bfc44-5rzmk     local-path-storage  Running +
-Select a Pod:  +
 </code> </code>
  
-Choisissez le pod **postgresql**. Vous verrez la sortie de la commande logs :+Vérifiez que le pod est en état de **READY** :
  
 <code> <code>
-Select a Pod1 +root@kubemaster:~# kubectl get pods 
-postgresql 14:58:48.79  +NAME                                     READY   STATUS    RESTARTS   AGE 
-postgresql 14:58:48.79 Welcome to the Bitnami postgresql container +flask-cap                                1/1     Running            4m4s 
-postgresql 14:58:48.79 Subscribe to project updates by watching https://github.com/bitnami/bitnami-docker-postgresql +flask-ro                                 1/1     Running            13m 
-postgresql 14:58:48.79 Submit issues and feature requests at https://github.com/bitnami/bitnami-docker-postgresql/issues +postgres-deployment-5b8bd66778-j99zz     1/1     Running            4d1h 
-postgresql 14:58:48.79  +redis-deployment-67d4c466c4-9wzfn        1/1     Running            4d1h 
-postgresql 14:58:48.81 INFO  ==> ** Starting PostgreSQL setup ** +result-app-deployment-b8f9dc967-nzbgd    1/1     Running            4d1h 
-postgresql 14:58:48.83 INFO  ==> Validating settings in POSTGRESQL_* env vars.. +result-app-deployment-b8f9dc967-r84k6    1/1     Running            3d22h 
-postgresql 14:58:48.84 INFO  ==> Loading custom pre-init scripts... +result-app-deployment-b8f9dc967-zbsk2    1/1     Running            3d22h 
-postgresql 14:58:48.85 INFO  ==> Initializing PostgreSQL database... +voting-app-deployment-669dccccfb-jpn6h   1/1     Running            4d1h 
-postgresql 14:58:48.87 INFO  ==> pg_hba.conf file not detected. Generating it... +voting-app-deployment-669dccccfb-ktd7d   1/1     Running            3d22h 
-postgresql 14:58:48.87 INFO  ==> Generating local authentication configuration +voting-app-deployment-669dccccfb-x868p   1/    Running            3d22h 
-postgresql 14:58:53.51 INFO  ==> Starting PostgreSQL in background... +worker-app-deployment-559f7749b6-jh86r   1/1     Running   19         4d1h
-postgresql 14:58:53.64 INFO  ==> Changing password of postgres +
-postgresql 14:58:53.66 INFO  ==> Configuring replication parameters +
-postgresql 14:58:53.69 INFO  ==> Configuring fsync +
-postgresql 14:58:53.70 INFO  ==> Loading custom scripts... +
-postgresql 14:58:53.71 INFO  ==> Enabling remote connections +
-postgresql 14:58:53.73 INFO  ==> Stopping PostgreSQL... +
-postgresql 14:58:54.74 INFO  ==> ** PostgreSQL setup finished! ** +
- +
-postgresql 14:58:54.78 INFO  ==> ** Starting PostgreSQL ** +
-2020-12-12 14:58:54.819 GMT [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432 +
-2020-12-12 14:58:54.820 GMT [1] LOG:  listening on IPv6 address "::", port 5432 +
-2020-12-12 14:58:54.829 GMT [1] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432" +
-2020-12-12 14:58:54.843 GMT [106] LOG:  database system was shut down at 2020-12-12 14:58:53 GMT +
-2020-12-12 14:58:54.850 GMT [1] LOG:  database system is ready to accept connections+
 </code> </code>
  
-Pour lister les plugins installés, utilisez la commande **list** :+Connectez-vous au conteneur :
  
 <code> <code>
-root@debian10:~# kubectl krew list +root@kubemaster:~# kubectl exec -it flask-cap -- bash 
-PLUGIN            VERSION +root@flask-cap:/#
-ctx               v0.9.1 +
-krew              v0.4.0 +
-ns                v0.9.1 +
-pod-logs          v1.0.1 +
-view-allocations  v0.9.2+
 </code> </code>
  
-Pour mettre à jour les plugins installés, utilisez la commande **upgrade** :+Notez la mise en place des restrictions :
  
 <code> <code>
-root@debian10:~kubectl krew upgrade +root@flask-cap:/ping 8.8.8.8 
-Updated the local copy of plugin index+pingLacking privilege for raw socket. 
-Upgrading pluginctx +root@flask-cap:/# chown daemon /tmp 
-Skipping plugin ctx, it is already on the newest version +chownchanging ownership of '/tmp'Operation not permitted
-Upgrading pluginkrew +
-Skipping plugin krew, it is already on the newest version +
-Upgrading pluginns +
-Skipping plugin ns, it is already on the newest version +
-Upgrading pluginpod-logs +
-Skipping plugin pod-logs, it is already on the newest version +
-Upgrading plugin: view-allocations +
-Skipping plugin view-allocations, it is already on the newest version +
-</code>+
  
-Pour supprimer un plugin, utilisez la commande **remove** : +root@flask-cap:/exit 
- +exit 
-<code> +command terminated with exit code 1
-root@debian10:~# kubectl krew remove pod-logs +
-Uninstalled plugin pod-logs +
-root@debian10:~kubectl krew list +
-PLUGIN            VERSION +
-ctx               v0.9.1 +
-krew              v0.4.0 +
-ns                v0.9.1 +
-view-allocations  v0.9.2+
 </code> </code>
  
-====1.Gérer des patchs====+====2.Kubernetes Network Policies====
  
-===La Commande kustomize=== +Créez le fichier **guestbook-all-in-one.yaml** :
- +
-Commencez par installer l'exécutable **tree** que vous utiliserez ultérieurement pour visualiser l'arborescence des répertoires et des fichiers que vous allez créer :+
  
 <code> <code>
-root@debian10:~# apt install tree +root@kubemaster:~# vi guestbook-all-in-one.yaml  
-</code> +root@kubemaster:~# cat  guestbook-all-in-one.yaml  
- +apiVersion: v1 
-Créez ensuite le répertoire **kustomize** contenant le répertoire **base** et placez-vous dans ce dernier : +kind: Service
- +
-<code> +
-root@debian10:~# mkdir -p kustomize/base +
-root@debian10:~# cd kustomize/base/ +
-root@debian10:~/kustomize/base#  +
-</code> +
- +
-Créez le manifest **deployment.yaml** : +
- +
-<code> +
-root@debian10:~/kustomize/base# vi deployment.yaml +
-root@debian10:~/kustomize/base# cat deployment.yaml +
-apiVersion: apps/v1 +
-kind: Deployment+
 metadata: metadata:
-  name: nginx+  name: redis-master
   labels:   labels:
-    app: nginx+    app: redis 
 +    tier: backend 
 +    role: master
 spec: spec:
 +  ports:
 +    # the port that this service should serve on
 +  - port: 6379
 +    targetPort: 6379
 +  selector:
 +    app: redis
 +    tier: backend
 +    role: master
 +---
 +apiVersion: v1
 +kind: ReplicationController
 +metadata:
 +  name: redis-master
 +  # these labels can be applied automatically 
 +  # from the labels in the pod template if not set
 +  labels:
 +    app: redis
 +    role: master
 +    tier: backend
 +spec:
 +  # this replicas value is default
 +  # modify it according to your case
   replicas: 1   replicas: 1
-  selector: +  selector can be applied automatically  
-    matchLabels+  # from the labels in the pod template if not set 
-      app: nginx+  # selector
 +  #   app: guestbook 
 +  #   role: master 
 +  #   tier: backend
   template:   template:
     metadata:     metadata:
       labels:       labels:
-        app: nginx+        app: redis 
 +        role: master 
 +        tier: backend
     spec:     spec:
-      affinity: 
-        podAntiAffinity: 
-          requiredDuringSchedulingIgnoredDuringExecution: 
-          - labelSelector: 
-              matchExpressions: 
-              - key: app 
-                operator: In 
-                values: 
-                - nginx 
-            topologyKey: "kubernetes.io/hostname" 
       containers:       containers:
-      - image: nginx:1.18.0 +      - name: master 
-        imagePullPolicyIfNotPresent +        image: gcr.io/google_containers/redis:e2e  # or just image: redis 
-        namenginx +        resources
-</code> +          requests
- +            cpu: 100m 
-<WRAP center round important 40%> +            memory100Mi 
-**Important** - le contenu de ce fichier crée un **deployment** de 1 **replica** du pod **nginx** à partir de l'image **nginx:1.18.0**. +        ports
-</WRAP> +        - containerPort6379 
- +---
-Créez ensuite le manifest **service.yaml** +
- +
-<code> +
-root@debian10:~/kustomize/base# vi service.yaml +
-root@debian10:~/kustomize/base# cat service.yaml+
 apiVersion: v1 apiVersion: v1
 kind: Service kind: Service
 metadata: metadata:
-  name: nginx+  name: redis-slave
   labels:   labels:
-    app: nginx+    app: redis 
 +    tier: backend 
 +    role: slave
 spec: spec:
-  type: ClusterIP 
   ports:   ports:
-  - port: 80 +    # the port that this service should serve on 
-    protocol: TCP +  - port: 6379
-    targetPort: 80+
   selector:   selector:
-    app: nginx +    app: redis 
-</code> +    tierbackend 
- +    roleslave 
-<WRAP center round important 40%> +---
-**Important** - le contenu de ce fichier crée un **service** de type **ClusterIP** en utilisant le **deployment** précédent. Le Service ClusterIP permet de regrouper les PODs offrant le même service afin de faciliter la communication. +
-</WRAP> +
- +
-<WRAP center round tip 40%> +
-Le Service ClusterIP permet de regrouper les PODs offrant le même service afin de faciliter la communication. +
-</WRAP> +
- +
-Dernièrement, créez le manifest **kustomization.yaml** +
- +
-<code> +
-root@debian10:~/kustomize/base# vi kustomization.yaml +
-root@debian10:~/kustomize/base# cat kustomization.yaml +
-apiVersion: kustomize.config.k8s.io/v1beta1 +
-kind: Kustomization +
- +
-images+
-name: nginx +
-  newTag: 1.19.1 +
- +
-resources: +
-deployment.yaml +
-service.yaml +
-</code> +
- +
-<WRAP center round important 60%> +
-**Important** - le contenu de ce fichier contient un **patch** pour l'application **nginx** créée par les deux fichiers précédent. Notez le tag **newTag** dans la section **images**. Dans la section **resources** se trouve la liste des manifests concernés par le patch. Notez que seul le manifest **deployment.yaml** fait référence à une image. Cependant, le fichier **service.yaml** est inclus ici car il sera nécessaire par la suite. +
-</WRAP> +
- +
-Consultez donc l'arborescence du répertoire **kustomize** : +
- +
-<code> +
-root@debian10:~/kustomize/base# cd .. +
-root@debian10:~/kustomize# tree +
-+
-└── base +
-    ├── deployment.yaml +
-    ├── kustomization.yaml +
-    └── service.yaml +
- +
-1 directory, 3 files +
-</code> +
- +
-Exécutez maintenant la commande **kustomize** pour créer un **patch** pour les fichiers se trouvant dans le répertoire **base** : +
- +
-<code> +
-root@debian10:~/kustomize# kubectl kustomize base+
 apiVersion: v1 apiVersion: v1
-kind: Service+kind: ReplicationController
 metadata: metadata:
 +  name: redis-slave
 +  # these labels can be applied automatically
 +  # from the labels in the pod template if not set
   labels:   labels:
-    app: nginx +    app: redis 
-  namenginx+    roleslave 
 +    tier: backend
 spec: spec:
-  ports: +  # this replicas value is default 
-  - port: 80 +  # modify it according to your case 
-    protocolTCP +  replicas2 
-    targetPort: 80 +  selector can be applied automatically 
-  selector: +  # from the labels in the pod template if not set 
-    app: nginx +  # selector
-  type: ClusterIP +  #   app: guestbook 
---- +  #   roleslave 
-apiVersion: apps/v1 +  #   tierbackend
-kind: Deployment +
-metadata+
-  labels: +
-    app: nginx +
-  name: nginx +
-spec+
-  replicas: 1 +
-  selector: +
-    matchLabels: +
-      appnginx+
   template:   template:
     metadata:     metadata:
       labels:       labels:
-        app: nginx+        app: redis 
 +        role: slave 
 +        tier: backend
     spec:     spec:
-      affinity: 
-        podAntiAffinity: 
-          requiredDuringSchedulingIgnoredDuringExecution: 
-          - labelSelector: 
-              matchExpressions: 
-              - key: app 
-                operator: In 
-                values: 
-                - nginx 
-            topologyKey: kubernetes.io/hostname 
       containers:       containers:
-      - imagenginx:1.19.1 +      - nameslave 
-        imagePullPolicy: IfNotPresent +        image: gcr.io/google_samples/gb-redisslave:v1 
-        name: nginx +        resources: 
-</code> +          requests: 
- +            cpu100m 
-<WRAP center round important 40%> +            memory100Mi 
-**Important** - notez que le fichier généré contient les contenus des **deux** fichiers **deployment.yaml** et **service.yaml** séparés par les caractères **---**. Le contenu du fichier **service.yaml** n'a pas été modifié tandis que l'image a été modifiée de **image: nginx:1.18.0** vers **image: nginx:1.19.1** dans le contenu du fichier **deployment.yaml**. Notez que les deux fichiers d'origine n'ont **pas** été modifiés. +        env: 
-</WRAP> +        - name: GET_HOSTS_FROM 
- +          valuedns 
-Imaginons maintenant que vous souhaitez déployer deux environnements **différents** de la même application, un pour la production et un pour le développement. La commande **kustomize** permet de faire ceci en utilisant des **overlays**. +          # If your cluster config does not include a dns service, then to 
- +          # instead access an environment variable to find the master 
-Créez les répertoires **kustomize/overlays/development** et **kustomize/overlays/production** +          # service's hostcomment out the 'valuedns' line above, and 
- +          uncomment the line below
-<code> +          valueenv 
-root@debian10:~/kustomize# mkdir -p overlays/development +        ports
-root@debian10:~/kustomize# mkdir overlays/production +        containerPort6379 
-</code> +---
- +
-Consultez l'arborescence du répertoire **kustomize** +
- +
-<code> +
-root@debian10:~/kustomizetree +
-+
-├── base +
-│   ├── deployment.yaml +
-│   ├── kustomization.yaml +
-│   └── service.yaml +
-└── overlays +
-    ├── development +
-    └── production +
- +
-4 directories3 files +
-</code> +
- +
-Créez le fichier **overlays/development/kustomization.yaml** +
- +
-<code> +
-root@debian10:~/kustomizevi overlays/development/kustomization.yaml +
-root@debian10:~/kustomizecat overlays/development/kustomization.yaml +
-apiVersionkustomize.config.k8s.io/v1beta1 +
-kind: Kustomization +
- +
-bases+
-../../base  # <---------------------indique où sont stockés les manifests principaux +
- +
-nameSuffix-development # <----------met à jour le nom du service/deployment +
- +
-commonLabels: +
-  environment: development # <--------ajoute une étiquette supplémentaire +
- +
-namespace: nginx-dev # <--------------indique le nom du namespace +
-</code> +
- +
-Appliquez ces modifications : +
- +
-<code> +
-root@debian10:~/kustomize# kubectl kustomize overlays/development/+
 apiVersion: v1 apiVersion: v1
 kind: Service kind: Service
 metadata: metadata:
 +  name: frontend
   labels:   labels:
-    app: nginx +    app: guestbook 
-    environmentdevelopment # <-----------étiquette supplémentaire +    tierfrontend
-  name: nginx-development # <--------------mise à jour du nom du service +
-  namespace: nginx-dev # <-----------------indique le nom du namespace+
 spec: spec:
 +  # if your cluster supports it, uncomment the following to automatically create
 +  # an external load-balanced IP for the frontend service.
 +  # type: LoadBalancer
   ports:   ports:
 +    # the port that this service should serve on
   - port: 80   - port: 80
-    protocol: TCP 
-    targetPort: 80 
   selector:   selector:
-    app: nginx +    app: guestbook 
-    environmentdevelopment # <-----------étiquette supplémentaire +    tierfrontend
-  type: ClusterIP+
 --- ---
-apiVersion: apps/v1 +apiVersion: v1 
-kind: Deployment+kind: ReplicationController
 metadata: metadata:
 +  name: frontend
 +  # these labels can be applied automatically
 +  # from the labels in the pod template if not set
   labels:   labels:
-    app: nginx +    app: guestbook 
-    environmentdevelopment +    tierfrontend
-  name: nginx-development +
-  namespace: nginx-dev+
 spec: spec:
-  replicas: 1 +  # this replicas value is default 
-  selector: +  # modify it according to your case 
-    matchLabels+  replicas: 3 
-      app: nginx +  selector can be applied automatically 
-      environmentdevelopment+  # from the labels in the pod template if not set 
 +  # selector
 +  #   app: guestbook 
 +  #   tierfrontend
   template:   template:
     metadata:     metadata:
       labels:       labels:
-        app: nginx +        app: guestbook 
-        environmentdevelopment+        tierfrontend
     spec:     spec:
-      affinity: 
-        podAntiAffinity: 
-          requiredDuringSchedulingIgnoredDuringExecution: 
-          - labelSelector: 
-              matchExpressions: 
-              - key: app 
-                operator: In 
-                values: 
-                - nginx 
-            topologyKey: kubernetes.io/hostname 
       containers:       containers:
-      - image: nginx:1.19.1 # <-------------utilise l'image spécifiée dans le fichier /kustomize/base/kustomization.yaml +      - name: php-redis 
-        imagePullPolicyIfNotPresent +        image: corelab/gb-frontend:v5 
-        namenginx+        resources: 
 +          requests: 
 +            cpu: 100m 
 +            memory: 100Mi 
 +        env: 
 +        name: GET_HOSTS_FROM 
 +          value: dns 
 +          # If your cluster config does not include a dns service, then to 
 +          # instead access environment variables to find service host 
 +          # info, comment out the 'value: dns' line above, and uncomment the 
 +          # line below. 
 +          # value: env 
 +        ports
 +        - containerPort80
 </code> </code>
  
-Maintenant créez le fichier **overlays/production/kustomization.yaml** :+Installez l'application **Guestbook** :
  
 <code> <code>
-root@debian10:~/kustomizevi overlays/production/kustomization.yaml +root@kubemaster:~# kubectl create -f guestbook-all-in-one.yaml 
-root@debian10:~/kustomize# cat overlays/production/kustomization.yaml +</code>
-apiVersion: kustomize.config.k8s.io/v1beta1 +
-kind: Kustomization+
  
-bases: +Attendez que tous les pods soient dans un état de **READY** :
-- ../../base # <---------------------indique où sont stockés les manifests principaux+
  
-nameSuffix-production # <----------met à jour le nom du service/deployment+<code> 
 +root@kubemaster:~kubectl get pods -o wide 
 +NAME                 READY   STATUS    RESTARTS   AGE   IP               NODE                       NOMINATED NODE   READINESS GATES 
 +flask-cap            1/1     Running            53m   192.168.239.26   kubenode1.ittraining.loc   <none>           <none> 
 +flask-ro             1/    Running            59m   192.168.150.14   kubenode2.ittraining.loc   <none>           <none> 
 +frontend-dhd4w       1/    Running            32m   192.168.150.16   kubenode2.ittraining.loc   <none>           <none> 
 +frontend-dmbbf       1/    Running            32m   192.168.150.17   kubenode2.ittraining.loc   <none>           <none> 
 +frontend-rqr6p       1/    Running            32m   192.168.239.29   kubenode1.ittraining.loc   <none>           <none> 
 +redis-master-zrrr4   1/    Running            32m   192.168.239.27   kubenode1.ittraining.loc   <none>           <none> 
 +redis-slave-jsrt6    1/1     Running            32m   192.168.150.15   kubenode2.ittraining.loc   <none>           <none> 
 +redis-slave-rrnx9    1/1     Running            32m   192.168.239.28   kubenode1.ittraining.loc   <none>           <none> 
 +... 
 +</code>
  
-commonLabels: +Cette application crée des pods de type //backend// et //frontend// :
-  environment: production # <--------ajoute une étiquette supplémentaire+
  
-namespacenginx-prod <------------indique le nom du namespace+<code> 
 +root@kubemaster:~kubectl describe pod redis-master-zrrr4 | grep tier 
 +              tier=backend
  
-images: +root@kubemaster:~# kubectl describe pod frontend-dhd4w | grep tier 
-name: nginx +              tier=frontend
-  newTag: 1.19.2 # <-----------------modifie l'image spécifiée dans le fichier /kustomize/base/kustomization.yaml+
 </code> </code>
  
-Appliquez ces modifications :+Créez le fichier **guestbook-network-policy.yaml** qui empêchera la communication d'un pod backend vers un pod frontend :
  
 <code> <code>
-root@debian10:~/kustomizekubectl kustomize overlays/production/ +root@kubemaster:~# vi guestbook-network-policy.yaml 
-apiVersion: v1 +root@kubemaster:~# cat guestbook-network-policy.yaml 
-kind: Service+apiVersion: networking.k8s.io/v1 
 +kind: NetworkPolicy
 metadata: metadata:
-  labels: +  name: deny-backend-egress 
-    app: nginx +  namespace: default
-    environment: production # <-----------étiquette supplémentaire +
-  name: nginx-production # <--------------mise à jour du nom du service +
-  namespace: nginx-prod # <---------------indique le nom du namespace+
 spec: spec:
-  ports: +  podSelector:
-  - port: 80 +
-    protocol: TCP +
-    targetPort: 80 +
-  selector: +
-    app: nginx +
-    environment: production # <-----------étiquette supplémentaire +
-  type: ClusterIP +
---- +
-apiVersion: apps/v1 +
-kind: Deployment +
-metadata: +
-  labels: +
-    app: nginx +
-    environment: production +
-  name: nginx-production +
-  namespace: nginx-prod +
-spec: +
-  replicas: 1 +
-  selector:+
     matchLabels:     matchLabels:
-      appnginx +      tierbackend 
-      environment: production +  policyTypes
-  template+    - Egress 
-    metadata: +  egress
-      labels: +    - to
-        app: nginx +       podSelector
-        environment: production +           matchLabels
-    spec: +             tierbackend
-      affinity: +
-        podAntiAffinity: +
-          requiredDuringSchedulingIgnoredDuringExecution: +
-          labelSelector+
-              matchExpressions: +
-              keyapp +
-                operator: In +
-                values: +
-                - nginx +
-            topologyKey: kubernetes.io/hostname +
-      containers: +
-      - image: nginx:1.19.2 # <-------------utilise l'image spécifiée dans le fichier overlays/production/kustomization.yaml +
-        imagePullPolicyIfNotPresent +
-        namenginx+
 </code> </code>
  
-Créez maintenant le namespace **nginx-prod** :+Exécutez kubectl :
  
 <code> <code>
-root@debian10:~/kustomize# kubectl create ns nginx-prod +root@kubemaster:~# kubectl create -f guestbook-network-policy.yaml 
-namespace/nginx-prod created+networkpolicy.networking.k8s.io/deny-backend-egress created
 </code> </code>
  
-Installez l'application **production** :+Connectez-vous au pod **redis-master** :
  
 <code> <code>
-root@debian10:~/kustomize# kubectl apply -k overlays/production/ +root@kubemaster:~# kubectl exec -it redis-master-zrrr4 -- bash 
-service/nginx-production created +[ root@redis-master-zrrr4:/data ]$ 
-deployment.apps/nginx-production created+
 </code> </code>
  
-Constatez le résultat de l'installation :+Essayez de contacter un pod du même **tier** :
  
 <code> <code>
-root@debian10:~/kustomize# kubectl get pods -n nginx-prod +root@redis-master-zrrr4:/data ]$ ping -c 4 192.168.150.15 
-NAME                               READY   STATUS    RESTARTS   AGE +PING 192.168.150.15 (192.168.150.15) 56(84) bytes of data. 
-nginx-production-f456f9c8f-8hgss   1/    Running            51s +64 bytes from 192.168.150.15: icmp_seq=ttl=62 time=0.324 ms 
-root@debian10:~/kustomize# kubectl get deployments -n nginx-prod +64 bytes from 192.168.150.15icmp_seq=2 ttl=62 time=0.291 ms 
-NAME               READY   UP-TO-DATE   AVAILABLE   AGE +64 bytes from 192.168.150.15: icmp_seq=3 ttl=62 time=0.366 ms 
-nginx-production   1/               1           67s +64 bytes from 192.168.150.15icmp_seq=4 ttl=62 time=0.379 ms 
-root@debian10:~/kustomize# kubectl get services -n nginx-prod + 
-NAME               TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE +--- 192.168.150.15 ping statistics --
-nginx-production   ClusterIP   10.96.55.123   <none>        80/TCP    77s+4 packets transmitted, 4 received, 0% packet loss, time 3070ms 
 +rtt min/avg/max/mdev = 0.291/0.340/0.379/0.034 ms
 </code> </code>
  
-Supprimez le deployment et le service nginx-production :+Essayez maintenant de contacter un pod d'un **tier** frontend :
  
 <code> <code>
-root@debian10:~/kustomize# kubectl delete deployments/nginx-production -n nginx-prod +root@redis-master-zrrr4:/data ]$ ping -c 4 192.168.150.16 
-deployment.apps "nginx-production" deleted +PING 192.168.150.16 (192.168.150.16) 56(84) bytes of data
-root@debian10:~/kustomize# kubectl get deployments -n nginx-prod + 
-No resources found in nginx-prod namespace. +--- 192.168.150.16 ping statistics --- 
-root@debian10:~/kustomize# kubectl get services -n nginx-prod +4 packets transmitted, 0 received, 100% packet loss, time 3063ms
-NAME               TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE +
-nginx-production   ClusterIP   10.96.55.123   <none>        80/TCP    4m13s +
-root@debian10:~/kustomize# kubectl get pods -n nginx-prod +
-No resources found in nginx-prod namespace. +
-root@debian10:~/kustomize# kubectl delete services/nginx-production -n nginx-prod +
-service "nginx-production" deleted +
-root@debian10:~/kustomize# kubectl get services -n nginx-prod +
-No resources found in nginx-prod namespace.+
 </code> </code>
  
-Installez l'application **development** :+Déconnectez-vous du pod **redis-master** et connectez-vous à un pod **frontend** :
  
 <code> <code>
-root@debian10:~/kustomize# kubectl create ns nginx-dev +root@redis-master-zrrr4:/data ]$ exit 
-namespace/nginx-dev created +exit 
-root@debian10:~/kustomize# kubectl apply -k overlays/development/ +command terminated with exit code 1 
-service/nginx-development created + 
-deployment.apps/nginx-development created+root@kubemaster:~# kubectl exec -it frontend-dhd4w -- bash 
 +root@frontend-dhd4w:/var/www/html#  
 </code> </code>
  
-Constatez le résultat :+Installez le paquet **iputils-ping** :
  
 <code> <code>
-root@debian10:~/kustomize# kubectl get pods -n nginx-dev +root@frontend-dhd4w:/var/www/htmlapt update 
-NAME                                 READY   STATUS    RESTARTS   AGE +root@frontend-dhd4w:/var/www/htmlapt install iputils-ping -y
-nginx-development-579c5cfcb6-w8dmq   1/1     Running            42s +
-root@debian10:~/kustomizekubectl get deployments -n nginx-dev +
-NAME                READY   UP-TO-DATE   AVAILABLE   AGE +
-nginx-development   1/               1           52s +
-root@debian10:~/kustomizekubectl get services -n nginx-dev +
-NAME                TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)   AGE +
-nginx-development   ClusterIP   10.96.51.27   <none>        80/TCP    62s+
 </code> </code>
  
-====1.9 - Alias utiles==== +Essayez de contacter un pod du même **tier** :
- +
-Pour faciliter le travail avec la commande kubectl, il est recommendé de créer des alias sous bash ou zsh :+
  
 <code> <code>
-root@debian10:~/kustomize# vi ~/.bash_aliases +root@frontend-dhd4w:/var/www/htmlping -c 4 192.168.150.17 
-root@debian10:~/kustomizecat ~/.bash_aliases +PING 192.168.150.17 (192.168.150.17): 56 data bytes 
-alias k='kubectl' +64 bytes from 192.168.150.17: icmp_seq=0 ttl=63 time=0.185 ms 
-alias kg='kubectl get' +64 bytes from 192.168.150.17: icmp_seq=1 ttl=63 time=0.112 ms 
-alias kd='kubectl describe' +64 bytes from 192.168.150.17: icmp_seq=2 ttl=63 time=0.093 ms 
-alias kga='kubectl get all' +64 bytes from 192.168.150.17: icmp_seq=3 ttl=63 time=0.121 ms 
-alias kp='kubectl get pods -o wide' +--- 192.168.150.17 ping statistics --
-alias kap='kubectl get pods -A -o wide' +4 packets transmitted, 4 packets received, 0% packet loss 
-alias ka='kubectl apply -f' +round-trip min/avg/max/stddev 0.093/0.128/0.185/0.035 ms
-alias kei='kuebctl exec -it' +
-alias ke='kubectl exec' +
-alias ktn='watch kubectl top nodes' +
-alias ktp='watch kubectl top pods' +
-alias kpf='kubectl port-forward' +
-alias kl='kubectl logs' +
-alias kz='kustomize'+
 </code> </code>
  
-Activez les alias avec la commande **source** :+Essayez maintenant de contacter un pod d'un **tier** backend :
  
 <code> <code>
-root@debian10:~/kustomizesource ~/.bash_aliases+root@frontend-dhd4w:/var/www/htmlping -c 4 192.168.239.27 
 +PING 192.168.239.27 (192.168.239.27): 56 data bytes 
 +64 bytes from 192.168.239.27: icmp_seq=0 ttl=62 time=0.371 ms 
 +64 bytes from 192.168.239.27: icmp_seq=1 ttl=62 time=0.469 ms 
 +64 bytes from 192.168.239.27: icmp_seq=2 ttl=62 time=0.349 ms 
 +64 bytes from 192.168.239.27: icmp_seq=3 ttl=62 time=0.358 ms 
 +--- 192.168.239.27 ping statistics --- 
 +4 packets transmitted, 4 packets received, 0% packet loss 
 +round-trip min/avg/max/stddev = 0.349/0.387/0.469/0.048 ms
 </code> </code>
  
-===L'Alias kg===+Sortez du pod frontend :
  
 <code> <code>
-root@debian10:~/kustomize# kg nodes +root@frontend-dhd4w:/var/www/htmlexit 
-NAME                 STATUS   ROLES    AGE   VERSION +exit 
-kind-control-plane   Ready    master   82m   v1.19.1 +root@kubemaster:~#
-kind-worker2         Ready    <none>   81m   v1.19.1 +
-kind-worker3         Ready    <none>   81m   v1.19.1 +
-root@debian10:~/kustomize# kg deployments +
-NAME         READY   UP-TO-DATE   AVAILABLE   AGE +
-postgresql   1/1                1           80m +
-root@debian10:~/kustomizekg services +
-NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE +
-kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   82m +
-root@debian10:~/kustomizekg pods +
-NAME                          READY   STATUS    RESTARTS   AGE +
-postgresql-6c99978556-kqkp4   1/    Running            81m+
 </code> </code>
  
-===L'Alias kd===+====2.4 - Kubernetes Resource Allocation Management====
  
-<code> +Les ressources qui peuvent être limitées au niveau d'un pod sont :
-root@debian10:~/kustomize# kd pod postgresql-6c99978556-kqkp4 | more +
-Name:         postgresql-6c99978556-kqkp4 +
-Namespace:    default +
-Priority:     0 +
-Node:         kind-worker2/172.18.0.4 +
-Start Time:   Sun, 13 Dec 2020 13:37:14 +0100 +
-Labels:       app=postgresql +
-              pod-template-hash=6c99978556 +
-Annotations:  <none> +
-Status:       Running +
-IP:           10.244.1.2 +
-IPs: +
-  IP:           10.244.1.2 +
-Controlled By:  ReplicaSet/postgresql-6c99978556 +
-Containers: +
-  postgresql: +
-    Container ID:   containerd://4faccd4f90e93528e6dddac1cc24dba7f93e36a4442e60093676e2ad1d4218aa +
-    Image:          bitnami/postgresql:10.13.0 +
-    Image ID:       docker.io/bitnami/postgresql@sha256:00794b9129f9b60942d70d635a00398180e70b4759e570e38cfe7434ebe2ccdd +
-    Port:           <none> +
-    Host Port:      <none> +
-    State:          Running +
-      Started:      Sun, 13 Dec 2020 13:37:36 +0100 +
-    Ready:          True +
-    Restart Count: +
-    Environment: +
-      POSTGRESQL_PASSWORD:  VerySecurePassword:-) +
-    Mounts: +
-      /var/run/secrets/kubernetes.io/serviceaccount from default-token-z5ptn (ro) +
-Conditions: +
-  Type              Status +
-  Initialized       True  +
-  Ready             True  +
-  ContainersReady   True  +
-  PodScheduled      True  +
-Volumes: +
-  default-token-z5ptn: +
-    Type:        Secret (a volume populated by a Secret) +
-    SecretName:  default-token-z5ptn +
-    Optional:    false +
-QoS Class:       BestEffort +
-Node-Selectors:  <none> +
-Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s +
---More-- +
-</code>+
  
-===L'Alias kga===+  * CPU 
 +  * Mémoire 
 +  * Stockage local 
 + 
 +Créez le fichier **flask-resources.yaml** :
  
 <code> <code>
-root@debian10:~/kustomizekga +root@kubemaster:~# vi flask-resources.yaml 
-NAME                              READY   STATUS    RESTARTS   AGE +root@kubemaster:~# cat flask-resources.yaml 
-pod/postgresql-6c99978556-kqkp4   1/1     Running            84m+apiVersion: v1 
 +kind: Pod 
 +metadata: 
 +  name: flask-resources 
 +  namespace: default 
 +spec: 
 +  containers: 
 +  image: mateobur/flask 
 +    name: flask-resources 
 +    resources: 
 +      requests: 
 +        memory: 512Mi 
 +      limits: 
 +        memory: 700Mi 
 +</code>
  
-NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE +Dans ce fichier on peut constater deux allocations de ressources :
-service/kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   86m+
  
-NAME                         READY   UP-TO-DATE   AVAILABLE   AGE +  * **requests**, 
-deployment.apps/postgresql   1/               1           84m+    * la quantité de mémoire qui doit être libre au moment du scheduling du pod, 
 +  * **limits**, 
 +    * la limite de mémoire pour le pod concerné.
  
-NAME                                    DESIRED   CURRENT   READY   AGE +Exécutez kubectl :
-replicaset.apps/postgresql-6c99978556                         84m +
-</code> +
- +
-===L'Alias kp===+
  
 <code> <code>
-root@debian10:~/kustomizekp +root@kubemaster:~# kubectl create -f flask-resources.yaml 
-NAME                          READY   STATUS    RESTARTS   AGE   IP           NODE           NOMINATED NODE   READINESS GATES +pod/flask-resources created
-postgresql-6c99978556-kqkp4   1/1     Running            85m   10.244.1.2   kind-worker2   <none>           <none>+
 </code> </code>
  
-===L'Alias kap===+Attendez que le statut du pod soit **READY** :
  
 <code> <code>
-root@debian10:~/kustomizekap +root@kubemaster:~# kubectl get pods 
-NAMESPACE            NAME                                         READY   STATUS    RESTARTS   AGE   IP           NODE                 NOMINATED NODE   READINESS GATES +NAME                 READY   STATUS    RESTARTS   AGE 
-default              postgresql-6c99978556-kqkp4                  1/1     Running            86m   10.244.1.2   kind-worker2         <none>           <none> +flask-cap            1/    Running            67m 
-kube-system          coredns-f9fd979d6-hd5sh                      1/1     Running            88m   10.244.0.3   kind-control-plane   <none>           <none> +flask-resources      1/1     Running            53s 
-kube-system          coredns-f9fd979d6-q7tcx                      1/1     Running            88m   10.244.0.2   kind-control-plane   <none>           <none> +flask-ro             1/1     Running            74m 
-kube-system          etcd-kind-control-plane                      1/1     Running            88m   172.18.0.5   kind-control-plane   <none>           <none> +...
-kube-system          kindnet-2vgnb                                1/1     Running            87m   172.18.0.4   kind-worker2         <none>           <none> +
-kube-system          kindnet-6x6pk                                1/1     Running            88m   172.18.0.5   kind-control-plane   <none>           <none> +
-kube-system          kindnet-snk42                                1/1     Running            87m   172.18.0.3   kind-worker3         <none>           <none> +
-kube-system          kube-apiserver-kind-control-plane            1/    Running            88m   172.18.0.5   kind-control-plane   <none>           <none> +
-kube-system          kube-controller-manager-kind-control-plane   1/1     Running            88m   172.18.0.5   kind-control-plane   <none>           <none> +
-kube-system          kube-proxy-lkljb                             1/1     Running            87m   172.18.0.3   kind-worker3         <none>           <none> +
-kube-system          kube-proxy-mfgcf                             1/    Running            88m   172.18.0.5   kind-control-plane   <none>           <none> +
-kube-system          kube-proxy-wl4mk                             1/    Running            87m   172.18.0.4   kind-worker2         <none>           <none> +
-kube-system          kube-scheduler-kind-control-plane            1/1     Running            88m   172.18.0.5   kind-control-plane   <none>           <none> +
-local-path-storage   local-path-provisioner-78776bfc44-bp7pb      1/1     Running            88m   10.244.0.4   kind-control-plane   <none>           <none> +
-nginx-dev            nginx-development-579c5cfcb6-w8dmq           1/    Running            25m   10.244.3.3   kind-worker3         <none>           <none>+
 </code> </code>
  
-===L'Alias kei===+Connectez-vous au pod :
  
 <code> <code>
-root@debian10:~/kustomizekei postgresql-6c99978556-kqkp4 -- bash +root@kubemaster:~# kubectl exec -it flask-resources -- bash 
-I have no name!@postgresql-6c99978556-kqkp4:/$ exit +root@flask-resources:/
-exit+
 </code> </code>
  
-===L'Alias ke===+Installez le paquet **stress** :
  
 <code> <code>
-root@debian10:~/kustomizeke postgresql-6c99978556-kqkp4 -- ls -alh +root@flask-resources:/# echo "deb http://archive.debian.org/debian/ jessie main contrib non-free" > /etc/apt/sources.list 
-total 88K +root@flask-resources:/# echo "deb http://archive.debian.org/debian-security jessie/updates main contrib non-free" >> /etc/apt/sources.list 
-drwxr-xr-x   1 root root 4.0K Dec 13 12:37 . +root@flask-resources:/# cat /etc/apt/sources.list 
-drwxr-xr-x   1 root root 4.0K Dec 13 12:37 .. +deb http://archive.debian.org/debian/ jessie main contrib non-free 
-drwxr-xr-x   1 root root 4.0K Aug 12 04:15 bin +deb http://archive.debian.org/debian-security jessie/updates main contrib non-free 
-drwxr-xr-x   root root 4.0K Aug 12 04:16 bitnami +root@flask-resources:/# apt update 
-drwxr-xr-x   2 root root 4.0K Jul 10 21:04 boot +root@flask-resources:/# apt install stress -y
-drwxr-xr-x   5 root root  360 Dec 13 12:37 dev +
-drwxrwxr-x   2 root root 4.0K Aug 12 04:16 docker-entrypoint-initdb.d +
-drwxr-xr-x   root root 4.0K Dec 13 12:37 docker-entrypoint-preinitdb.d +
-drwxr-xr-x   1 root root 4.0K Dec 13 12:37 etc +
-drwxr-xr-x   2 root root 4.0K Jul 10 21:04 home +
-drwxr-xr-x   1 root root 4.0K Sep 25  2017 lib +
-drwxr-xr-x   2 root root 4.0K Jul 21 19:27 lib64 +
-drwxr-xr-x   2 root root 4.0K Jul 21 19:27 media +
-drwxr-xr-x   2 root root 4.0K Jul 21 19:27 mnt +
-drwxrwxr-x   1 root root 4.0K Aug 12 04:15 opt +
-dr-xr-xr-x 177 root root    0 Dec 13 12:37 proc +
-drwx------   2 root root 4.0K Jul 21 19:27 root +
-drwxr-xr-x   1 root root 4.0K Dec 13 12:37 run +
-drwxr-xr-x   1 root root 4.0K Aug 12 04:15 sbin +
-drwxr-xr-x   root root 4.0K Jul 21 19:27 srv +
-dr-xr-xr-x  13 root root    0 Dec 13 12:37 sys +
-drwxrwxrwt   root root 4.0K Dec 13 12:37 tmp +
-drwxrwxr-x   1 root root 4.0K Aug 12 04:15 usr +
-drwxr-xr-x   1 root root 4.0K Jul 21 19:27 var+
 </code> </code>
  
-===L'Alias kpf===+Testez la limite mise en place :
  
 <code> <code>
-root@debian10:~/kustomizekpf postgresql-6c99978556-kqkp4 8080 +root@flask-resources:/# stress --cpu 1 --io 1 --vm 2 --vm-bytes 800M 
-Forwarding from 127.0.0.1:8080 -> 8080 +stressinfo[41dispatching hogs1 cpu, 1 io, 2 vm, 0 hdd 
-Forwarding from [::1]:8080 -> 8080 +stress: FAIL: [41] (416) <-worker 45 got signal 9 
-^Croot@debian10:~/kustomize# +stressWARN: [41] (418) now reaping child worker processes 
 +stress: FAIL: [41] (452) failed run completed in 1s
 </code> </code>
  
-===L'Alias kl===+Sortez du pod flask-resources :
  
 <code> <code>
-root@debian10:~/kustomizek get deploy +root@flask-resources:/# exit 
-NAME         READY   UP-TO-DATE   AVAILABLE   AGE +exit 
-postgresql   1/               1           92m +root@kubemaster:~#
-root@debian10:~/kustomizekl deploy/postgresql --tail 10 +
-postgresql 12:37:40.90 INFO  ==> Enabling remote connections +
-postgresql 12:37:40.92 INFO  ==> Stopping PostgreSQL... +
-postgresql 12:37:41.93 INFO  ==> ** PostgreSQL setup finished! ** +
- +
-postgresql 12:37:41.95 INFO  ==> ** Starting PostgreSQL ** +
-2020-12-13 12:37:41.979 GMT [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432 +
-2020-12-13 12:37:41.979 GMT [1] LOG:  listening on IPv6 address "::", port 5432 +
-2020-12-13 12:37:41.983 GMT [1] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432" +
-2020-12-13 12:37:42.001 GMT [105] LOG:  database system was shut down at 2020-12-13 12:37:40 GMT +
-2020-12-13 12:37:42.007 GMT [1] LOG:  database system is ready to accept connections+
 </code> </code>
  
 ---- ----
-<html> +Copyright © 2024 Hugh Norris
-<DIV ALIGN="CENTER"> +
-Copyright © 2020 Hugh Norris +
-</div> +
-</html> +
- +
Menu