GitOps and Mutating Policies: The Tale of Two Loops
Do policies that mutate or generate resources violate GitOps principles?
In this blog post, I will show you how policy-based resource management can be complementary to GitOps, what benefits it provides, and how to use Kyverno to mutate and generate rules with popular GitOps tools like Flux and ArgoCD.
Kubernetes Control Loops
The Controller pattern is a foundational concept in Kubernetes. Controllers are driven by declarative configurations that define the system’s desired state and run a control loop reconciling the current state with the desired state.
Kubernetes has several built-in controllers, like pod controllers. Kubernetes is extensible and supports custom controllers that can run inside of Kubernetes.
The GitOps Control Loop
The GitOps pattern is another form of the controller pattern, where the desired state is versioned in Git, and the GitOps controller reconciles resources in clusters with resources declared in Git.
The size of the control loops matters, and the tighter and more self-contained the loop, the better. Tighter control loops are less error prone and more efficient, with fewer moving pieces. Tighter control loops can also offer greater security, as the attack surface is reduced when there are fewer dependencies on external systems.
The Policy Control Loop
Kubernetes offers many forms of policies, including API resources. Policy management solutions, like Kyverno and OPA/Gatekeeper, use dynamic admission controls to intercept API requests.
A Kubernetes policy controller is also a form of a control loop where the desired state is defined as a declarative policy. A policy controller applies policies to resource configurations in near real-time. Policies can be used to validate and block or flag insecure and misconfigured resources. Policies can also mutate, generate, and delete (cleanup) resources based on customizable criteria.
Maintaining State in Git
“I want all cluster states to be stored in git” is often stated as a reason for not using mutation or generation policies.
The goal of GitOps is to make the cluster state fully reproducible from Git and to store just enough to recover and track the state entirely.
For example, it does not make sense to store each Pod declaration in git as Kubernetes pod controllers like Deployments are used to manage the lifecycle of pods in a cluster. Hence, only pod controller declarations are stored in Git.
Similarly, policies can also be stored in Git and applied to clusters. A controller then watches the policy states, dynamically enforces required policies, and manages configurations.
The Advantages of Using Policies
Managing configurations using policies can bring numerous advantages. For instance, policies can simplify the configuration management process, enforce security measures, and promote best practices. In addition to these benefits, there are other advantages to using policies for configuration management.:
1. Just in Time Resource Management: policies can apply missing defaults and generate complete resources for security, isolation, multi-tenancy, or other concerns. Since this happens directly inside the cluster, it works with kubectl or any other Kubernetes client tool.
2. Tighter Security Controls: policy controllers, like Kyverno, register as dynamic admission controllers and monitor each API request. Since attackers will directly exploit security weaknesses within a cluster and bypass the CI/CD pipelines, admission controllers act as an essential line of defense.
3. Separation of Concerns: policies allow cleanly separating concerns across development, operations, and security roles. For example, some policies may be mandated by the security team, whereas the operations team may manage other policies. A policy controller consolidates and applies policies across all.
Avoiding Sync Errors with Server Side Apply (SSA)
Kubernetes Server Side Apply (SSA) is a feature that allows multiple controllers to collaborate on changes to a resource.
Both FluxCD and ArgoCD can leverage SSA to coordinate changes with policy engines and other mutating admission controllers.
Kyverno and Flux
Flux enables SSA by default, so there is nothing special to configure.
This git repository, from Stefan Prodan, contains a detailed demo of how to use Kyverno policies to mutate a pod security context:
This policy replaces all image tags with digests, which are immutable and more secure. Note that the policy does not perform any other form of image verification, like checking signatures or attestations:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: image-digest
annotations:
policies.kyverno.io/title: Convert tags to digests
policies.kyverno.io/category: Supply Chain Security
policies.kyverno.io/subject: Pod
policies.kyverno.io/minversion: 1.11.0
policies.kyverno.io/description: >-
Image tags are mutable and can be spoofed. This policy resolves
image tags to digests which are immutable.
spec:
validationFailureAction: Enforce
rules:
- name: replace-tag
match:
any:
- resources:
kinds:
- Pod
exclude:
all:
- resources:
namespaces:
- argocd
verifyImages:
- imageReferences:
- "*"
required: false
verifyDigest: true
mutateDigest: true
This policy allows the Kubernetes cluster auto-scaler to evict pods that use emptyDir by adding the annotation `cluster-autoscaler.kubernetes.io/safe-to-evict: true` if a pod contains an emptyDir volume.
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: add-safe-to-evict
annotations:
policies.kyverno.io/title: Add Safe To Evict
policies.kyverno.io/category: Other
policies.kyverno.io/subject: Pod
policies.kyverno.io/minversion: 1.6.0
policies.kyverno.io/description: >-
The Kubernetes cluster autoscaler does not evict pods that
use hostPath or emptyDir volumes. To allow eviction of these
pods the annotation cluster-autoscaler.kubernetes.io/safe-to-evict
must be set to `true`.
spec:
rules:
- name: annotate-empty-dir
match:
any:
- resources:
kinds:
- Pod
exclude:
all:
- resources:
namespaces:
- argocd
mutate:
patchStrategicMerge:
metadata:
annotations:
+(cluster-autoscaler.kubernetes.io/safe-to-evict): "true"
spec:
volumes:
- <(emptyDir): {}
This policy turns off the auto-mount of service account tokens:
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: service-account
annotations:
policies.kyverno.io/title: Disable Auto-Mount of Service Accounts
policies.kyverno.io/category: Other
policies.kyverno.io/subject: Pod
policies.kyverno.io/minversion: 1.6.0
policies.kyverno.io/description: >-
Kubernetes automatically mounts ServiceAccount credentials in each Pod.
The ServiceAccount may be assigned roles allowing Pods to access API resources.
Blocking this ability is an extension of the least privilege best practice and should
be followed if pods do not need to speak to the API server to function.
This policy ensures that mounting of these ServiceAccount tokens is blocked.
spec:
rules:
- name: disable-automount-sa
match:
any:
resources:
kinds:
- Pod
exclude:
all:
- resources:
namespaces:
- argocd
mutate:
patchStrategicMerge:
spec:
+(automountServiceAccountToken): false
Install ArgoCD
Note that a version greater than 2.10 is required:
You can also view the pod and deployment details using ArgoCD:
Since Kyverno policy reports are namespaced Kubernetes resources, you can also check the compliance of each resource directly in the ArgoCD UI!
Conclusion
This blog post highlights the importance of mutating policies in securing and operating clusters and provides a tutorial on using Kyverno policies with FluxCD and ArgoCD. The post offers practical examples, such as adding pod security context defaults, necessary annotations, and converting image tags to digests during admission controls, all of which make sense to centralize using policies. If you’re interested in exploring other mutation policies, you can find them at https://kyverno.io/policies/?policytypes=mutate.
Moreover, Kyverno also supports policies that generate resources, which can simplify self-service use cases for multi-tenancy and application isolation. To view examples of such policies, check out https://kyverno.io/policies/?policytypes=generate.
Managing configurations using policies can bring numerous advantages. For instance, policies can simplify the configuration management process, enforce security measures, and promote best practices, while maintaining separation of concerns across developers, operations, and security teams.
For those looking to maximize the value of running Kyverno in production, Nirmata Control Hub offers a robust solution and a free trial! Simply head to https://try.nirmata.io/ to get started.
Radhesh is Managing Partner of Arka Venture Labs. Arka Venture Labs is an Accelerator fund which assists Indian B2B Startups to foray into US by providing a combination of Funding, Mentoring and access to Silicon Valley Ecosystem. Arka Venture Labs was formed in August 2018 and has made 9 investments so far. Prior to starting Arka, Radhesh was Venture Advisor to Blume Ventures, focusing on early stage B2B Startups investments. Before this he was leading the Global Entrepreneur Program, for IBM India and South Asia. He exhibited strong leadership in steering the Startup initiative of IBM from scratch to one of the companies to be reckoned by the Startup ecosystem in India and generating strong revenues for IBM India Cloud business. He has helped many B2B startups scale in their journey by mentoring them, facilitating access to funds and customers.
He has core competency in evaluating startups leveraging technology and advising them on areas of improvement from business and technology standpoint. He conceptualized IBM India`s Startup challenge called IBM India Smartcamp and successfully executed the same. Radhesh has personally curated the startups for the finals, many of whom got funding either for the first time or for their subsequent rounds.He also worked with large enterprises in assisting them in identifying the next generation innovations through joint hackathons and startup challenges.
Prior to this role at IBM he was working as a Software Architect where he was designing Software solutions for Enterprise Clients, ISVs and System Integrators. He created many First of its kind solutions and led several key Sales wins for IBM. Radhesh has strong skills in building strategic relationships with Partner organizations.
Anubhav is VP of Business Development and Customer Success. He has 20+ years of experience in building and growing businesses across service provider, enterprise and commercial sectors. He has led functions in business development, product management, marketing, delivery and operations through his career, and most recently served as GM for the $250M Web-scale Services business at Cisco.
Anubhav is passionate about building new solutions and teams, and growing new market segments. At Cisco, he grew business 30-40% annually for many years while also building new offers, a world class team and a global delivery model.
Throughout his career, Anubhav has straddled technical, operational and business domains to bring new solutions around real-time analytics, operational assessments and network lifecycle management. Most recently, he was involved in bringing in new offers around recently launched Business Critical Services, a $2.5B business for Cisco. Before leaving Cisco, Anubhav signed off with a $350M multi-year deal built entirely around new solutions and engagement model with an innovative commercial structure.
Anubhav brings to Nirmata’s product development and organization an extensive experience developing both custom and standard subscription services, which was significantly formed by his time spent building analytics solutions at Cisco. This perspective on building bleeding edge solutions is evident in his business outlook, which recognizes that best solutions are built with the customers, by listening to them and partnering in risk taking when breaking new ground.
Anubhav holds bachelor’s degrees in both physics and electronics and telecommunications from Mumbai University and an MBA from San Jose State University.
Ritesh Patel, Founder & VP of Products
Ritesh Patel is co-founder of Nirmata and has 20+ years experience building and delivering enterprise software solutions and has led highly successful software and business development teams. Ritesh began his career in engineering for high tech firms, and has since migrated to the business side of the operation. In his founding of Nirmata, Ritesh sought to bring his broad spectrum of experience to a single previously unaddressed industry problem through the creation of a new business. To Nirmata’s leadership, Ritesh brings a rare skill set incorporating experience with the entire chain of software development activities. This background has contributed to Nirmata’s commitment to empowering all employees to do the hard work required to deliver tools that solve tough problems.
Prior to Nirmata, Ritesh led business development at Brocade, where he was responsible for defining the firm’s cloud strategy, and oversaw developments that advanced the entire cloud “as-a-service” market. Through cloud and security-related initiatives, Ritesh and his team at Brocade were able to package Brocade’s plethora of IT infrastructure products into enterprise-ready solutions including OpenStack and CloudStack that pioneered widespread cloud computing implementation. In addition to these technical achievements, Ritesh succeeded in creating an extensive partner ecosystem to efficiently match these solutions with urgent customer needs.
Ritesh has also held key technical positions at Trapeze Networks (where he created industry award-winning products), Nortel, and Motorola. Ritesh holds an MBA from UC Berkeley and a master’s degree in computer engineering from Michigan State University.
Damien Toledo, Founder & VP of Engineering
Damien Toledo is Co-Founder and Vice President of Engineering, overseeing research and development, operations, maintenance, and delivery of Nirmata products. Damien brings over 20 years experience leading global engineering teams and delivering Enterprise grade solutions.
Since 1998 when he arrived in Silicon Valley from France to pursue the possibilities of US startup culture, Damien has held a number of engineering positions at high tech firms, each of which playing a role in the concept development for Nirmata. Building on lessons learned in management transformation at Jetstream Communications in the early 2000s, Damien built the Meru Networks Network Management team and Network Management solution from the ground up as one of the firm’s original members. Meru Networks went public in 2010 (NASDAQ:MERU).
Subsequent to his work at Meru, Damien led the transformation of the engineering team at Netscout to build an agile organization. At Netscout, he championed the adoption of Continuous Integration best practices across a team of 200+ engineers and 7 development sites, which resulted in reducing the software release cycles by 300%. While at Netscout and together with Nirmata co-founder Jim Bugwadia, Damien oversaw the adoption of microservices while searching for solutions to operating quickly in the cloud, and developed the foundations for what would become Nirmata.
Damien holds a master’s degree in computer science from University of Technology of Compiègne.
Jim Bugwadia, Founder & CEO
Jim Bugwadia has 20+ years experience building and leading effective teams and has created software that powers communications systems around the world.
Jim was among the original architects and business leaders within Cisco’s cloud automation practice, where he helped grow revenues to over $250M. During Jim’s tenure, IDC recognized the practice as #1 in global cloud services.
Prior to his work at Cisco, Jim led engineering teams at startups including Pano Logic, a desktop virtualization startup recognized for its innovative design by Wired magazine; Trapeze Networks, a wireless pioneer; and Jetstream Communications, a telecom equipment manufacturer. Jim started his career developing C++ software at Motorola for cellular network infrastructure where his team launched the world’s first cellular telephony that used code division multiplexing to optimize radio frequency usage.
Jim’s passion is to simplify the use of complex systems by providing well designed products that drive mass adoption of new technologies. As software has become mission critical to all businesses, Jim and his co-founders started Nirmata to help enterprises automate the delivery and management of applications. Jim currently develops software in Java, Golang, and Javascript, and is a Certified Kubernetes Administrator who actively participates in Nirmata’s full product lifecycle.
Over the course of his career, Jim has logged over $1.3B in revenue, 6 patent filings, 8 major product launches, and 29 years experience coding.
Jim holds a bachelor’s degree in engineering from Chicago State University and a master’s degree in computer science from the University of Illinois at Chicago.
Sorry, the comment form is closed at this time.