Backup and restoration of the K8S etcd database
- etcd stores the state and configuration of the cluster, on each control plane.
- Backing up the database.
- Step-by-step restoration.
- Automation with Ansible; regularly test your scenarios.
Introduction
To function, Kubernetes stores its configuration in a key/value database.
Historically and by default, etcd serves this function within a cluster.
etcd can be externalized and deployed outside the cluster, but most often it is an integral part of the base components configured when using kubeadm.
In this type of installation, an etcd container is deployed on each control plane that makes up the cluster, thus providing data redundancy.
With each operation on the cluster, the etcd database is modified to maintain the status of K8S objects.
Constantly, Kubernetes compares the contents of its database with the state of the assets it controls. If a discrepancy is detected, K8S will then take the necessary steps to return to the state described in its database.
The etcd database therefore becomes a critical element of the cluster. In case of inconsistency, the entire status of the cluster may no longer correspond to the expectations of administrators.
The unavailability of etcd inevitably makes it impossible to interact with the cluster and therefore to manage the underlying assets.
Therefore, it is highly recommended to regularly back up the etcd database and to ensure that you can restore it in case of an incident.
In this article, I will try to describe a possible procedure for addressing this issue.
Nevertheless, this remains an exercise that may vary depending on the configuration. It is not guaranteed that what works in my case will work for you. But I hope you find enough elements here to build your backup strategy and practice restoration.
Principles
If it is relatively simple in the case of a cluster with only one control plane, it can be somewhat more complex in the case of multiple control planes.
Each control plane has its own version of the database and ensures that its content is consistent with the content of other servers.
This synchronization is ensured by the Raft protocol. It is a distributed consensus algorithm that requires a minimum number of servers to be active in order to function.
Raft is based on the concept of a leader who takes responsibility for managing writes to the database. The other nodes in the cluster are followers and receive updates from the leader.
If the leader becomes unavailable, the followers elect a new leader among themselves, provided that there are enough of them to reach an agreement.
For example, a cluster with three nodes can tolerate the loss of one node; the remaining two represent a sufficient majority. However, if a second node fails, Raft is no longer able to elect a leader, and the remaining node cannot ensure updates to the database.
Incorrectly restoring an etcd database within a cluster can cause desynchronization of nodes and errors in the Raft protocol, preventing the nodes from being able to elect a leader.
Therefore, it is necessary to follow a strict procedure that should not be hesitated to test several times before going into production.
To illustrate my article, I will use a development cluster that I set up with three control planes and two worker nodes, distributed across a VMware and XCP-ng infrastructure.
Click the image to enlarge.
I will create a backup before deleting a namespace called dev-demo-lan. The goal is to restore the backup to see the namespace reappear.
Backing up the etcd database
The backup can be performed independently on each control plane. It is recommended to create a backup for each control plane in order to have multiple backup images of the database.
As a prerequisite, it is necessary to install the etcd package on the control planes. etcd runs as containers, and the servers do not directly have the etcd binaries that are needed to execute the backup and restore commands.
In my case, I am using PhotonOS, so the installation of the package needs to be adapted to your distribution.
For me, the command is tdnf install etcd
Click the image to enlarge.
Next, we ensure that we are running as root in order to create a directory dedicated to hosting the backups.
To stay consistent with the description of my cluster installation, I arbitrarily chose /etc/kubernetes/backup.
mkdir -p /etc/kubernetes/backup
Click the image to enlarge.
Then, on each control plane, as root, I run the following command:
- On control plane one:
ETCDCTL_API=3 etcdctl --endpoints=https://ip_du_serveur_01:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key snapshot save /etc/kubernetes/backup/etcd-nom_serveur_01.snap - On the second control plane:
ETCDCTL_API=3 etcdctl --endpoints=https://ip_du_serveur_02:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key snapshot save /etc/kubernetes/backup/etcd-nom_serveur_02.snap - On the third control plane:
ETCDCTL_API=3 etcdctl --endpoints=https://ip_du_serveur_03:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key snapshot save /etc/kubernetes/backup/etcd-nom_serveur_03.snap
Click the image to enlarge.
The IP address to use is the primary IP address of your control plane. The other options allow you to specify the certificate and private key of the etcd server, so that you can authenticate with the etcd instance running as a container on the node.
Indeed, when deploying the cluster using kubeadm, all these elements are automatically generated and placed in the default paths. However, depending on your method of installing Kubernetes, the locations may differ.
Normally, the details of your etcd installation are available in the etcd installation manifest, which is retrieved by kubeadm (or another tool) and can be found at /etc/kubernetes/manifests/etcd.yaml
Click the image to enlarge.
You will find the elements to pass in your backup command there.
Once the operation is complete on each server, being careful to change the IP address for each control plane, you should have a backup per server.
When we talk about backups, we are actually talking about snapshots, and that is how etcd works. Backing up etcd means taking a snapshot of the database into a file.snap.
On my side, I delete my test namespace.
kubectl delete ns dev-demo-lan
Click the image to enlarge.
Click the image to enlarge.
Restoring the etcd database
To restore the database, you will first need to save an image of the backup and use the same one on each of the control planes.
In my case, I have three master nodes, and I will decide to use the backup that was created on my first server (here devk8sctp501).
To avoid any inconsistencies in the database, I will first make sure to stop all services associated with a control plane during the operation, and this for all nodes.
It is important that no control plane is active during the restoration, because as soon as the backup image is restored on a node, if the other nodes continue to function in parallel, the data will start to differ.
We will now switch to the root user on each control plane and move the manifest files from the directory /etc/kubernetes/manifests/ to /etc/kubernetes/backup using the following command: mv /etc/kubernetes/manifests/*.yaml /etc/kubernetes/backup/.
Click the image to enlarge.
Indeed, to ensure that the basic components of the cluster are running on the nodes, the kubelet agent installed on each server monitors this directory and executes all YAML files found within it. This is how Kubernetes "boots" up.
From the moment a YAML file is removed from its location, the associated pods are stopped by the kubelet agent, terminating the related services.
This may take a few minutes. You need to monitor the shutdown of etcd using the following command:
ps aux | grep etcd
Click the image to enlarge.
As long as it returns something, it indicates that etcd is active. Once there are no more etcd processes on each control plane, you can proceed with the operations.
(Besides etcd, other manifests have also been moved, cutting off the scheduler, API, and other system components associated with K8S. This is preferable during the unavailability of the etcd database).
But before that, you need to clear the original data; otherwise, the snapshot cannot be deployed.
You can either delete the data or move it aside. In my case, I consider the base data lost, so I delete it:
rm -rf /var/lib/etcd/*
Click the image to enlarge.
(As a reminder, the location of the data is visible in the manifest associated with etcd, mentioned at the beginning of this article).
You can do the same on each control plane.
Once this operation is complete, you can run the restore command on the first control plane.
ETCDCTL_API=3 etcdctl --data-dir="/var/lib/etcd/" --name=nom_server_01 --endpoints=https://ip_du_serveur_01:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key --initial-advertise-peer-urls=https://ip_du_serveur_01:2380 --initial-cluster-token=etcd-cluster-0 --initial-cluster=nom_server_01=https://ip_du_serveur_01:2380,nom_server_02=https://ip_du_serveur_02:2380,nom_server_03=https://ip_du_serveur_03:2380 snapshot restore /etc/kubernetes/backup/etcd-nom_serveur_01.snap
As with the backup command, you specify the IP address of the server, connection information using the key and certificate, and the snapshot to use as the source for restoration.
You also need to specify the name and IPs of the other servers that will participate in the cluster using the --initial-cluster option.
The --initial-cluster-token option is also important because it allows all servers to communicate with each other during the initialization (bootstrap) of each node.
Without these parameters, each control plane might think it's operating alone. Indeed, the snapshot does not contain the cluster configuration, only the values in the database. Therefore, you must specify during the restoration operation that it will be used in a clustered environment and indicate which other servers will participate.
In the commands, make sure to use the short names of the servers, as they appeared in the kubectl get node command.
You need to follow the same procedure on all control plane nodes, but be careful, I repeat, always use the same snapshot (and make sure you have purged the data beforehand).
This snapshot must therefore be copied from the node designated as the backup source to each other node using the following commands:
scp /etc/kubernetes/backup/etcd-nom_serveur_01.snap user@nom_serveur_02:/home/user
scp /etc/kubernetes/backup/etcd-nom_serveur_01.snap user@nom_serveur_03:/home/user
Click the image to enlarge.
Click the image to enlarge.
In summary, in my case, with three control plane nodes and the reference snapshot available on each server, my restoration commands are:
- On the first server (devk8sctp501):
ETCDCTL_API=3 etcdctl --data-dir="/var/lib/etcd/" --name=devk8sctp501 --endpoints=https://192.168.10.41:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key --initial-advertise-peer-urls=https://192.168.10.41:2380 --initial-cluster-token=etcd-cluster-0 --initial-cluster=devk8sctp501=https://192.168.10.41:2380,devk8sctp502=https://192.168.10.42:2380,devk8sctp503=https://192.168.10.43:2380 snapshot restore /etc/kubernetes/backup/etcd-devk8sctp501.snap - On the second server (devk8sctp502):
ETCDCTL_API=3 etcdctl --data-dir="/var/lib/etcd/" --name=devk8sctp502 --endpoints=https://192.168.10.42:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key --initial-advertise-peer-urls=https://192.168.10.42:2380 --initial-cluster-token=etcd-cluster-0 --initial-cluster=devk8sctp501=https://192.168.10.41:2380,devk8sctp502=https://192.168.10.42:2380,devk8sctp503=https://192.168.10.43:2380 snapshot restore /etc/kubernetes/backup/etcd-devk8sctp501.snap - On the third server (devk8sctp503):
ETCDCTL_API=3 etcdctl --data-dir="/var/lib/etcd/" --name=devk8sctp503 --endpoints=https://192.168.10.43:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key --initial-advertise-peer-urls=https://192.168.10.43:2380 --initial-cluster-token=etcd-cluster-0 --initial-cluster=devk8sctp501=https://192.168.10.41:2380,devk8sctp502=https://192.168.10.42:2380,devk8sctp503=https://192.168.10.43:2380 snapshot restore /etc/kubernetes/backup/etcd-devk8sctp501.snap
Once the restoration instructions have been applied to all control plane nodes, you can restore the manifests to their original location by running this command on each node.
mv /etc/kubernetes/backup/*.yaml /etc/kubernetes/manifests/
Proceed server by server. You will see that with the commands ps aux | grep etcd and ps aux | grep k8s, the system components gradually restart.
After a few minutes, you should be able to run commands like kubectl get node again and communicate with your cluster once more.
In my case, if I run a kubectl get ns now, I can see that my namespace dev-demo-lan, which was previously deleted, has been restored.
This clearly shows that the database has been restored.
Click the image to enlarge.
Using Ansible
As I explained in this article, I use Ansible extensively to automate certain tasks.
Even if I don't fully automate the restoration process, I have at least automated the backup process.
This allows me to easily initiate an etcd backup and ensures that I always have a snapshot of the database readily available.
I won't go into detail about how Ansible works or its directory structure here, but you can read the following article, in which I describe the logic I usually use.
Therefore, I have created a role role_k8s_etcd_backup consisting of the following tasks:
01-prerequisites.yml
This playbook is only used to install the etcd binaries and the directories that I use to store the snapshots.
I also create a restore folder.
---
- name: Install basic packages
become: yes
tdnf:
update_cache: yes
name: "etcd"
state: present
tags: role_k8s_etcd_backup.prerequis.package
when: "'k8sctp' in inventory_hostname"
- name: Creates backup folder
become: yes
file:
path: "/etc/kubernetes/backup"
state: directory
mode: 0770
recurse: yes
when: "'k8sctp' in inventory_hostname"
tags: role_k8s_etcd_backup.etcd.folder
- name: Creates restore folder
become: yes
file:
path: "/etc/kubernetes/restore"
state: directory
mode: 0770
recurse: yes
when: "'k8sctp' in inventory_hostname"
tags: role_k8s_etcd_backup.etcd.folder
02-create-script.yml
The second playbook 02-create-script.yml allows me to copy a backup script to each control plane node, which includes the commands explained previously.
---
- name: Récupérer l'adresse IPv4 de l'interface eth0
become: yes
shell: ip -4 addr show dev eth0 | grep inet | awk '{print $2}' | cut -d'/' -f1
register: ipv4_address_eth0
when: "'k8sctp' in inventory_hostname"
tags: role_k8s_etcd_backup.script.ip
- name: Afficher l'adresse IPv4 associée à eth0
debug:
msg: "L'adresse IPv4 de l'interface eth0 est {{ ipv4_address_eth0.stdout }}"
when: "'k8sctp' in inventory_hostname"
tags: role_k8s_etcd_backup.script.ip
- name: "Deploy etcd Backup script"
become: yes
template:
src: backup-etcd.sh.j2
dest: /etc/kubernetes/backup/backup-etcd.sh
mode: u=rwx,g=r,o=r
when: "'k8sctp' in inventory_hostname"
tags: role_k8s_etcd_backup.script.copy
It relies on a template backup-etcd.sh.j2, and here is its content:
#!/bin/bash
ETCDCTL_API=3 etcdctl --endpoints=https://{{ ipv4_address_eth0.stdout }}:2379 \
--cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt \
--key=/etc/kubernetes/pki/etcd/server.key \
snapshot save /etc/kubernetes/backup/etcd-{{ inventory_hostname }}.snap
03-launch-backup.yml
The third playbook 03-launch-backup.yml launches the script copied previously to create a snapshot on each server.
---
- name: "launch backup"
become: yes
shell: sh backup-etcd.sh
args:
chdir: /etc/kubernetes/backup/
when: "'k8sctp' in inventory_hostname"
tags: role_k8s_etcd_backup.backup.launch
04-create-restoration-script.yml
Finally, the last playbook 04-create-restoration-script.yml generates a restoration script, ready to use in the 'restore' folder.
---
- name: "create script restoration"
become: yes
set_fact:
min_hostname : "{{ inventory_hostname | lower }}"
when: "'k8sctp' in inventory_hostname"
tags: role_k8s_etcd_backup.restore.prerequis
- name: "Deploy etcd restoration script"
become: yes
template:
src: restore-etcd.sh.j2
dest: /etc/kubernetes/backup/restore-etcd.sh
mode: u=rwx,g=r,o=r
when: "'k8sctp' in inventory_hostname"
tags: role_k8s_etcd_backup.restore.create
It is also based on a template restore-etcd.sh.j2 that includes the etcd commands for restoring data.
#!/bin/bash
# Vérifiez si un argument a été fourni
if [ "$#" -ne 1 ]; then
echo "Usage: $0
You can find the role and associated files in my GitHub repository if you wish.
I just need to regularly run my role to have a backup of my database and have all the necessary commands available on my control planes as ready-to-use scripts.
Click the image to enlarge.
Conclusion
Ensuring that you have regular snapshots of your etcd database is a good practice that should not be neglected.
However, ensuring that you can restore it is just as important. Here's why you shouldn't hesitate to practice and regularly test the procedure. Because it is possible that this procedure will evolve over time or work differently with different versions of K8S.
Note that during the restoration phase, etcd and system components are unavailable, so your cluster is no longer operational. However, active pods remain in their state on worker nodes. But no scheduling or management operations are possible.
Also note that once the etcd database is restored, Kubernetes will attempt to bring its resources back to the state they were in. If configuration changes have been made between the time you took the snapshot and the time you perform the restoration, these changes will be lost. A series of actions may then be triggered to revert to the state described in the snapshot.
Some components may not appreciate this, especially third-party drivers or add-ons that you may have installed on your cluster.
Each case is unique, and this article aims only to provide you with ideas for organizing your own strategy. In any case, don't hesitate to regularly run your scenarios.
Even though doing so in production is complex, you can, as I have done, reproduce your infrastructure on a development cluster to practice. Try to be as close to your production environment as possible; ideally, do it directly on the production environment at some point... but carefully assess the risk!