Operating Argo CD
local graph
Chapter 3 — Operating Argo CD
Section titled “Chapter 3 — Operating Argo CD”We will start this chapter by installing Argo CD with Kustomize using high availability (HA) manifests and go through some configuration options that we will perform while following the GitOps approach. We will make changes in the ConfigMap of a live Argo CD installation to see how we can modify different settings of Argo CD in a GitOps manner.
Then, we will look at the different Argo CD components, see what changes were introduced by the HA manifests, and what else we can do to make our installation a highly available one. While a Kubernetes cluster has a multi-control plane and worker nodes, it can still fail. Due to this, we will learn how to prepare for disaster recovery and move our installation from one cluster to another, including all the state.
Finally, we will discover what metrics are being exposed and how we can make the setup notify end users or send a custom hook to a CI/CD system when an application synchronizes successfully or not.
In this chapter, we will cover the following topics:
- Declarative configuration
- Setting up an HA installation
- Planning for disaster recovery
- Enabling observability
- Notifying the end user
Technical requirements
Section titled “Technical requirements”For this chapter, you will need access to a Kubernetes cluster. However, this time, local ones will not be enough. This is because we will be using the HA manifests, which require multiple nodes to run on so that the Pods can be spread between them. Any cluster with at least three nodes will do; the cloud provider doesn’t matter. In my case, I will be using an EKS cluster from AWS, which you can set up easily with a tool such as eksctl (https://eksctl.io). You can think of this as a production-ready installation.
This time, we are going to install Argo CD on the cluster using Kustomize, so you will need to install it as one of your tools (https://kubectl.docs.kubernetes.io/installation/kustomize/). You will also need kubectl (https://kubernetes.io/docs/tasks/tools/#kubectl).
We are also going to make changes to some Git repositories, so Git needs to be installed (https://git-scm.com/book/en/v2/Getting-Started-Installing-Git), as well as a code editor such as Visual Studio Code (VS Code) (https://code.visualstudio.com). You will also need an account on a Git-hosted platform such as GitHub and must be familiar with working with Git commands to create commits and pull and push to remote.
The code for this chapter can be found at the book’s companion GitHub repository within the ch03 folder.
Declarative configuration
Section titled “Declarative configuration”There are multiple ways to install Argo CD in a cluster. For one, we can directly apply its manifests, which are located at https://github.com/argoproj/argo-cd/blob/master/manifests/install.yaml – this installs the latest version. However, there are also manifests that are generated for each version, such as https://github.com/argoproj/argo-cd/blob/v2.0.0/manifests/install.yaml. Using kubectl, you will need to apply the raw manifests, so the link will be a little bit different (you will need to click on the Raw button after going to the preceding links):
kubectl apply -f https://raw.githubusercontent.com/argoproj/argo-cd/v2.0.0/manifests/install.yamlUse the official Helm chart located at https://github.com/argoproj/argo-helm/tree/master/charts/argo-cd. This option was already covered in Chapter 2, Getting Started with Argo CD, along with AutoPilot.
Another possibility is that, with Kustomize, similar to what’s in the Argo CD repository, we have Kustomize folders (the ones where you will find a kustomization.yaml file, such as https://github.com/argoproj/argo-cd/tree/master/manifests/base). We are going to look at this option in more detail, including how to configure it and how to make it manage itself (this time, not with AutoPilot). Apart from this, we have Kustomize manifests for an HA installation. We will explore these next.
HA installation with Kustomize
Section titled “HA installation with Kustomize”For Kustomize, I currently have version 4.3.0 on my machine. You can find out your current version by running the following command:
kustomize versionThe output of the preceding command should look similar to the following:
{Version:kustomize/v4.3.0 GitCommit:cd17338759ef64c14307991fd25d52259697f1fb BuildDate:2021-08-24T19:24:28Z GoOs:darwin GoArch:amd64}The code for the Kustomize installation can be found at the book’s companion GitHub repository in the ch03/kustomize-installation folder.
Follow these steps:
- Create a repository where you will keep the installation configuration. This will follow the GitOps approach as every change will be done with a pull request. Because we are trying to put all our demos in the same repository for simplicity, the installation is in a folder. However, it is recommended to be in a separate repository. To use the benefits of GitOps, it is recommended not to push changes directly but to do them via pull requests so that they can be peer-reviewed.
- In the repository, create a new folder called
resources. - Inside the
resourcesfolder, add a new file callednamespace.yaml. This is where we will set the namespace where Argo CD will be installed. This is the file’s content:apiVersion: v1kind: Namespacemetadata:name: argocd - Directly in the root of the repository that you created earlier, add a new file called
kustomization.yamlwith the following content. As you can see, this points to thev2.1.1HA manifests of Argo CD (this is the latest version at the time of writing) and also references thenamespace.yamlfile we just created:apiVersion: kustomize.config.k8s.io/v1beta1kind: Kustomizationnamespace: argocdbases:- github.com/argoproj/argo-cd/manifests/ha/cluster-install?ref=v2.1.1resources:- resources/namespace.yaml - From the root of the repository, run the following command. The first part,
kustomize build ., will generate the manifests, while the second part,kubectl apply -f -, will take the manifests and apply them to the cluster in a declarative manner:kustomize build . | kubectl apply -f -
The output should start with something like this (there are many more lines; we have just provided the first seven so that you can verify this worked correctly):
namespace/argocd createdcustomresourcedefinition.apiextensions.k8s.io/applications.argoproj.io createdcustomresourcedefinition.apiextensions.k8s.io/appprojects.argoproj.io createdserviceaccount/argocd-application-controller createdserviceaccount/argocd-dex-server createdserviceaccount/argocd-redis-ha createdserviceaccount/argocd-redis-ha-haproxy created- Commit and push everything to your remote repository.
If we have a valid installation, the next step would be to check the UI, which we can do with port-forward (you can use another port if needed):
kubectl port-forward svc/argocd-server -n argocd 8085:80Open your browser to https://localhost:8085; you should see the login page, which we already discussed in Chapter 2, Getting Started with Argo CD, and how to connect (and change the admin password). You will probably get a certificate warning because Argo CD is using self-signed certificates, but at this time, there should be no risk in visiting the website. For a production installation, you would also need a LoadBalancer service to be created with a certificate attached so that you can offload TLS to it.
In the next section, you will learn how to turn Argo CD into an application that can be managed via Argo CD itself, allowing for easy and declarative configuration updates.
Argo CD self-management
Section titled “Argo CD self-management”Argo CD can manage itself in the same way it manages other applications from the cluster. This is similar to what AutoPilot (https://argocd-autopilot.readthedocs.io/en/stable/) does under the hood. In this section, we will create an Argo CD application that points to the folder where we have our Kustomize manifests. This way, Argo CD will start monitoring that repository and folder for changes. Any new commits we make to the folder will be applied automatically.
First, we must create a file called argocd-app.yaml in our repository with the following content. An Argo CD application is made up of three parts: destination, which is where the manifests are applied, project, which we use to create specific restrictions (for example, this application should only deploy resources to a cluster and a specific namespace), and the source repository, which where it takes the manifests, including the branch and repo folder:
apiVersion: argoproj.io/v1alpha1kind: Applicationmetadata: name: argocdspec: destination: namespace: argocd server: https://kubernetes.default.svc project: default source: path: ch03/kustomize-installation repoURL: https://github.com/PacktPublishing/ArgoCD-in-Practice.git targetRevision: mainNow, we are going to apply this application with kubectl:
kubectl apply -f argocd-app.yaml -n argocdThe output should be similar to the following:
application.argoproj.io/argocd createdBy creating this application, we are telling Argo CD that, in the the book’s companion GitHub repository, in the ch03/kustomize-installation folder, some manifests should be applied. These are the manifests for the Argo CD installation. In terms of the control loop, the state that we desire is the state from the cluster, so after the observe state phase, there should be no actions to take. The main thing is that from now on, Argo CD monitors the repository every 3 minutes (by default) and checks for new commits. If it finds any, it will recalculate the manifests and try to apply them to the cluster. This is the mechanism through which Argo CD can manage itself.
If you have stopped port-forward, which we enabled earlier, you can reenable it with the following command:
kubectl port-forward svc/argocd-server -n argocd 8085:80Then, if you go to https:// localhost:8085, you will see your first application that has been synchronized by Argo CD, which is Argo CD itself:

Figure 3.1 – Argo CD managed by Argo CD
Now, let’s look at some simple configuration updates we can apply automatically to Argo CD by creating a commit and pushing it to remote.
Configuration updates
Section titled “Configuration updates”Since version 2.1 of Argo CD, we have a new setting in the main ConfigMap that allows us to modify the default interval that’s used to check for new updates on Git repositories. Every 180 seconds, it checks if new commits have been pushed. We can modify this using the timeout.reconciliation parameter. Before this parameter was introduced, we had to change StatefulSet of the application controller to set a different value with the –app-resync flag (which has been deprecated since version 2.1).
To update this reconciliation timeout, we will create a new folder called patches, at the same level as the resource folder. Inside it, we will create a new file called argocd-cm.yaml. We are not replacing the entire ConfigMap; instead, we are applying some patches to it – in this case, just the timeout.reconciliation field. The content of this new file will be as follows:
apiVersion: v1kind: ConfigMapmetadata: name: argocd-cmdata: timeout.reconciliation: 300sWe also need to update the kustomization.yaml file by adding a reference to the change that we made for our ConfigMap. The file should now look like this:
apiVersion: kustomize.config.k8s.io/v1beta1kind: Kustomizationnamespace: argocdbases: - github.com/argoproj/argo-cd/manifests/cluster-install?ref=v2.1.1resources: - resources/namespace.yamlpatchesStrategicMerge: - patches/argocd-cm.yamlNext, we need to create a commit that contains the new argocd-cm.yaml file and the change we made to kustomization.yaml and then push it to the remote repository. Argo CD is checking for new commits every 180 seconds, so it will identify the change and apply it. After doing so, it will check for new commits every 300 seconds.
The documentation says that it is not enough to update this setting – we also need to manually restart the argocd-repo-server deployment for the new configuration to be loaded. This can be done using the following command:
kubectl rollout restart -n argocd deployment argocd-repo-serverThe output should be similar to the following:
deployment.apps/argocd-repo-server restartedHaving Argo CD manage itself is useful as we can make changes to its running installation, from small configuration updates, as we just saw, to upgrading the version. And all these will be applied automatically by Argo CD, making it become an application like any other managed by Argo CD. The normal GitOps flow should include creating a pull request with your changes so that they can be reviewed by your peers. In our case, for simplicity, we are pushing directly to the remote default branch, so they will be applied right away. Next, we will discover how an HA installation can be achieved by looking at all the different Argo CD components and the changes we will apply to them.
Setting up an HA installation
Section titled “Setting up an HA installation”Since we have already used the HA option with Kustomize, let’s see what components are installed, how they handle the HA part, and if there is anything else we can do:
- API server: This handles all the exterior interaction, so if you are using the CLI or the UI or creating a client, you will communicate with the API. The HA manifests already set two instances for this pod.
- Repository server: This is responsible for creating the final manifests to apply to the cluster; manifests generation is complicated because of all the templating supported by Argo CD, such as Helm 2 or 3, Kustomize, and Jsonnet. The HA manifests come with two replicas.
- Application controller: This is where the work is initiated, where the control loop is implemented, and application sync takes place. Initially, you were only able to have one instance, but now, you can have one instance per cluster shard. The HA manifests use one instance of the controller.
- Redis cache: Manifest generation is an expensive operation and Argo CD tries to save the manifests in a Redis instance; there is no problem if the cache fails as it can be recalculated, but do expect a performance penalty. Here, we probably have the biggest changes between the normal and HA manifests. In HA mode, we get an additional deployment of HAProxy and three replicas for Redis – that is, one master and two slaves.
- Dex server: This is responsible for user authentication when you use external identity providers such as Security Assertion Markup Language (SAML), OpenID Connect (OIDC), or Lightweight Directory Access Protocol (LDAP). It is optional, but if you want to, for example, connect your GitHub or Google account to Argo CD, you will need this component.
Let’s discuss each in terms of HA.
API server
Section titled “API server”The API server is the entry point for all our requests, regardless of whether they are coming from the UI, CLI, or a custom client, such as curl. It doesn’t have any state, so we can scale it up or down, depending on the load. This also means we can keep an HA installation just by changing the number of replicas for its deployment. By using the HA option, we got two replicas, but let’s see how we can update this number to three and what other changes need to be made.
Besides the replicas, optionally, we could update the ARGOCD_API_SERVER_REPLICAS environment variable so that it has the same number of replicas we are using. This is used when calculating a limit for brute-force password attacks. Let’s say that if, for one instance, 30 concurrent login requests would be a lot to trigger a different response from the server, for three instances, the load will be spread, so you will only get 10. This means that the more instances we have, the lower we need to go with the limit. Now, if you don’t update the variable, the application will still work, but if you do update it, then it will be safer.
To have three replicas of the argocd-server deployment, we need to do the following. Create a new file called argocd-server-deployment.yaml in the patches folder. Its content should be as follows:
apiVersion: apps/v1kind: Deploymentmetadata: name: argocd-serverspec: replicas: 3 template: spec: containers: - name: argocd-server env: - name: ARGOCD_API_SERVER_REPLICAS value: '3'Then, we need to add the entry to the kustomization.yaml file so that our change will be taken into consideration. I am not going to show the whole file here, just the section starting from patchesStrategicMerge:
patchesStrategicMerge: - patches/argocd-cm.yaml - patches/argocd-server-deployment.yamlNow, as usual, we must create a git commit with these two files and then push it to remote so that Argo CD can see the new revision and apply the changes to the installation.
Repository server
Section titled “Repository server”The repository (repo) server is an important component that generates the resources to apply to a cluster. Usually, in our GitOps repos, we don’t use simple manifests; instead, we use templating engines such as Helm, Jsonnet, and Kustomize. This component is transforming those templates into manifests that are ready to be applied with the kubectl apply command. It goes and fetches the content of the Git repo, based on which it knows whether to use Helm, Kustomize, or something else (for example, if it finds a file called Chart.yaml, it knows it is a Helm chart). After it finds out what the templating engine is, it runs commands such as helm template and kustomize build to generate the final manifests. For Helm, it may need to do a helm dep update beforehand to fetch any external dependencies.
A lot is going on in this repo server application, which means that if we run multiple instances of it, we will be able to generate more manifests in parallel. It also makes sense to provide enough resources so that these containers don’t get killed because of out-of-memory errors or throttled on the CPU. If you have thousands of applications that have been deployed with Argo CD, you can easily run more than 10 instances of the repo server and assign something such as 4 to 5 CPUs and 8 to 10 GB of memory to each instance. From the HA manifests, we have two instances already, but we are going to modify it so that it has three. We will not place any resource requests or limits because we are using local clusters, but for real ones, this is highly recommended.
Note – Repo server performance
My experience with repo servers is highly impacted by the usage of Helm 2. When we migrated most of our charts to Helm 3, we ran some tests and realized that the move significantly reduces the manifest generation time (at least in some situations, which still occur pretty often in our setup). So, you should take the preceding container resource recommendations with a pinch of salt and do your own calculations.
Another important parameter that we may need to modify is the timeout for the templating engine. Argo CD forks the Helm or Kustomize commands and sets a 90-second timeout for these operations. Sometimes, that may not be enough, such as when Kustomize is using big remote bases or when Helm needs to template big charts such as kube-prometheus-stack (https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack – it used to be known as prometheus-operator) or istio (https://istio.io/latest/docs/setup/install/helm/). So, you can run some tests and see what would work for you. If you want to increase the timeout, you can use the ARGOCD_EXEC_TIMEOUT environment variable.
Create a new file called argocd-repo-server-deployment.yaml in the patches folder with the following content, where 3 replicas have been set for the repo server and 3 minutes have been set for the templating timeout:
apiVersion: apps/v1kind: Deploymentmetadata: name: argocd-repo-serverspec: replicas: 3 template: spec: containers: - name: argocd-repo-server env: - name: "ARGOCD_EXEC_TIMEOUT" value: "3m"We also need to update the kustomization.yaml file so that it includes a reference to the new file we just created in the patches folder (I am adding the patchesStrategicMerge section here, which includes the change and not the entire content of the file):
patchesStrategicMerge: - patches/argocd-cm.yaml - patches/argocd-server-deployment.yaml - patches/argocd-repo-server-deployment.yamlCreate the Git commit and push it to remote, so that Argo CD can then update the repo server deployment.
Application controller
Section titled “Application controller”Initially, this was the component that couldn’t have more than one replica because there was a control loop that was the initiator of all synchronizations. Thus, having more than one replica would introduce the possibility of two or more synchronizations starting for the same application at the same time. But starting with version 1.8, you can have more than one replica, with each instance taking care of a part of the clusters registered in Argo CD.
For example, if you have nine clusters where Argo CD is installing applications and you start three application controllers, then each controller will take care of three of those clusters. Scaling them is not necessary for an HA installation, but it does help in this direction because the failure of one controller only affects part of the clusters, not all of them. It also helps the overall performance of Argo CD by splitting the load into multiple instances.
To tell the Argo CD application controller how many shards (or instances) it can have, you can use the ARGOCD_CONTROLLER_REPLICAS environment variable from its StatefulSet. Let’s look at what an overlay for the Kustomize installation set to 3 replicas (which would mean three shards) for the controller would look like. Create a file called argocd-application-controller-statefulset.yaml under the patches folder with the following content:
apiVersion: apps/v1kind: StatefulSetmetadata: name: argocd-application-controllerspec: replicas: 3 template: spec: containers: - name: argocd-application-controller env: - name: ARGOCD_CONTROLLER_REPLICAS value: "3"Now, update the patchesStrategicMerge section of the kustomization.yaml file, like this:
patchesStrategicMerge: - patches/argocd-cm.yaml - patches/argocd-server-deployment.yaml - patches/argocd-repo-server-deployment.yaml - patches/argocd-application-controller-statefulset.yamlCreate the commit, push to remote, and Argo CD will take care of the rest.
There might be scenarios when there is only one destination cluster, meaning all your applications, regardless of whether they are dev, test, QA, or prod, will be installed on one cluster only. In this case, it doesn’t make sense to have more than one instance of application controllers, but you should allocate a large amount of CPU and memory for the container. You should check the --operation-processors, --status-processors, and --kubectl-parallelism-limit flags in the official documentation (https://argo-cd.readthedocs.io/en/stable/operator-manual/high_availability/#argocd-application-controller) and set higher values for them to allow your instance to handle more applications.
Note – Replicas in environment variables
This pattern is used in at least two places: the API server and the application controller. Here, the number of replicas is injected into the container with an environment variable. This way, it is a lot simpler compared to calling the Kubernetes API from each instance to find out the number. Even with the additional overhead for the developer to make sure they update both places, it is still worth doing it like this.
Redis cache
Section titled “Redis cache”Redis is used by Argo CD as a throwaway cache, meaning the system still works if Redis is not responding, gives some error, or isn’t installed at all, though this might affect its performance. So, this is an optional component, but a highly recommended one.
This is because the manifests that were generated from a Git repository will be kept in the Redis cache, so if Redis is missing, they will have to be recreated at every synchronization request. The cache is only dropped if there are new commits to the Git repo (think of the commit’s SHA as the key). If the cache is lost, everything needs to be recreated, which means the application still works but with a performance hit.
The HA installation comes with a StatefulSet with three replicas for Redis – one master and two slaves. It also comes with an HAProxy deployment that sits in front of Redis. If the Redis master fails for some reason and one of the slaves is promoted as the new master, HAProxy will make this transparent to the client applications.
In terms of HA, the Redis installation has a very good setup, so there is no need to make any changes.
Note – Redis manifests
The Redis manifests that are used by Argo CD are generated from a Helm chart located at https://github.com/DandyDeveloper/charts/tree/master/charts/redis-ha. When we use Kustomize or the simple manifest options, the Helm chart is already templated and transformed into simple resources. The Helm installation has a redis-ha chart declared as a dependency, so it is consumed directly.
Dex server
Section titled “Dex server”Dex (https://github.com/dexidp/dex) is used to delegate authentication when an external system is involved, such as when using something such as OIDC. Because dex keeps an in-memory cache, we can’t use more than one instance; otherwise, we risk inconsistencies. What we risk if it goes down is not being able to log in using the external system. This is not critical as Argo CD continues to do all the necessary reconciliation, so it should still have connectivity to the Git repos and the destination Kubernetes clusters, which means its work will not stop. The login downtime should be temporary because by being installed as a one-replica deployment, the controller will restart the instance (sometimes, it will do this with our help when node issues are involved).
If you only use local users (we will learn more about them in Chapter 4, Access Control) or the admin special user, then you can disable the dex installation by setting the number of replicas to zero.
HA is one of the best practices for reducing the risk of interruptions for your services. Even if your Argo CD instance is down for a small period, you don’t want this to happen while doing any kind of production deployment or rollback. So, it becomes critical that we eliminate the single points of failure by building redundancy and resilience into Argo CD components. Luckily, we get HA manifests out of the box. Once we understand how each component is modified to become highly available, we can take more steps toward improved service, from using even more replicas than the default to splitting the Kubernetes clusters where we are deploying our applications to more application controllers. Next, we are going to look at disaster recovery, which is about getting the system back to a working state after it becomes inoperative. This can help us put things back in order where HA was not enough.
Planning for disaster recovery
Section titled “Planning for disaster recovery”Argo CD doesn’t use any database directly (Redis is used as a cache), so it looks like it doesn’t have any state. Earlier, we saw how we can have a high availability installation, done mostly by increasing the number of replicas for each deployment. But we also have application definitions (such as the Git source and destination cluster) and details on how to access a Kubernetes cluster or how to connect to a private Git repo or a private Helm one. These things, which make up the state of Argo CD, are kept in Kubernetes resources – either native ones, such as secrets for connection details, or custom ones for applications and application constraints.
A disaster may occur due to human intervention, such as the Kubernetes cluster or the Argo CD namespace being deleted, or maybe some cloud provider issues. We may also have scenarios where we want to move the Argo CD installation from one cluster to another. For example, maybe the current cluster was created with a technology that we don’t want to support anymore, such as kubeadm (https://kubernetes.io/docs/ setup/production-environment/tools/kubeadm/), and now we want to move to a cloud provider-managed one.
A question may have popped up in your head: “ but I thought this is GitOps, so everything is saved in Git repos, which means that it is easy to recreate?” First, not quite everything gets saved into Git repos. For example, when registering a new cluster in Argo CD, we do so imperatively by running a command so that such details are not in Git (which is OK for security reasons). Second, recreating everything from the GitOps repos may take a lot of time – there might be thousands of applications, hundreds of clusters, and tens of thousands of Git repos. A better option might be to restore all the previous resources from a backup instead of recreating all of them from scratch; that would be much faster.
Installing the CLI
Section titled “Installing the CLI”Argo CD provides a utility part of the main CLI (the argocd admin subcommand) that can be used to create the backup (export all related data) to a YAML file or import data from an existing one. The CLI can be found in the main Docker image, or it can be installed separately.
To install the v2.1.1 version of the CLI, run the following commands (this is the macOS version; for other options, please check the official page: https://argo-cd.readthedocs.io/en/stable/cli_installation/):
curl -sSL -o /usr/local/bin/argocd https://github.com/argoproj/argo-cd/releases/download/v2.1.1/argocd-darwin-amd64chmod +x /usr/local/bin/argocdargocd version --clientIf everything went OK, then the output of the preceding commands should show the Argo CD client version, like so:
argocd: v2.1.1+aab9542 BuildDate: 2021-08-25T15:14:05Z GitCommit: aab9542f8b3354f0940945c4295b67622f0af296 GitTreeState: clean GoVersion: go1.16.5 Compiler: gc Platform: darwin/amd64Now that we have installed the CLI, we can use it to create the backup.
Creating the backup
Section titled “Creating the backup”Now, we can connect to our cluster and create the backup. You should be connected to the cluster where you have the Argo CD installation (your kube context for pointing to the cluster). Run the following command, which will create a file with a custom name based on the current date and time (this way, you can run it daily or even more frequently):
argocd admin export -n argocd > backup-$(date +"%Y-%m-%d_%H:%M").ymlEven if we had a simple installation with just one application (Argo CD itself), you can see that the backup is quite a big file (it should contain almost 1,000 lines). This is also because the Argo CD application is a pretty big one (we deployed many resources) and it keeps a history of everything it has synchronized. You will find the backup file that I generated for the [HA installation in this book’s Git repository (https](the book’s companion GitHub repository in the ch03/disaster-recovery folder.
Next, we should take this backup file and save it on a cloud storage system (such as AWS S3, Azure Blob, or Google Cloud Storage), encrypt it, and have access policies around it. This is because, for a real installation, a lot of sensitive information will be stored there, including access to your production Kubernetes clusters.
Restoring on a different cluster
Section titled “Restoring on a different cluster”To restore a backup, you need to install Argo CD in the destination cluster. This is because, in the backup, we have its configuration, as well as all the ConfigMaps and Secrets, so everything we changed for the initial installation should be present. However, the backup doesn’t store the actual Deployments or StatefulSets. This means they need to be installed before the backup is restored. The same goes for CustomResourceDefinitions – we will have all the instances of Application and AppProject, but we won’t have the definitions of those custom resources.
So, in the new cluster, perform the same installation we did previously in the HA installation with Kustomize section. After that, run the following command (you will need to change the filename so that it matches yours):
argocd admin import - < backup-2021-09-15_18:16.ymlNow, you should have a new installation with all the states (applications, clusters, and Git repos) you had when you created the backup. The only difference is that now, there is nothing in the Redis cache, so Argo CD will need to start recalculating all the manifests from the Git repos, which may affect the system’s performance for the first couple of minutes. After that, everything should be business as usual.
In this section, we saw that Argo CD tools are easy to automate, from creating regular backups to restoring them on newly created clusters. It is important to have a backup strategy and to do restoration exercises from time to time. We should be prepared for when a disaster occurs and have the necessary runbooks so that we can execute them with the same results, regardless of whether it is 2:00 A.M. or 2:00 P.M. Disasters are rare, so we will come across a lot of situations in our day-to-day operations. This could be an increased number of applications to sync or a specific version of a YAML templating tool leading to timeouts or even an unresponsive system. For this, we need to have a good strategy for observability. We will explore this in the next section.
Enabling observability
Section titled “Enabling observability”Observability is important because it can provide answers about the system’s health, performance, and behavior. When working in a big setup with thousands of applications with tens of teams deploying their monoliths and microservices to Kubernetes, there’s a big chance that things won’t always go as smoothly as you would expect. There is always some wrong setting, an older version that wasn’t supposed to be used, an immutable field trying to be updated, many applications needing to be synchronized at the same time, a team trying to use a private repo without setting its SSH key, or big applications that can cause timeouts.
Luckily, Argo CD exposes many metrics that allow us to understand the system, if it is underutilized or overutilized, and what to do about it. It also gives us ways to directly alert the development teams that are responsible for specific applications when something goes wrong, such as a failed synchronization. The alerts that we will create can be split into two directions – one for the team responsible for operating Argo CD and one for the teams taking care of the microservices.
In this section, we will learn how to monitor Argo CD with Prometheus, which has become the default choice for monitoring dynamic environments such as microservices running in containers on Kubernetes. Prometheus, with its focus on reliability, is one of the best tools to find out the current state of your system and to easily identify possible issues.
Monitoring with Prometheus
Section titled “Monitoring with Prometheus”Like Kubernetes became a standard for container orchestration, Prometheus became a standard for monitoring. It was the second project to enter Cloud Native Computing Foundation (CNCF), with Kubernetes being the first. In the cloud-native world, we have an operator for running Prometheus in Kubernetes (like Argo CD i s an operator for GitOps) calle d Prometheus Operator (https://prometheus-operator.dev). Argo CD components expose metrics in Prometheus format, making it easy to install Prometheus Operator in the cluster and start scraping those endpoints. There is a Helm chart you can use to install it (usually, this is done in a separate namespace called monitoring): https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack.
After the installation, we will need to tell Prometheus where it can find the endpoints that expose the metrics. To do that, we can use the custom ServiceMonitor resource (https://prometheus-operator.dev/docs/operator/design/#servicemonitor). Three services should be scraped – one for the application controllers, one for the API servers, and one for the repo servers – thus covering all the Argo CD components. You can find the ServiceMonitor resources in the official documentation at https://argo-cd.readthedocs.io/en/stable/operator-manual/metrics/#prometheus [-operator. We also saved a copy of them in our Git re](the book’s companion GitHub repository po (the book’s companion GitHub repository in the ch03/servicemonitor folder.
You can apply the files by putting them in a Git repo, inside a folder, and then creating an application that points to it so that you can apply them using GitOps.
After we have the ServiceMonitor resources in place and the s craping process has begun, there is a Grafana dashboard (https://grafana.com/grafana/dashboards), which is offered as an example in the official documentation at https://argo-cd.readthedocs.io/en/stable/operator-manual/metrics/#dashboards, that you can use. Please follow the official documentation on how to import a dashboard to see how you can add this to your own Prometheus Operator installation: https://grafana.com/docs/grafana/latest/dashboards/export-import/#import-dashboard. We will cover monitoring from two different perspectives – one for the team taking care of Argo CD, which we are calling the operating team, and the second for the team building applications, which we are calling the microservices team.
Metrics for the operating team
Section titled “Metrics for the operating team”To perform synchronizations, Argo CD uses the repo servers and the controllers. These are the most important pieces that we need to monitor and taking good care of them will allow us to have a good, performant system. Various metrics can help us understand their behavior. So, let’s explore a few of them.
OOMKilled
Section titled “OOMKilled”Over time, we realized that the most valuable metric for these two components was not something exposed by Argo CD but the out-of-memory (OOM) kills that were performed by the node OS on the containers trying to use too many resources. This is a good indicator of whether the container resources that you have set are not enough or if you are using a parameter that sets a value that’s too big for parallelism. The Argo CD documentation provides a good explanation of when OOM can occur and what parameters to use to reduce parallelism: https://argo-cd.readthedocs.io/en/stable/operator-manual/high_availability/. In terms of the repo server, too many manifests are generated at the same time, while for the application controller, too many manifests are being applied at the same time.
You can use the following query to get alerts about these events. It checks if the containers have been restarted in the last 5 minutes and whether the last terminated reason was OOMKilled (this query comes from this old and valuable Kubernetes thread: https://github.com/kubernetes/kubernetes/issues/69676#issuecomment-455533596):
sum by (pod, container, namespace) (kube_pod_container_status_last_terminated_reason{reason="OOMKilled"}) * on (pod,container) group_left sum by (pod, container) (changes(kube_pod_container_status_restarts_total[5m])) > 0If you receive such alerts once or twice a week, that might not be that bad, and you can wait a few more weeks to see what happens. If they occur a couple of times per day, either for the repo servers or the controllers, you should take action. Here are a few things you can do:
- Increase the number of replicas for
Deployment/StatefulSetso that when an application synchronization needs to occur, the load will be spread to more instances. - Set more resources – both CPU and memory – for the containers.
- Reduce the value of the
--parallelismlimitparameter for the repo servers and the value of the--kubectl-parallelism-limitparameter for the controllers.
OOM is related to how much work the controller needs to do to reconcile the application’s state. This means that if you don’t have deployments for a few days, this probably won’t happen, while if you start synchronizing many applications at once, you may start receiving OOM alerts. If this is the case, then we should see a correlation with the load metrics we have defined in the system. We will look at those next.
System load metrics
Section titled “System load metrics”There are a few metrics that can reveal the load of the system. Here, we will look at one that’s relevant for repo servers and one that’s relevant for application controllers.
The repo servers are tasked with fetching the Git repos’ content and then creating the manifests based on the templating engine that was used. After they create the final manifests, their work is continued by the application controllers. We have seen that too many manifests using apply at the same time can lead to OOM issues, but what happens when we have a lot of requests for fetching the content of Git repos? In this case, there is a metric called argocd_repo_pending_request_total that goes up and down (in Prometheus, we would call it a gauge), depending on how many requests are pending on the repo server instances. Of course, the number should be as close to zero as possible, showing that the current number of repo instances can handle the load. However, this is not a problem if it goes up for a short period. Problems can occur when there is a big value for a long period, so that’s what you should look out for.
Note – Scaling repo servers with HPA
If you are already thinking about scaling repo servers with HPA based on this gauge, please join the discussion on this thread as it turns out it is not that easy: https://github.com/argoproj/argo-cd/issues/2559.
On the application controller side, there is another important metric for showing the system load – that is, argocd_kubectl_exec_pending. This shows how many apply and auth commands are pending to be executed on the destination clusters. The maximum number can be equal to the --kubectl-parallelism-limit flag because that’s how many parallel threads can start commands on the destination clusters. It is not a problem if it reaches the maximum for a short period, but problems such as synchronization taking a lot of time can occur when the value remains big for a longer period of time.
Metrics for the microservices teams
Section titled “Metrics for the microservices teams”If you are trying to apply the idea of platform teams that create self-service platforms for development teams, then you should allow the development teams to monitor, get alerts, and take action when something goes wrong with their live deployments. One way to do this is to allow them to set up alerts for the Argo CD applications that are used to take their microservices to production. Two metrics can provide value for development teams. One can be used for the synchronization status, especially if there was a failure during the synchronization process. The other can be used for the application’s health status, especially the Degraded status, which means something is not functioning as expected.
Application synchronization status
Section titled “Application synchronization status”The synchronization status is useful to alert on so that the team doesn’t need to pay attention to the UI or run regular commands via the CLI to find out the status of the new version deployment. This is especially true when this is done several times per week, not to mention if you do it more frequently. The teams can set up alerts for the applications that they manage so that if they fail to synchronize the new version of their Docker image or some other change they made to the manifests, then they will receive an alert. The argocd_app_sync_total metric can be used for this.
The following query can be used to alert you about any applications that have changed their synchronization statuses to Failed in the last 5 minutes. The query only looks for applications from the argocd namespace and that start with accounting (which would be of interest to an accounting team):
sum by (name) (changes(argocd_app_sync_total{phase="Failed", exported_namespace="argocd", name=~"accounting.*"}[5m]))>0If there are no issues, we shouldn’t get any results. However, if we do get any applications with a Failed synchronization status, we should start investigating the reasons.
Application health status
Section titled “Application health status”The health status is different than the synchronization status because it can be modified independently of a synchronization. We are usually looking for a Degraded status, which happens when something is not functioning correctly, such as if you asked for three replicas in your StatefulSet, but only two are up and running while the third one is still initializing after a long period, or it was terminated and now it is not being scheduled and remains Pending. Such scenarios can occur at any time while the application is running in production and it is not directly related to a synchronization event. The metric for tracking this is argocd_app_info. You can use the following query to track the Degraded status of an Argo CD application from the argocd namespace if its name starts prod but it doesn’t end with app (this can be useful when the intermediary applications that were created by the app-of-apps pattern use the app suffix: https://argo-cd.readthedocs.io/en/stable/operator-manual/cluster-bootstrapping/#app-of-apps-pattern):
argocd_app_info{health_status="Degraded",exported_namespace="argocd",name=~"prod.*",name!~".*app"}Getting applications with Degraded statuses in the results is a clear sign that some problems in the cluster are preventing your application from functioning properly, so it needs to be checked.
Next, we will learn how to notify the user about events that are happening in Argo CD, such as whether an application was deployed successfully. This can be achieved with different tools. We are going to look at the ones that are Argo CD-specific, such as the Argo CD Notifications project and the custom webhooks built into Argo CD.
Notifying the end user
Section titled “Notifying the end user”To synchronize applications, Argo CD can work in two different ways. First, it can work manually so that a new commit to the GitOps repo will not have any direct effect unless you trigger the synchronization manually via the CLI, by using the UI, or by using an API call. The second mode, which I think is the most used one, is that after a push to the repo, Argo CD will start to automatically reconcile the cluster state so that it matches the one we declared.
The developers that performed the state changes are interested in the outcome of the reconciliation – they want to know if their microservices are up and running correctly or if they have some problems with the new configuration or the new container image.
Earlier, we learned how to monitor the synchronization process using Prometheus and the metrics Argo CD exposes for application health and synchronization status. However, there is another way we can notify development teams that their microservices have some failures or when everything went perfectly: the Argo CD Notifications project. This was built especially with Argo CD in mind and can provide more useful details to its users. You can learn more about the Argo CD Noti fications project at https://github.com/argoproj-labs/argocd-notifications.
Installing Argo CD Notifications
Section titled “Installing Argo CD Notifications”Like Argo CD, the Notifications project can be installed in three different ways: via a Helm chart (https://github.com/argoproj/argo-helm/tree/master/charts/argocd-notifications), using simple manifests (https://github.com/argoproj-labs/argocd-notifications/tree/master/manifests), or via Kustomize. We will go with the Kustomize option and install it using Git [Ops mode. All the code for the notifications we will buil](the book’s companion GitHub repository d can be found at the book’s companion GitHub repository in the ch03/notifications folder.
In the same repo that you used to install Argo CD, create a new folder called notifications. Inside that folder, create a file called kustomization.yaml and add the following content. As you can see, we kept the same argocd namespace; there is no reason to create another one as this is not a standalone application. However, it needs an instance of Argo CD to work with (in other words, we won’t have an instance of Argo CD Notifications if Argo CD isn’t installed):
apiVersion: kustomize.config.k8s.io/v1beta1kind: Kustomizationnamespace: argocdbases: - github.com/argoproj-labs/argocd-notifications/manifests/controller?ref=v1.1.1You should commit the file to your repo and then push to remote so that we can create the application file. Name this argocd-notifications-app.yaml and place it in the top folder this time (it should be at the same level as the argocd-app.yaml file that we created earlier in this chapter when we made Argo CD self-managed). Here is the content of the file (just make sure that you replace path and repoURL with your own values):
apiVersion: argoproj.io/v1alpha1kind: Applicationmetadata: name: argocd-notificationsspec: destination: namespace: argocd server: https://kubernetes.default.svc project: default source: path: ch03/notifications repoURL: https://github.com/PacktPublishing/ArgoCD-in-Practice.git targetRevision: main syncPolicy: automated: {}Now that we’ve created the file, we need to apply it with the following command (don’t forget to commit and push it to your repo for future reference):
kubectl apply -n argocd -f argocd-notifications-app.yamlAfter applying it, you should have the Argo CD Notifications application installed by Argo CD in your cluster. In the UI, it should look like this:

Figure 3.2 – The Argo CD Notifications application in the Argo CD UI
Next, we’ll learn how to start GitLab pipelines from Argo CD Notifications. This can be done to update the deployment status of our application in various tracking systems and can be seen as a way to close the GitOps reconciliation loop.
Starting a pipeline
Section titled “Starting a pipeline”The following is a good article on the Argo blog that ex plains how to set the proper configurations to send notific ations via emails: https://blog.argoproj.io/notifications-for-argo-bb7338231604. In the official documentation, there are more examples of notification services such as Slack (https://argocd-notifications.readthedocs.io/en/latest/services/slack/), Microsoft Teams (https://argocd-notifications.readthedocs.io/en/latest/services/teams/), Telegram (https://argocd-notifications.readthedocs.io/en/latest/services/telegram/), and a few others. There are also good explanations on how to use webhooks to set statuses on GitHub commits (https://argocd-notifications.readthedocs.io/en/latest/services/webhook/#set-github-commit-status) or custom hooks to post data (https://argocd-notifications.readthedocs.io/en/latest/services/webhook/#set-github-commit-status).
We want to come up with something new, which is not easy because a lot of useful scenarios have already been covered. So, let’s look at an example where we start a pipeline in GitLab CI/CD. GitLab is being used more and more these days for CI/CD because it enables pipelines where everything runs on containers in a cloud-native way with its Kubernetes runner: https://docs.gitlab.com/runner/executors/kubernetes.html. For our demo, we will not be using the Kubernetes executor; we will be using the shared one provided by GitLab, which is based on docker-machine: https://docs.gitlab.com/runner/executors/docker_machine.html. The pipeline we are creating will run the same on both Kubernetes and Docker machine r unners.
First, create a user on GitLab by going to https://gitlab.com/users/sign_up. Once you have the account up and running, go ahead and create a project. There should be a New project button somewhere in the top-right corner of the GitLab UI. Choose Create blank project on the next page, after which you should be able to set the project’s name.
In my case, I named it resume-manual-pipeline and I set the project to Public so that I can share it with everyone. You can set it however you wish:

Figure 3.3 – Creating a new GitLab project
Once we’ve created the project, before adding any code to it, we need to set up an easy authentication method for our Git repos with an SSH key. First, go to the top-right corner, locate the last link on the right, and click on it – you should see the Preferences menu item. This will take you to a page where you have a big menu on the left, including an SSH Keys entry. Clicking it will take you to a page where you can add your SSH key (follow Steps 1, 2, and 3 in the following screenshot to get to the SSH Keys page). There will be a link that explains how to generate a new one. After you have created it, you can paste the Public one in the textbox (not the Private one), give it a title, and click Add key:

Figure 3.4 – How to get to the SSH Keys page
Now that we have the correct setup, we can clone, pull, and push our Git repos without any problems.
Now, getting back to our repo, we should clone it locally and open it in an editor. We will build a pipeline with one job named update-deploy-status. It will use an alpine Docker image and it will run a dummy script that will show the application’s name, status, and the commit SHA that was applied by Argo CD. The idea is that this job can make a couple of changes, such as setting a tag to the Git commit or putting a Production label on some tasks after a synchronization event occurs. Ours is a dummy one to explain the link between the event and the pipeline, but yours can be more advanced. So, create a new file near the README.md file named gitlab-ci.yml and set the following pipeline definition:
update-deploy-status: stage: .post script: - echo "Deploy status $APPLICATION_DEPLOY_STATUS for Application $APPLICATION_NAME on commit $APPLICATION_GIT_COMMIT" image: alpine:3.14 only: variables: - $APPLICATION_DEPLOY_STATUS - $APPLICATION_NAME - $APPLICATION_GIT_COMMITNote – Manual GitLab pipeline
A manual start can be done by using the condition that certain variables need to be present for the job to run (see the only: part). This allows us to also start the pipeline from the GitLab UI, which is a good way to debug it.
Next, we will create a commit with the .gitlab-ci.yml file we created and push it to the remote repo. Before we define the webhook, we need a way to authenticate the Argo CD Not ifications call to our GitLab pipeline. We will use a pipeline trigger token for this: https://docs.gitlab.com/ee/api/pipeline_triggers.html. We will create it from the GitLab UI. On the project’s main page, in the left menu, there is a Settings entry. Upon clicking it, you will see the CI/CD item in its submenu. Clicking on it will take you to a page with many sections that you can expand, one of which is Pipeline triggers. There, you can create a new trigger; I named mine Argo CD Notifications Webhook. After clicking on Add trigger, the token will appear:

Figure 3.5 – Creating a pipeline trigger – give it a name and click the Add trigger button
We now have a token that we can use to authenticate when we want to start the pipeline from the Argo CD Notifications webhook. In the Pipeline triggers section, we already have an example of what the webhook should look like – all we need to do is adjust it with our configuration. TOKEN is the one we just created. In our case, REF_NAME is the main branch. Regarding the variables, we will populate them in the Argo CD Notifications template:
curl -X POST \ -F token=TOKEN \ -F "ref=REF_NAME" \ -F "variables[RUN_NIGHTLY_BUILD]=true" \ https://gitlab.com/api/v4/projects/29851922/trigger/pipelineFor the next few steps, we can f ollow the official documentation on how to create the webhook in Argo C D Notifications (https://argocd-notifications.readthedocs.io/en/stable/services/webhook/).
We need to modify the argocd-notifications-cm ConfigMap, which we can do by making a change in Git. In the notifications folder, which we created when we installed Argo CD Notifications, we need to add a new folder called patches. Inside this, we will add a file called argocd-notifications-cm.yaml, where we will define the trigger, when to send the webhook, and what the webhook should look like, which involves a notification template. We named the trigger on-sync. We are activating it when the sync ends up as Succeeded, Error, or Failed and we are linking it to the gitlab-webhook template. Next, the template is linked to the gitlab webhook, which shows that an HTTP POST request will be sent with the required variables to start our job, with ref set to main, as well as the authentication token (you will need to set this to a real value – the one that you created earlier):
apiVersion: v1kind: ConfigMapmetadata: name: argocd-notifications-cmdata: trigger.on-sync: | - when: app.status.operationState.phase in ['Succeeded', 'Error', 'Failed'] send: [gitlab-webhook] service.webhook.gitlab: | url: https://gitlab.com/api/v4/projects/29851922/trigger/pipeline headers: - name: Content-Type value: multipart/form-data template.gitlab-webhook: | webhook: gitlab: method: POST body: ref=main&token=<token-goes-here>&variables[APPLICATION_DEPLOY_STATUS]={{.app.status.sync.status}}&variables[APPLICATION_NAME]={{.app.metadata.name}}&variables[APPLICATION_GIT_COMMIT]={{.app.status.operationState.operation.sync.revision}}We need an entry in the kustomization.yaml file to reference this new file:
apiVersion: kustomize.config.k8s.io/v1beta1kind: Kustomizationnamespace: argocdbases: - github.com/argoproj-labs/argocd-notifications/manifests/controller?ref=v1.1.1patchesStrategicMerge: - patches/argocd-notifications-cm.yamlNow, create the commit, push it to remote, and make sure that the Argo CD application was synchronized to include our changes. We should now be ready to update one of our application custom resources to subscribe to the webhook we created. In this case, we have the applications in Git, but they are not tracked directly by Argo CD, so if we change them, we still need to apply them manually. In Chapter 5*, Argo CD Bootstrap K8s Cluster*, we will look at the app-of-apps pattern, which allows us to store all the application definitions in Git. For now, though, we are OK with performing these small changes manually.
Earlier, in the ch03 folder, we created an argocd-app.yaml file. Here, we are going to modify it so that it includes the annotation that will specify that it is subscribed to the gitlab webhook with the on-sync trigger (see the highlighted code):
apiVersion: argoproj.io/v1alpha1kind: Applicationmetadata: annotations: notifications.argoproj.io/subscribe.on-sync.gitlab: "" name: argocdspec: destination: namespace: argocd server: https://kubernetes.default.svc project: default source: path: ch03/kustomize-installation repoURL: https://github.com/PacktPublishing/ArgoCD-in-Practice.git targetRevision: mainWe need to apply this file manually with the following command:
kubectl apply -f argocd-app.yamlThe output should look like this:
application.argoproj.io/argocd configuredWith that, we’ve done all the setup so that every change and synchronization we make on the argocd application will start a pipeline in our GitLab project. Here, we can modify the argocd-cm ConfigMap we added earlier in this chapter when we discussed Argo CD self-management. After we push the change to remote, we should have a pipeline that provides an output similar to the following:

Figure 3.6 – The GitLab job’s output from the pipeline that was started by Argo CD Notifications
In this section, we went through quite a lengthy demo where we created a small GitLab pipeline with one job that gets triggered with a notification when a failed or successfully performed synchronization occurs in an Argo CD application. The other option would have been to regularly query the application sync status from a pipeline when a new commit was performed until it gets to the state we are waiting for and then have to perform the actions we need. These notifications allow us to embrace the full pull nature of GitOps and not have to create workarounds that make it look like a push method.
Summary
Section titled “Summary”We started this chapter by installing Argo CD with Kustomize. We went with a cloud provider-managed cluster because we needed more nodes to experiment with an HA deployment. We experienced how Argo CD can update itself and how we can make configuration changes to our installation. While a production Kubernetes cluster is highly available and a cloud provider will manage it for us, there are still scenarios when disasters can happen, so we need to have a working disaster recovery strategy. We saw how we can create backups of the Argo CD state and then restore it in a new cluster.
Observability is an important topic and we discussed which metrics can be used to monitor an Argo CD installation, from the OOM container restarts to what a microservice team needs to watch out for. We finished by learning how to link the result of a synchronization to a pipeline so that everything will be automated.
In the next chapter, we are going to discover how we can bootstrap a new Kubernetes cluster in AWS using Argo CD, including how to set up applications in the newly created cluster, such as external DNS and Istio.
Further reading
Section titled “Further reading”To learn more about the topics that were covered in this chapter, take a look at the following resources:
- The Argo proje ct’s official blog (this includes Argo CD and other projects from the Argo organization): https://blog.argoproj.io.
- For an HA installation, i t is also important that the Pods are spread across nodes (and availabil ity zones). Go to https://kubernetes.io/docs/concepts/scheduling-eviction/as sign-pod-node/ to see how this is done with node affinity.
- Observability with Prometheus: https://prometheus.io/docs/introduction/overview/.