Declarative YAML manifests

Declarative YAML manifests

Move from 'Doing' to 'Declaring.' Master the heart of Kubernetes operations and learn why Infrastructure as Code (IaC) is the key to scalable production systems.

Declarative YAML: The Heart of Infrastructure as Code

In the early days of sysadmin work, if you wanted to change a server, you’d log in via SSH and run a series of commands: apt-get install, vim config, systemctl restart. This is called Imperative management. You are giving the computer a list of steps to follow. The problem? If you have 100 servers, you have to run those steps 100 times, and if one step fails, your servers are all in different, inconsistent states.

Kubernetes is different. It is built on the Declarative philosophy.

In Kubernetes, you don't tell the cluster how to do something. You describe what you want the final result to be (the "Desired State"), and the cluster works in the background to make it so. We do this using YAML Manifests. In this lesson, we will master the art of writing and managing these manifests, and we will understand why this "Infrastructure as Code" (IaC) approach is the secret to managing thousands of apps with ease.


1. Imperative vs. Declarative: The Restaurant Metaphor

Imagine you are in a restaurant.

The Imperative Approach:

You walk into the kitchen and say: "Chef, I want you to take two slices of bread. Toast them for 2 minutes. Take a block of cheese, slice it into 3 pieces. Put the cheese on the bread. Microwave it for 30 seconds."

  • Problem: If the chef is busy, or if there is no microwave, the whole process breaks because you were too specific about the steps.

The Declarative Approach:

You sit at the table and say: "I want a Grilled Cheese Sandwich."

  • Benefit: The chef knows what a grilled cheese is. They look at the available tools (pan, toaster, microwave) and the available ingredients (cheddar, swiss, sourdough) and they find the best way to deliver the result.
  • In K8s, the Deployment YAML is your order. The Control Plane (The Chef) handles the execution.

2. Anatomy of a Manifest: The Four Required Fields

Every Kubernetes YAML file, regardless of its purpose, must have these four top-level fields:

  1. apiVersion: Which version of the Kubernetes API are you talking to? (e.g., v1, apps/v1, networking.k8s.io/v1).
  2. kind: What is the object type? (Pod, Service, Deployment, Secret).
  3. metadata: Data that helps identify the object uniqueness, like name, namespace, and labels.
  4. spec: This is the most important part. It is where you define the Desired State. (e.g., which image to use, how many replicas to run).

3. The Power of kubectl apply

The primary tool for declarative management is kubectl apply -f <filename>.

Unlike kubectl create, which identifies an error if the object already exists, apply is Idempotent.

  • If the object doesn't exist, it creates it.
  • If it does exist, it compares the new YAML with the current state and only updates the parts that changed.

The "Three-Way Merge" Magic:

When you run apply, K8s performs a three-way comparison between:

  1. The YAML file on your computer.
  2. The last version you applied (stored in an annotation in etcd).
  3. The actual "Live" state in the cluster.

This ensures that if another developer changed a setting manually, your apply won't accidentally overwrite their change unless you explicitly change that field in your YAML.


4. Organizing your Manifests: Best Practices

For a production app like a FastAPI backend with a Next.js frontend, you will have dozens of YAML files. How do you keep them organized?

A. Directory Segregation

Don't put everything in one file. Use folders:

  • /k8s/base: Core app manifests.
  • /k8s/database: Config for SQL/NoSQL.
  • /k8s/monitoring: Prometheus/Grafana configs.

B. Dry Runs and Validation

Before you "Apply" a change that could potentially break production, always validate it.

# Check if the YAML is syntactically valid
kubectl apply -f my-app.yaml --dry-run=client

# See EXACTLY what will change in the cluster before it happens
kubectl diff -f my-app.yaml

5. Visualizing the IaC Workflow

graph LR
    Dev["Developer"] --> Git["Git Repository (Source of Truth)"]
    Git --> CI["CI/CD Pipeline (GitHub Actions)"]
    CI --> Test["Validation & Dry Run"]
    Test --> Prod["Kubernetes Cluster (kubectl apply)"]
    Prod --> Observe["Monitoring (Grafana)"]
    Observe --> Dev

This loop is called GitOps. Since your infrastructure is just text files in Git, you can track every change, review it in a Pull Request, and roll back any change by simply hitting "Revert" in Git.


6. Practical Example: A Multi-Container YAML

Sometimes a Pod needs two containers. For example, your FastAPI app and a "Sidecar" that handles sensitive AI encryption for AWS Bedrock.

apiVersion: v1
kind: Pod
metadata:
  name: ai-secure-pod
spec:
  containers:
  - name: main-api
    image: myrepo/fastapi-app:latest
  - name: crypto-sidecar
    image: myrepo/encryption-agent:latest
    env:
    - name: ENCRYPTION_KEY
      valueFrom:
        secretKeyRef:
          name: ai-secrets
          key: crypto-key

Writing this in a declarative file makes it easy for any other developer to understand exactly how these two containers interact.


7. AI Implementation: Self-Documenting Infrastructure

When you use LangChain to build complex agents, your infrastructure requirements (Memory, GPUs, API Keys) can grow quickly.

By using declarative YAML, you are "Documenting" your infrastructure as you build it.

  • A year from now, if you need to recreate the environment on a different cloud provider, you don't need to remember 50 kubectl commands.
  • You just run kubectl apply -f k8s/ and your entire AI empire is rebuilt in minutes.

Tip: Use Helm for Templates

As your YAMLs grow, you'll start noticing repetitive code. In Module 11, we will learn how to use Helm, the "Package Manager" for Kubernetes, to turn these YAMLs into reusable templates.


8. Summary and Key Takeaways

  • Declarative: Describe the "What," not the "How."
  • YAML: The language of Kubernetes. Every manifest needs Version, Kind, Metadata, and Spec.
  • Idempotency: kubectl apply can be run a thousand times and will only change what is necessary.
  • IaC: Versioning your infrastructure in Git provides safety, auditability, and speed.
  • GitOps: The ultimate expression of declarative management.

In the next lesson, we will look at the other side of the coin: Imperative commands with kubectl, and when it’s actually better to use them.


9. SEO Metadata & Keywords

Focus Keywords: Kubernetes declarative manifests tutorial, imperative vs declarative K8s, kubectl apply vs create, infrastructure as code K8s best practices, three-way merge Kubernetes, GitOps for AI developers.

Meta Description: Move beyond manual server management and master the power of Declarative Infrastructure in Kubernetes. Learn why YAML manifest files and the 'apply' workflow are the keys to building scalable, version-controlled, and professional cloud environments.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn