February 22, 2025

Implementing FinOps as Code: Enforcing Cloud Cost Management

Cloud Governance

Managing cloud costs effectively is a key challenge for modern organizations. Cloud services can quickly become a financial burden if not carefully monitored and optimized. This is where FinOps comes in—a financial operations framework that brings together finance, technology, and operations teams to manage cloud spending efficiently.

In this blog, we’ll first explore FinOps, its core principles, and how these principles can help organizations control cloud costs. Then, we’ll dive into two powerful tools, Open Policy Agent (OPA) and Gatekeeper, that help enforce these principles through policy-as-code. Finally, in the next step, we will walk through a hands-on implementation of these concepts.

What is FinOps?

FinOps is the practice of bringing financial accountability to the cloud, enabling cross-functional teams to manage cloud costs with efficiency, transparency, and speed. It combines financial and operational practices, ensuring that cloud spending is closely tied to business goals and that everyone in the organization has visibility into cloud costs.

|resize

At its core, FinOps empowers organizations to:

  • Make cloud costs visible to all teams
  • Enable teams to take ownership of their cloud spending
  • Optimize costs while maintaining agility

The Six FinOps Principles

The FinOps Foundation has defined six core principles that guide organizations in adopting best practices for cloud financial management. Let’s take a look at these principles and their implications:

1. Teams Need to Collaborate

FinOps is not just a finance function—it’s a cross-functional practice involving finance, technology, product, and business teams. Collaboration is essential for making timely, informed decisions on cloud usage and cost management. Since cloud costs are dynamic and operate on a per-resource, per-second basis, teams must work together in near real-time to improve efficiency and innovation.

2. Decisions Are Driven by Business Value of Cloud

Rather than focusing solely on aggregate spend, decisions about cloud usage should be based on the business value of the cloud. Unit economics, value-based metrics, and trade-offs between cost, quality, and speed help drive decisions that align with the business’s goals. Cloud should be viewed as a driver of innovation and not just a cost center.

3. Everyone Takes Ownership for Their Cloud Usage

Cloud costs should not be hidden behind the finance department; engineers, developers, and teams should take ownership of their cloud usage. This means taking responsibility for cost-effective architecture, resource usage, and optimization decisions from the beginning of the software development lifecycle.

4. FinOps Data Should Be Accessible and Timely

Cloud cost data needs to be easily accessible and shared across teams in real-time. Transparent, consistent visibility into spend drives better utilization and helps teams make quick adjustments to prevent overspending. Fast feedback loops and trend analysis help identify issues early and optimize cloud usage effectively.

5. A Centralized Team Drives FinOps

While cloud cost management is a shared responsibility, a centralized FinOps team plays a critical role in establishing best practices, policies, and processes. This team facilitates collaboration, drives financial planning, and ensures everyone is aligned around cloud cost goals. A central team also helps with rate negotiations and optimization at scale, freeing up engineering teams to focus on optimizing their own environments.

6. Take Advantage of the Variable Cost Model of the Cloud

The cloud’s variable cost model—where pricing is based on actual usage—offers tremendous opportunities for cost optimization. Rather than sticking to static long-term plans, organizations should embrace agile, iterative planning and proactive system design. Continuous adjustments in cloud optimization should replace reactive clean-ups, allowing businesses to maximize value while minimizing unnecessary costs.

What Are OPA and Gatekeeper?

With these principles in mind, the next question is: how do we enforce these principles in a real-world cloud environment? Here’s where Open Policy Agent (OPA) and Gatekeeper come into play.

What is Open Policy Agent (OPA)?

OPA is an open-source policy engine that enables you to define and enforce policies across various systems, including cloud platforms and infrastructure-as-code (IaC) tools. OPA allows you to write policies using a declarative language called Rego, which can be integrated into your deployment pipeline to ensure that cloud resources meet your cost, security, and operational requirements.

|resize

In the context of FinOps, OPA helps ensure that policies for cost optimization and cloud resource management are consistently applied. It can be used to enforce rules such as ensuring that resources are tagged with cost-related metadata or that certain high-cost services are only deployed when absolutely necessary.

What is Gatekeeper?

Gatekeeper is an extension of OPA, specifically designed for Kubernetes environments. It provides a way to enforce policies for Kubernetes resources and ensure that deployments align with organizational standards, including cost-related requirements. With Gatekeeper, Kubernetes administrators can define policies that enforce best practices for resource provisioning and scaling within clusters.

Gatekeeper integrates with OPA and makes policy enforcement in Kubernetes easier, ensuring that cloud-native workloads follow cost-efficient practices while remaining agile and flexible.

FinOps as Code in Practice

Let’s see FinOps as Code, using OPA and Gatekeeper, in action. Here’s an overview of what we’ll do:

  1. Set Up Your Azure Environment (Resource Group, AKS, and necessary permissions)
  2. Install and Configure Gatekeeper (OPA) on AKS
  3. Create Cost Management Policies (Rego rules to enforce FinOps principles)
  4. Deploy and Test Policy Violations (See the policy in action)

⚠️ Note: This guide is for demonstration purposes and the covered configuration choices do not adhere to best practices for production scenarios.

Prerequisites

Before diving into the next steps, ensure you have the following prerequisites in place:

  • Azure Subscription with Owner Permissions: You’ll need an active Azure subscription with Owner permissions to create and manage resources in Azure.
  • Azure CLI: Install Azure CLI (version 2.57.0 or later) for interacting with Azure services from the command line. You can install Azure CLI by following the instructions at Microsoft’s official documentation.
  • Kubectl and Kubectl Login: Ensure kubectl is installed no your system, along with kubelogin to log in to Azure Kubernetes Service (AKS) using Entra ID credentials. You can install kubectl and kubelogin by following the instructions in this documentation.
  • Visual Studio Code (optional): Have Visual Studio Code installed on your system for editing files and managing your project. You can download Visual Studio Code from here.

Set Up Your Azure Environment

Since we’re focusing on cost management, we’ll deploy Azure Kubernetes Service (AKS) as a sandbox. We’ll also configure an Azure Container Registry (ACR), as this helps demonstrate cost-related governance (e.g., enforcing image reuse instead of pulling from external sources).

Step 1: Open your terminal and log in, using the az login command. After, set the correct subscription, by using the command below:

az account set --subscription "<your-subscription-id>"

Step 2: Let’s create a Resource Group that holds our resources, that we’ll create in the next steps. Run the command below:

az group create --name FinOps-RG --location westeurope

Step 3: Next, we’ll create a small basic AKS cluster with system-managed identities, to minimize costs. Run the command below:

az aks create --resource-group FinOps-RG \
  --name FinOpsAKS \
  --node-count 2 \
  --enable-managed-identity \
  --enable-addons monitoring \
  --generate-ssh-keys

Step 4: Once the AKS cluster has been created, connect to the cluster by running the command below:

az aks get-credentials --resource-group FinOps-RG --name FinOpsAKS

Install and Configure Gatekeeper (OPA)

Now our cluster has been created, we’ll install and configure OPA Gatekeeper. OPA Gatekeeper allows us to enforce policies at the Kubernetes admission controller level.

Step 5: Install Gatekeeper on AKS, by running the command below:

kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml

Step 6 (optional): Once applied, you may want to verify the installation by running the command below:

kubectl get pods -n gatekeeper-system

Define Cost Management Policies with Rego

Now, let’s create an example policy to enforce FinOps best practices. In this example we’ll create a policy to enforce the use of resource tagging for cost tracking.

Step 7: Create a new file require-tags.rego, with the content below:

package k8srequiredtags

violation[{"msg": msg}] {
    input.review.object.metadata.labels.costcenter == ""
    msg := "All workloads must have a 'costcenter' label for cost tracking."
}

Step 8: Apply the constraint template, by running the command below:

kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper-library/master/library/general/requiredlabels/template.yaml

Step 9: To ensure that all workloads have a costcenter label, helping track expenses at a team level, create the constraint by running the command below:

kubectl apply -f - <<EOF
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
  name: require-costcenter-label
spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Pod"]
  parameters:
    labels:
      - key: "costcenter"
EOF

Test the Policy

We’re now going to test the policy, by deploying a pod without the required label, and by deploying a compliant pod.

Step 10: First, deploy a pod without the required label, by running the command below:

kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
  name: untagged-pod
  labels:
    app: test
spec:
  containers:
  - name: nginx
    image: nginx
EOF

Step 11: This should be blocked. We can check the violations, by running the commands below:

kubectl get constrainttemplates
kubectl get K8sRequiredLabels -o json

Step 12: Now, let’s deploy a compliant pod. The command below should not be blocked:

kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
  name: tagged-pod
  labels:
    app: test
    costcenter: "finops-team"
spec:
  containers:
  - name: nginx
    image: nginx
EOF

Deleting the Resources to prevent Ongoing Costs

Once you’ve finished exploring OPA, it’s important to clean up to avoid unnecessary consumption costs. You can easily delete the AKS cluster using the Azure CLI by following the steps below.

Step 13: Delete the AKS cluster:

az aks delete --resource-group FinOps-RG --name FinOpsAKS --yes --no-wait

Step 14: Delete the resource group:

az group delete --name FinOps-RG --yes --no-wait

Closing Words

As organizations increasingly embrace FinOps to optimize cloud spending, enforcing cost governance through automation becomes essential. By leveraging Open Policy Agent (OPA) and Gatekeeper, we’ve demonstrated how policy-as-code can help organizations align with FinOps principles, ensuring transparency, accountability, and efficiency in cloud cost management. From defining policies that enforce proper resource tagging and cost allocation to preventing unnecessary high-cost deployments, FinOps as Code empowers teams to take ownership of their cloud usage while maintaining agility and innovation.

Whether you’re just starting your FinOps journey or looking to enhance your cloud cost governance, integrating OPA and Gatekeeper into your cloud infrastructure offers a powerful way to ensure compliance and cost efficiency at scale. If you’re interested in diving deeper, consider exploring additional resources on FinOps best practices, OPA policy design, and cost management automation:

Thank you for taking the time to go through this post and making it to the end. Stay tuned, because we’ll keep continuing providing more content on topics like this in the future.

Author: Rolf Schutten

Posted on: February 22, 2025