[{"content":"Spec-Driven Development with Spec Kit In this post we are going to see what Spec-Driven development is and how GitHub&rsquo;s Spec Kit makes it easy to get started.\nWhat is Spec-Driven Development (SDD) Executable Specifications: Reverses the traditional &ldquo;code is king&rdquo; model by treating natural language specifications as the primary source of truth that directly generates implementation, rather than just serving as passive documentation. Constitutional Governance: Enforces immutable project principles through a &ldquo;Constitution&rdquo; that establishes non-negotiable rules before any coding begins. Structured AI Workflow: Replaces unstructured &ldquo;vibe coding&rdquo; with a disciplined, multi-stage pipeline: Specify &amp; Plan: Decouples the &ldquo;what&rdquo; (requirements) from the &ldquo;how&rdquo; (tech stack), converting vague ideas into structured Product Requirement Documents (PRDs). Tasks &amp; Implement: Breaks plans into parallelizable units of work and executes them in a strict Red-Green-Refactor loop where tests are written and verified before implementation code. Iterative &amp; Agnostic: Uses AI agents to progressively refine intent into concrete artifacts, creating technology-independent specs that can generate multiple distinct implementations. For example: Moving from React to Vue, from Go to Python, etc. by using the same core requirements. SDD vs &ldquo;Vibe Coding&rdquo; Limitations of &ldquo;Vibe Coding&rdquo;: Current AI coding often relies on &ldquo;one-shot&rdquo; prompting or unstructured chat loops, this degrades as complexity grows (lacking context, hard to maintain, loss of context, etc.). Structured Context Management: SDD replaces ephemeral chat history with persistent artifacts (spec files, plans, checklists), ensuring the AI agent retains full context of the project scope and constraints. From Generation to Engineering: Moves the focus from simply generating lines of code to engineering a system, requiring the AI to validate its own work against a pre-approved plan before execution. Reduction of Technical Debt: By enforcing planning and architectural review before code generation, SDD aims to prevent the &ldquo;spaghetti code&rdquo; often produced by unguided AI assistants. SDD Phases Constitution &amp; Specification (Phase 1): The developer establishes the &ldquo;rules of the road&rdquo; (coding standards) and the &ldquo;destination&rdquo; (functional requirements) without defining the specific technology stack yet. Technical Planning (Phase 2): The AI agent analyzes the spec to generate a detailed implementation plan, selecting libraries and architecture that adhere to the project&rsquo;s Constitution. Atomic Task Breakdown (Phase 3): The plan is converted into a list of discrete, manageable tasks (e.g: Create database schema, build API endpoint, etc.) that can be tracked or executed in parallel. Verified Implementation (Phase 4): The agent executes tasks individually, typically requiring a passing test or validation step for one task before proceeding to the next to ensure structural integrity. The &ldquo;Constitution&rdquo; concept Governance as Code: A foundational document (markdown file) that serves as the immutable &ldquo;system prompt&rdquo; for the project, dictating behavioral and technical boundaries for the AI agent. Non-Negotiable Constraints: Can enforce specific rules such as Always use Python, No external 3rd party libraries, or 100% test coverage required. Coding agent must adhere to this. Consistency Across Agents: Ensures that different AI models produce code that feels uniform and adheres to the same standards. Living Documentation: Unlike traditional wikis that often go ignored, the Constitution is actively read by the coding agent before every task, actively preventing architectural drift. Getting started Initialize repo once installed (installation instructions).\na) Greenfield: specify init &lt;PROJECT_NAME&gt;\nb) Brownfield: cd &lt;existing_project_folder&gt; &amp;&amp; specify init --here\nEstablish constitution: \/speckit.constitution\nAction: Creates the .specify\/memory\/constitution.md file.\nGoal: Define non-negotiable rules that the agent must follow. E.g: Always use Python.\nDefine intent (the spec): \/speckit.specify\nAction: Generates a detailed requirement document (PRD) in specs\/.\nGoal: Describe what you want to build and why. Focus on user stories, goals, and success metrics. Do not talk about tech stack here.\nRefine (optional but recommended): \/speckit.clarify\nAction: The AI interviews you about gaps in your spec.\nGoal: Fix underspecified areas. E.g: How should errors be handled?\nArchitectural Plan: \/speckit.plan\nAction: Generates plan.md and data-model.md.\nGoal: Define how to build it. This is where you specify the tech stack (Python, Postgres), libraries, and file structure.\nBreak Down Work: \/speckit.tasks\nAction: Creates tasks.md.\nGoal: Converts the plan into a checklist of small, atomic, parallelizable coding tasks. E.g: Create API endpoint X, create database schema, etc.\nExecute: \/speckit.implement\nAction: Writes the actual code.\nGoal: The agent iterates through the task list one by one. In strict mode, it will write a test, verify it fails (Red), write the code, and verify it passes (Green) before moving to the next task.\nExample run In this example we are going to build an intervals-workout timer web app.\nAttention\nThis is just an example, I haven&rsquo;t spent much time reviewing the prompts or outputs, this should be used to understand the process of working with Spec Kit, nothing else.\nInitialize the project from the terminal and open it in your coding agent:\nspecify init interval-timer\/ cd intervals-timer \/path\/to\/coding-agent-binary In your coding agent, create the consitution file:\n\/speckit.constitution Fill the constitution with the bare minimum requirements for an intervals-timer web application. Some unbreakable rules: - Don&#39;t use third party libraries - Use standard CSS, HTML5 and JavaScript - Use reactive web design Now, define the specification for this app:\n\/speckit.specify I want to build a high-fidelity, aesthetically distinct web-based Interval Timer application. The goal is to move away from utilitarian, boring timers and create a &#34;sleek&#34;, modern, and immersive experience. 1. Core User Flow &amp; Layout - Landing State: Upon opening the application, the view should be split vertically: - Top Section (The Lab): A dynamic Interval Configurator. - Bottom Section (The Library): A list containing both pre-defined presets (e.g., Tabata) and user-saved configurations. - Active State: Once a timer is started (either by finishing a configuration or selecting a preset), the UI must transition smoothly into an &#34;Active View,&#34; removing the clutter and focusing entirely on the ticking timer. 2. The Configurator (Functional Requirements) - The system must support building a workout &#34;chain&#34; of intervals. - Parameters per interval: Work Duration, Recovery\/Rest Duration. - Quick-Add Workflow: Users should be able to quickly add a new interval. By default, adding a new interval should duplicate the parameters of the previous one (to speed up standard HIIT setups). - Irregular Support: Despite the quick-add feature, the user must have full control to edit specific intervals individually to create irregular patterns (e.g., Pyramid training: 30s work, 45s work, 60s work) 3. The Active Timer (Visuals &amp; Behavior) - Representation: The timer must be visualized as a circular, fluid interface. - Behavior: The circle acts as a progress indicator that adapts and shrinks\/fills based on the remaining time of the current interval. - Animations: Transitions between &#34;Work&#34; and &#34;Rest&#34; states should be visually distinct (e.g., color shifts, pulse effects) but seamless. 4. Data Persistence - Users must be able to save their custom configurations to the &#34;Library&#34; section for future use. 5. Design Philosophy - Vibe: Sleek, modern, minimalist but not empty. It should feel like a premium tool. - Responsiveness: Must look excellent on both desktop and mobile web. Build the plan:\n\/speckit.plan Generate a technical implementation plan that utilizes modern browser standards without any build steps or external dependencies. 1. Technology Stack - Core: Native HTML5, CSS3, and Modern JavaScript (ES6+ Modules). - State Management: Use a lightweight, custom &#34;Pub\/Sub&#34; or &#34;Observer&#34; pattern in a Store.js file to handle application state (current interval, time remaining, active\/editing mode). - Storage: localStorage for persisting user-saved timer configurations. - Audio: Native HTML5 Audio API for interval beeps. 2. Architecture &amp; File Structure - Organize code using ES Modules (&lt;script type=&#34;module&#34;&gt;). - Separate concerns into: - \/js\/core: Timer logic (high precision, accounting for drift) and State management. - \/js\/ui: DOM manipulation and rendering logic. - \/css: Use CSS Variables (:root) for the theming and &#34;sleek&#34; styling to ensure easy updates. 3. Implementation Strategies - The Circular Timer: Implement this using an SVG with stroke-dasharray and stroke-dashoffset. Manipulate the offset via JavaScript in a requestAnimationFrame loop to ensure the animation is buttery smooth and high-performance. Do NOT use Canvas unless strictly necessary for performance. - Responsiveness: Use CSS Grid and Flexbox. The &#34;Configurator&#34; (Top) and &#34;Library&#34; (Bottom) should stack vertically on mobile but potentially align side-by-side on wide desktop screens if space permits. - Reactive Design: Since we have no framework, ensure that a change in the Store triggers a re-render of only the necessary DOM elements to maintain performance. 4. Data Model - Define a JSON structure for a &#34;Workout&#34; that supports the irregular intervals requirement (e.g., an array of objects where each object has duration, type (work\/rest), and label). Create tasks:\n\/speckit.tasks break this down into tasks Implement the app:\n\/speckit.implement Implement the tasks for this project, and update the task list as you go. This is the resulting app:\n","permalink":"https:\/\/linuxera.org\/spec-driven-development-with-spec-kit\/","summary":"Spec-Driven Development with Spec Kit In this post we are going to see what Spec-Driven development is and how GitHub&rsquo;s Spec Kit makes it easy to get started.\nWhat is Spec-Driven Development (SDD) Executable Specifications: Reverses the traditional &ldquo;code is king&rdquo; model by treating natural language specifications as the primary source of truth that directly generates implementation, rather than just serving as passive documentation. Constitutional Governance: Enforces immutable project principles through a &ldquo;Constitution&rdquo; that establishes non-negotiable rules before any coding begins.","title":"Spec-Driven Development with Spec Kit"},{"content":"Turning the Knobs of LLM Text Generation Ever wonder how much control you actually have over the text an LLM produces? In this post, we will look at three simple but powerful knobs you can tweak to push a model toward more deterministic output or toward something more creative.\nWe are talking about top_k, top_p and temperature. But before describing them, we need to understand the two main behaviors we can get from an LLM when it is sampling tokens:\nGreedy Sampling: At each step, the model picks the token with the highest probability given the preceding context.\nPros: Produces output that is typically coherent and aligned with the most common patterns in the training data. Is deterministic. Same prompt, same output every time. Cons: Often dull or repetitive because it never takes alternative paths. Short-sighted: the &ldquo;best next token&rdquo; doesn\u2019t always lead to the best overall sequence. Random (Stochastic) Sampling: The model draws the next token from the entire probability distribution. Higher probability tokens are more likely, but even low probability tokens can be sampled.\nPros: Output is more diverse and creative. Helps avoid repetitive loops that greedy sampling can fall into. Cons: Can reduce coherence or quality. Non-deterministic. Running the same prompt multiple times produces different results. The influence of top_k, top_p, and temperature lies in how they control the amount of randomness the model is allowed to use during sampling. By adjusting them, you can push the model closer to greedy, deterministic behavior, make it sample from a broader range of possibilities, or land anywhere in between.\nTop-K This parameter limits the model to the top K most probable tokens at each generation step. Everything outside that shortlist is ignored.\nExample Let&rsquo;s say we have the prompt The future of AI is, and we configure top_k = 5. This means the model will pick only tokens among the five tokens with the highest probability.\nThat list might look like this:\nToken: &#39; in&#39; (ID: 11) | Logprob: -2.1674 | %: 11.45% Token: &#39; not&#39; (ID: 45) | Logprob: -3.1830 | %: 4.15% Token: &#39; now&#39; (ID: 122) | Logprob: -3.4174 | %: 3.28% Token: &#39; here&#39; (ID: 259) | Logprob: -3.4330 | %: 3.23% Token: &#39; a&#39; (ID: 10) | Logprob: -3.4955 | %: 3.03% With top_k = 5, the model must pick from these five tokens and ignore everything else. How it chooses among them depends on your temperature setting.\nIf temperature = 0, the sampling becomes greedy and the model will always select the token with the highest probability,\u00a0in in the example above.\nTop-P (Nucleus Sampling) This parameter filters out tokens once the cumulative probability threshold is reached. Unlike top_k, which always keeps a fixed number of tokens, top_p includes as many tokens as necessary until their combined probability reaches the chosen value.\nExample top_k = 5 -&gt; Always selects the 5 highest-probability tokens. top_p = 0.3 -&gt; Collects tokens (from highest to lowest probability) until their cumulative probability reaches 30%. Given a list of token probabilities, we accumulate them in descending order:\nToken: &#39; the&#39; | Prob: 8.86% | Cumul: 8.86% Token: &#39; a&#39; | Prob: 7.61% | Cumul: 16.48% Token: &#39; not&#39; | Prob: 3.81% | Cumul: 20.29% Token: &#39; in&#39; | Prob: 3.11% | Cumul: 23.40% Token: &#39; being&#39; | Prob: 2.16% | Cumul: 25.56% Token: &#39; one&#39; | Prob: 1.36% | Cumul: 26.93% Token: &#39; home&#39; | Prob: 1.36% | Cumul: 28.29% Token: &#39; now&#39; | Prob: 1.29% | Cumul: 29.58% Token: &#39; getting&#39; | Prob: 1.24% | Cumul: 30.82% Top-p threshold reached (30.82% \/ 30.0%). Remaining tokens are ignored. With top_p = 0.3, the model would sample from this set of tokens, regardless of how many there are. In this example, it happened to include nine tokens, 4 more tokens than the fixed limit you\u2019d get from top_k = 5. These could have been different if tokens had a high probability, in that case we would have gotten fewer tokens than with top_k = 5.\nAgain, if temperature = 0, the sampling becomes greedy and the model will always select the token with the highest probability,\u00a0the in the example above.\nTemperature This parameter adjusts how &ldquo;spread out&rdquo; the probability distribution is during sampling by scaling the model\u2019s logits before selecting the next token.\nLow temperature (closer to 0): Sharpens the distribution, making high-probability tokens even more likely. Output becomes predictable and stable. High temperature (closer to 1): Flattens the distribution, increasing the chances of lower-probability tokens. Output becomes more varied and creative, but also more chaotic if pushed too far. temperature = 0 removes randomness entirely and forces greedy behavior (always picking the token with the highest probability).\nHow can I adjust those parameters? Good question. How you can tweak top_k, top_p, and temperature depends on how you\u2019re using LLMs.\nIf you\u2019re interacting through managed web interfaces (like ChatGPT\u2019s website), you typically cannot adjust these parameters. If you\u2019re using API access provided by the service, you can usually control them when sending requests. Always check the official documentation of your provider for the exact way to set these parameters in API calls.\nWhat&rsquo;s next? If you want to experiment with tuning these parameters on open models, check out this Jupyter Notebook, which uses vLLM python bindings to tune LLM text generation.\nJupyter Notebook ","permalink":"https:\/\/linuxera.org\/turning-the-knobs-of-llm-text-generation\/","summary":"Turning the Knobs of LLM Text Generation Ever wonder how much control you actually have over the text an LLM produces? In this post, we will look at three simple but powerful knobs you can tweak to push a model toward more deterministic output or toward something more creative.\nWe are talking about top_k, top_p and temperature. But before describing them, we need to understand the two main behaviors we can get from an LLM when it is sampling tokens:","title":"Turning the Knobs of LLM Text Generation"},{"content":"Get data from an etcd backup (encrypted or not!) The following post aims to provide a step by step procedure to recover data from an etcd snapshot (even if it\u2019s encrypted) from a Kubernetes cluster.\nThe post targets the following use cases:\nWe have a non-encrypted etcd snapshot file, and we want to get some data from it. We have an encrypted etcd snapshot file, and we want to get some data from it. For non-encrypted etcd snapshots, you can read the data with the etcdctl tool directly. In this post, since I have to cover encrypted as well, I&rsquo;ll describe how to consume the restored data from a temporary local kube-apiserver.\nPrereqs Download etcd tooling and Kubernetes binaries (you want to use the same versions as the ones used in the cluster where the backup was taken, it may work using different ones thought).\nmkdir -p \/var\/tmp\/etcd-restore-tests\/bin cd \/var\/tmp\/etcd-restore-tests curl -LO https:\/\/github.com\/etcd-io\/etcd\/releases\/download\/v3.5.18\/etcd-v3.5.18-linux-amd64.tar.gz curl -LO https:\/\/dl.k8s.io\/v1.31.11\/kubernetes-server-linux-amd64.tar.gz tar xvf etcd-v3.5.18-linux-amd64.tar.gz -C .\/bin\/ etcd-v3.5.18-linux-amd64\/etcd etcd-v3.5.18-linux-amd64\/etcdutl --transform=&#39;s|.*\/||&#39; tar xvf kubernetes-server-linux-amd64.tar.gz -C .\/bin\/ kubernetes\/server\/bin\/kube-apiserver --transform=&#39;s|.*\/||&#39; Generate the required certificates for the temporary kube-apiserver.\nopenssl req -x509 -newkey rsa:2048 -nodes -keyout ca.key -out ca.crt -subj &#34;\/CN=etcd-ca&#34; -days 3650 openssl req -newkey rsa:2048 -nodes -keyout apiserver.key -out apiserver.csr -subj &#34;\/CN=127.0.0.1&#34; openssl x509 -req -in apiserver.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out apiserver.crt -days 3650 -extensions v3_req -extfile &lt;(printf &#34;[v3_req]\\nsubjectAltName=IP:127.0.0.1,DNS:localhost&#34;) openssl req -newkey rsa:2048 -nodes -keyout admin.key -out admin.csr -subj &#34;\/CN=admin\/O=system:masters&#34; openssl x509 -req -in admin.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out admin.crt -days 3650 Non-Encrypted Scenario NOTE: You can use tools such as Auger or koff to access data from the unencrypted backup without having to run the local kubeapiserver. Thanks @palonsoro for the pointers.\nCheck etcd snapshot consistency.\n.\/bin\/etcdutl snapshot status snapshot_2025-10-02_092618.db -w table +----------+----------+------------+------------+ | HASH | REVISION | TOTAL KEYS | TOTAL SIZE | +----------+----------+------------+------------+ | 7804fc7a | 9078653 | 11199 | 94 MB | +----------+----------+------------+------------+ Restore the snapshot data to a local folder.\n.\/bin\/etcdutl snapshot restore snapshot_2025-10-02_092618.db --data-dir etcd-data 2025-10-02T11:26:59Z info snapshot\/v3_snapshot.go:265 restoring snapshot {&#34;path&#34;: &#34;snapshot_2025-10-02_092618.db&#34;, &#34;wal-dir&#34;: &#34;etcd-data\/member\/wal&#34;, &#34;data-dir&#34;: &#34;etcd-data&#34;, &#34;snap-dir&#34;: &#34;etcd-data\/member\/snap&#34;, &#34;initial-memory-map-size&#34;: 10737418240} 2025-10-02T11:26:59Z info membership\/store.go:141 Trimming membership information from the backend... 2025-10-02T11:26:59Z info membership\/cluster.go:421 added member {&#34;cluster-id&#34;: &#34;cdf818194e3a8c32&#34;, &#34;local-member-id&#34;: &#34;0&#34;, &#34;added-peer-id&#34;: &#34;8e9e05c52164694d&#34;, &#34;added-peer-peer-urls&#34;: [&#34;http:\/\/localhost:2380&#34;]} 2025-10-02T11:26:59Z info snapshot\/v3_snapshot.go:293 restored snapshot {&#34;path&#34;: &#34;snapshot_2025-10-02_092618.db&#34;, &#34;wal-dir&#34;: &#34;etcd-data\/member\/wal&#34;, &#34;data-dir&#34;: &#34;etcd-data&#34;, &#34;snap-dir&#34;: &#34;etcd-data\/member\/snap&#34;, &#34;initial-memory-map-size&#34;: 10737418240} Start a single unauthenticated etcd instance with this data.\n.\/bin\/etcd --data-dir etcd-data \\ --listen-client-urls http:\/\/127.0.0.1:2379 \\ --advertise-client-urls http:\/\/127.0.0.1:2379 Start a local kube-apiserver and connect it to the etcd instance.\nNOTE: The --etcd-prefix parameter may be different for your cluster. Some Kubernetes distributions change this.\n.\/bin\/kube-apiserver \\ --etcd-servers=http:\/\/127.0.0.1:2379 \\ --authorization-mode=AlwaysAllow \\ --secure-port=6443 \\ --tls-cert-file=.\/apiserver.crt \\ --tls-private-key-file=.\/apiserver.key \\ --client-ca-file=.\/ca.crt \\ --service-account-issuer=https:\/\/kubernetes.default.svc \\ --service-account-key-file=.\/apiserver.key \\ --service-account-signing-key-file=.\/apiserver.key \\ --etcd-prefix \/kubernetes.io Get the data you want.\nkubectl --kubeconfig \/dev\/null \\ --server=https:\/\/127.0.0.1:6443 \\ --certificate-authority=.\/ca.crt \\ --client-certificate=.\/admin.crt \\ --client-key=.\/admin.key \\ -n kube-system get secret \\ pull-secret -o jsonpath=&#39;{.data.\\.dockerconfigjson}&#39; | base64 -d {&#34;auths&#34;:...&lt;redacted&gt; Encrypted Scenario Check snapshot consistency.\n.\/bin\/etcdutl snapshot status snapshot_2025-10-02_102135.db -w table +----------+----------+------------+------------+ | HASH | REVISION | TOTAL KEYS | TOTAL SIZE | +----------+----------+------------+------------+ | 32c89b47 | 9119744 | 16292 | 102 MB | +----------+----------+------------+------------+ Restore the snapshot data to a local folder.\n.\/bin\/etcdutl snapshot restore snapshot_2025-10-02_102135.db --data-dir etcd-data-encrypted 2025-10-02T11:36:57Z info snapshot\/v3_snapshot.go:265 restoring snapshot {&#34;path&#34;: &#34;snapshot_2025-10-02_102135.db&#34;, &#34;wal-dir&#34;: &#34;etcd-data-encrypted\/member\/wal&#34;, &#34;data-dir&#34;: &#34;etcd-data-encrypted&#34;, &#34;snap-dir&#34;: &#34;etcd-data-encrypted\/member\/snap&#34;, &#34;initial-memory-map-size&#34;: 10737418240} 2025-10-02T11:36:57Z info membership\/store.go:141 Trimming membership information from the backend... 2025-10-02T11:36:57Z info membership\/cluster.go:421 added member {&#34;cluster-id&#34;: &#34;cdf818194e3a8c32&#34;, &#34;local-member-id&#34;: &#34;0&#34;, &#34;added-peer-id&#34;: &#34;8e9e05c52164694d&#34;, &#34;added-peer-peer-urls&#34;: [&#34;http:\/\/localhost:2380&#34;]} 2025-10-02T11:36:57Z info snapshot\/v3_snapshot.go:293 restored snapshot {&#34;path&#34;: &#34;snapshot_2025-10-02_102135.db&#34;, &#34;wal-dir&#34;: &#34;etcd-data-encrypted\/member\/wal&#34;, &#34;data-dir&#34;: &#34;etcd-data-encrypted&#34;, &#34;snap-dir&#34;: &#34;etcd-data-encrypted\/member\/snap&#34;, &#34;initial-memory-map-size&#34;: 10737418240} Start a single unauthenticated etcd instance with this data.\n.\/bin\/etcd --data-dir etcd-data-encrypted \\ --listen-client-urls http:\/\/127.0.0.1:2379 \\ --advertise-client-urls http:\/\/127.0.0.1:2379 Get the encryption provider config.\nNOTE: This file is the one that contains the encryption config configuration from the cluster where the etcd snapshot was taken.\ncat .\/encryption-config {&#34;kind&#34;:&#34;EncryptionConfiguration&#34;,&#34;apiVersion&#34;:&#34;apiserver.config.k8s.io\/v1&#34;,&#34;resources&#34;:[{&#34;resources&#34;:[&#34;configmaps&#34;],&#34;providers&#34;:[{&#34;aesgcm&#34;:{&#34;keys&#34;:[{&#34;name&#34;:&#34;1&#34;,&#34;secret&#34;:&#34;sTD5PvlTrSwtq1O5PSHEuQdggYYXmyNhnjTtJbHZsP0=&#34;}]}},{&#34;identity&#34;:{}}]},{&#34;resources&#34;:[&#34;secrets&#34;],&#34;providers&#34;:[{&#34;aesgcm&#34;:{&#34;keys&#34;:[{&#34;name&#34;:&#34;1&#34;,&#34;secret&#34;:&#34;sTD5PvlTrSwtq1O5PSHEuQdggYYXmyNhnjTtJbHZsP0=&#34;}]}},{&#34;identity&#34;:{}}]}]} Start a local kube-apiserver wit the encryption config and connect it to the local etcd instance.\n.\/bin\/kube-apiserver \\ --etcd-servers=http:\/\/127.0.0.1:2379 \\ --encryption-provider-config=.\/encryption-config \\ --authorization-mode=AlwaysAllow \\ --secure-port=6443 \\ --tls-cert-file=.\/apiserver.crt \\ --tls-private-key-file=.\/apiserver.key \\ --client-ca-file=.\/ca.crt \\ --service-account-issuer=https:\/\/kubernetes.default.svc \\ --service-account-key-file=.\/apiserver.key \\ --service-account-signing-key-file=.\/apiserver.key \\ --etcd-prefix \/kubernetes.io Get the data you want.\nkubectl --kubeconfig \/dev\/null \\ --server=https:\/\/127.0.0.1:6443 \\ --certificate-authority=.\/ca.crt \\ --client-certificate=.\/admin.crt \\ --client-key=.\/admin.key \\ -n kube-system get secret \\ pull-secret -o jsonpath=&#39;{.data.\\.dockerconfigjson}&#39; | base64 -d {&#34;auths&#34;:...&lt;redacted&gt; ","permalink":"https:\/\/linuxera.org\/get-data-from-encrypted-etcd-backup\/","summary":"Get data from an etcd backup (encrypted or not!) The following post aims to provide a step by step procedure to recover data from an etcd snapshot (even if it\u2019s encrypted) from a Kubernetes cluster.\nThe post targets the following use cases:\nWe have a non-encrypted etcd snapshot file, and we want to get some data from it. We have an encrypted etcd snapshot file, and we want to get some data from it.","title":"Get data from an etcd backup (encrypted or not!)"},{"content":"A Beginner\u2019s Guide to RAG: What I Wish Someone Told Me In this post, I&rsquo;ll try to provide a beginners guide to RAG, focusing on what I wish someone told me before trying to build a RAG solution.\nAttention\nWhile I\u2019ve made a strong effort to ensure the information is accurate, I\u2019m far from an expert on the topic, and some details may not be entirely correct. If you notice anything missing or inaccurate, please leave a comment!\nWhat is Retrieval-Augmented Generation (RAG) RAG (Retrieval-Augmented Generation) is an AI technique that combines a language model with a search system to retrieve relevant documents and use them as context for generating more accurate, informed, and up-to-date responses. It enhances output by grounding it in external knowledge.\nTo put it simple, we provide the LLM (Large Language Model) with a set of documents it has to use when answering. These documents, are processed and stored in a vector database.\nWhy RAG? There are several use cases that benefit from the RAG pattern. Based on my findings, the most common involve leveraging existing documents to answer user questions.\nFor example:\nLet\u2019s say your company has lots of internal documents \u2014 onboarding manuals, policy guides, troubleshooting playbooks \u2014 scattered across different platforms. You want to let employees ask questions like:\n&ldquo;How do I request parental leave?&rdquo; &ldquo;How do I set up a VPN on a company-issued laptop?&rdquo; &ldquo;What\u2019s the on-call escalation policy for SREs?&rdquo; Public LLMs don&rsquo;t have access to any of that, they don&rsquo;t know your company\u2019s internal knowledge. But a RAG system can retrieve the relevant documents at inference time and inject them into the model\u2019s context. This grounds the answers in your organization\u2019s actual data.\nRAG is especially useful for internal search, support bots, and documentation assistants - particularly when your knowledge base is large and constantly changing.\nEmbeddings To make documents usable for a Retrieval-Augmented Generation (RAG) system, they must be converted into vector embeddings (numerical representations that capture semantic meaning). These embeddings are generated using a specialized embedding model, and then stored in a vector database, where they can later be searched and retrieved based on similarity to a user\u2019s query.\nThe typical flow looks like this:\nDocument -&gt; Embedding Model (tokenizes internally) -&gt; Vector Database\nContext Window We described Context Window in more detail in a previous blog post, but here\u2019s a quick refresher.\nThe Context Window defines the maximum number of tokens (words, subwords, or characters depending on the tokenizer) the model can process in a single input sequence (including both the prompt and any output generated during a single pass).\nFor example, if a model has a context window of 2048 tokens, and the prompt uses 1000 tokens, the model has 1048 tokens left for generating a response.\nWhy is the Context Window important for RAG? In Retrieval-Augmented Generation (RAG), once relevant documents are retrieved from the vector database, they are injected into the context window along with the user\u2019s query. This is how the model gains access to external knowledge at inference time.\nIf the combined length of the query and retrieved content exceeds the context window, the model won\u2019t be able to see the full input. This can result in:\nTruncated documents Missing critical context Inaccurate or hallucinated responses In summary, the context window acts as the model&rsquo;s working memory. Keeping the inputs within its limits is essential for accurate, high-quality answers in RAG systems.\nKey Considerations for RAG Document Quality over Quantity &ldquo;Garbage in, garbage out&rdquo; applies especially to RAG systems. Even the most advanced LLM can&rsquo;t compensate for low-quality source material. If you wouldn&rsquo;t hand a document to a new hire to explain a topic, don\u2019t hand it to your model either.\nTo improve the quality of your documents, consider the following strategies:\nCollaborate with content owners to update and improve documentation. Use LLMs to summarize, clean up, or extract key points \u2014 there are specialized models for creating FAQs, concise summaries, etc. Also, prepare documents with retrievability in mind. Remove elements that are hard to parse or irrelevant for text-based models:\nDiagrams, images, screenshots Long blocks of low-readability content (e.g., raw tracebacks or logs) In summary, don\u2019t try to go from zero to hero. Start with high-quality documents you trust, and gradually expand your ingestion pipeline as you validate the results.\nUnstructed vs Structured In RAG, it&rsquo;s critical to understand the type of data you\u2019re working with:\nUnstructured data: Free-form text like articles, web pages, manuals, wikis, and documentation. No strict schema. Structured data: Information with a predefined schema, such as database rows, spreadsheets, or API responses. If you\u2019re working with structured data, classic RAG may not be the best fit. Instead, consider using Agentic RAG, where the LLM is given access to tools (like APIs or SQL queries) that retrieve structured data on-demand and inject it into the context window.\nAgentic RAG also works well when you need to blend structured and unstructured sources in a single system.\nRAG Searches Retrieval-Augmented Generation (RAG) systems rely on effective document retrieval techniques to surface relevant context for the LLM. There are three main search strategies you should be familiar with: semantic search, keyword search, and hybrid approaches.\nSemantic Search Semantic search focuses on understanding the meaning behind a query rather than matching specific words. It uses vector embeddings to represent both the query and documents in a high-dimensional space, then measures their similarity.\nThis is especially useful when the user\u2019s query uses different phrasing than the source material \u2014 for example, searching &ldquo;How to get a refund?&rdquo; could match documents about &ldquo;return policies.&rdquo;\nCommon similarity metrics include:\nCosine Similarity: Measures the angle between two vectors \u2014 good for checking direction\/semantic similarity. Dot Product: Takes into account both similarity and vector magnitude \u2014 useful when embedding magnitude carries importance. (Be cautious: unnormalized dot product can favor longer text regardless of relevance.) Euclidean Distance: Measures literal distance \u2014 often used in clustering or when you want to group semantically close documents. Semantic Search Algorithms Cosine Similarity Compare two texts to see if they talk about the same thing, even if one is longer.\nDoc A: &ldquo;The capital of France is Paris.&rdquo; Doc B: &ldquo;Paris is the capital city of France, known for the Eiffel Tower.\u201d Despite different lengths and wordings, their cosine similarity will be high because they are semantically aligned.\nDot Product Prioritize documents that not only match the query direction but also carry stronger signals (e.g., longer content, weighted terms).\nDoc A: &ldquo;200 words about EU regulations on emissions.&rdquo; Doc B: &ldquo;2000 words with comprehensive policy analysis, including emissions and carbon tax.&rdquo; Both match query direction, but doc B has a higher magnitude. Possibly due to length, or emphasis.\nEuclidean Distance Grouping documents with similar embeddings into clusters, regardless of angle. Closer means more similar overall vector positions.\nYou embed 1000 support tickets, and you want to cluster them into 5 issue types. Euclidean will help you do K-Means Clustering to find natural groupings. Keyword \/ Full-text Search Keyword-based search is more literal. It tries to find exact words or phrases within documents \u2014 like traditional search engines or grep. It\u2019s ideal when the user is looking for a specific term, phrase, or entity.\nA commonly used algorithm here is:\nBM25 (Best Match 25): A probabilistic model that ranks documents based on the occurrence and frequency of query terms, adjusted by document length. While it doesn\u2019t capture semantic meaning, keyword search is fast, simple, and precise \u2014 especially for technical content with consistent terminology.\nHybrid Search Hybrid search combines both semantic and keyword search to maximize recall and precision. A typical approach might:\nUse keyword search (e.g: BM25) to quickly narrow down a large document set. Use semantic search to rank or rerank the candidates based on relevance and meaning. This approach gives you the best of both worlds: the precision of keywords with the flexibility of semantics.\nThe order of operations in hybrid search isn\u2019t fixed \u2014 it depends on your use case:\nKeyword First \u2192 Semantic Rerank: Good when you have a lot of documents and the question uses specific terms. It\u2019s fast and works well. Semantic First \u2192 Keyword Filter or Boost: Good when people might phrase things differently. Helps find relevant results even if the wording doesn\u2019t match exactly. Improving RAG Searches A RAG system is only as good as the documents it retrieves. Even if your documents are high-quality, poor retrieval can lead to weak answers. These strategies help improve document retrieval and relevance.\nReranking When your system retrieves documents \u2014 whether using semantic, keyword, or hybrid search \u2014 you typically get a list of candidates with scores. Reranking helps reorder these results to better match your specific use case.\nHere are common reranking strategies:\nLLM-based Reranking: Use a language model to evaluate which results best answer the user\u2019s question. Cross-Encoder Reranking: Use a model that takes both the query and document together to assign a new relevance score. Custom Rerankers: Create your own logic to boost or demote certain results based on metadata (e.g., date, author, document type, etc.). Refine user&rsquo;s questions Sometimes the original question doesn\u2019t provide enough context, especially in ambiguous cases. For example:\nUser query: Where can I buy a mouse? LLM: Do they mean a computer peripheral or a pet? To avoid confusion, you can refine the query using an LLM by injecting context. If you know your documents cover internal hardware policies, your refinement prompt might look like:\n&ldquo;You&rsquo;re a helpful assistant specialized in helping users buy computer hardware following company policy.&rdquo; Make sure to include the user\u2019s original question in the final prompt. This helps keep the user\u2019s intent while clarifying the meaning for better retrieval.\nUse the right algorithm for semantic search Different similarity algorithms can give different retrieval behaviors. Choose based on what matters most in your case.\nYou can also combine them, for example:\nUse Cosine Similarity to get meaning-aligned docs. Use Dot Product to emphasize importance or weight. Improving RAG Answers Once your RAG system retrieves the right documents, the next step is generating accurate and trustworthy answers. Here are some key practices to improve answer quality.\nAlways Include Source Links Make sure the system outputs links or references to the documents used to generate an answer. This improves transparency and helps users verify the information.\nLimit the Number of Documents Used Allow your system to restrict the number of retrieved documents passed into the context window \u2014 for example, the top 3 most relevant ones.\nFewer, more relevant documents often lead to better answers than many loosely related ones.\nManage the Context Window Wisely The context window is finite \u2014 and balance is key. When injecting documents into the prompt:\nIf the documents are small and fit entirely into the context window, include the full document:\nBut don\u2019t overload the context \u2014&gt; this can confuse the model (overstuffing). And don\u2019t underload \u2014&gt; the model may hallucinate or miss key details (undersupplying). Example:\nWant a summary of Chapter 1 of a book? \u279c Send only Chapter 1. Want to know how many times a character appears? \u279c Send the whole book (if it fits). Embeddings Strategies In a RAG system, how you generate embeddings has a big impact on both retrieval performance and answer quality. The two most common approaches are full-length and chunk-level embeddings \u2014 and each has trade-offs.\nFull-Length Embeddings Full-length embeddings are vector representations of entire documents or large text blocks. Their goal is to capture the overall semantic meaning of the content.\nEfficient retrieval: Fewer vectors to store and search (e.g., 1 vector per document). Lower granularity: May miss fine details buried deep in the text. This approach is useful when you&rsquo;re trying to quickly identify which document is most relevant \u2014 like finding the right manual or report.\nChunk-Level Embeddings Chunk-level embeddings break documents into smaller parts \u2014 sentences, paragraphs, or sections \u2014 and generate vectors for each chunk. These embeddings focus on local details.\nHigher precision: Great for surfacing exact sections relevant to a query. More expensive: You\u2019ll need to store and search many more vectors. While more vectors improve granularity, they increase index size, memory use, and retrieval latency \u2014 especially for large bodies of text. This approach shines when specific answers are scattered throughout large documents \u2014 like answering \u201cWhat ports does this device support?\u201d from a 100-page manual.\nCombine the Two A smart strategy is to combine both approaches:\nStart with full-length embeddings to quickly identify relevant documents. This narrows down your search space (e.g., 1,000 vectors instead of 10,000). Then, search within those documents using chunk-level embeddings to locate the most relevant sections. This hybrid method may require using different embedding models optimized for different levels of granularity \u2014 but the payoff is better retrieval and more accurate answers.\nRAG vs Fine-Tuning RAG injects relevant external documents into the model\u2019s context at inference time to improve responses without changing the model itself. It\u2019s flexible and keeps up with changing information.\nFine-tuning modifies the model&rsquo;s internal weights by training it on task-specific data. This can improve performance but updates require retraining and are less responsive to real-time changes compared to RAG.\nIn summary, RAG adds knowledge dynamically at inference time; fine-tuning bakes knowledge into the model permanently.\nRAFT (RAG + Fine-Tuning) RAFT (Retrieval-Augmented Generation + Fine-Tuning) brings together the strengths of both approaches to maximize performance and flexibility.\nFine-tune your LLM on high-quality, stable knowledge (e.g., internal documentation, product specs, historical data). Use RAG to inject dynamic or frequently updated information (e.g., current policies, real-time data) at query time. This hybrid strategy is especially effective when your system needs to reason over both historical and real-time knowledge.\nVague Recollection vs Working Memory To understand how RAFT works, it helps to think of your LLM like a person:\nFine-tuned knowledge is like vague recollection \u2014 facts learned and internalized over time. Stored in the model\u2019s weights. RAG-injected knowledge is like working memory \u2014 recent or immediate context added temporarily. Stored in the context window. Example:\nSummarizing a book you read months ago? That&rsquo;s vague recollection (fine-tuned knowledge). Summarizing a chapter you just read? That\u2019s working memory (RAG). By combining both, RAFT enables your LLM to be knowledgeable, adaptable, and context-aware.\nUseful Resources Major&rsquo;s Hayden blog on RAG Embedding models leaderboard Effective context window size for models (NVIDIA Ruler) Repository with advanced RAG techniques LlamaIndex Introduction to RAG LLamaIndex Production RAG r\/RAG SML RAG Arena What&rsquo;s Next? Go and try building a RAG system by using existing frameworks like LLamaIndex or LangChain.\nIn the next days I&rsquo;ll be publishing a test app I made while trying to learn about RAG internals.\n","permalink":"https:\/\/linuxera.org\/rag-beginners-guide\/","summary":"A Beginner\u2019s Guide to RAG: What I Wish Someone Told Me In this post, I&rsquo;ll try to provide a beginners guide to RAG, focusing on what I wish someone told me before trying to build a RAG solution.\nAttention\nWhile I\u2019ve made a strong effort to ensure the information is accurate, I\u2019m far from an expert on the topic, and some details may not be entirely correct. If you notice anything missing or inaccurate, please leave a comment!","title":"A Beginner\u2019s Guide to RAG: What I Wish Someone Told Me"},{"content":"Introduction to LLM concepts In this post, I&rsquo;ll cover various LLM concepts and the questions I asked myself while diving deep into the world of LLMs. I expect this post to be updated as I continue to learn more things around LLMs.\nAttention\nThis post is the result of my exploratory work on LLMs. While I\u2019ve made a strong effort to ensure the information is accurate, I\u2019m far from an expert on the topic, and some details may not be entirely correct. If you notice anything missing or inaccurate, please leave a comment!\nGeneral LLM Concepts and Questions This section describes general concepts and questions around Large Language Models.\nWhat&rsquo;s a Large Language Model (LLM)? A Large Language Model (LLM) is an AI system trained on vast amounts of text data to understand and generate human-like language. Using deep learning, specifically transformer architectures, LLMs can answer questions, summarize text, generate content, and more. They predict the most likely next word based on context.\nWhat&rsquo;s the difference between a Base and an Instruct model? A base model predicts the next word, an instruct model has been fine-tuned to predict the next word in a conversation between a user and a helpful assistant and specifically to follow instructions. There are other types like chat models that are fine-tuned to follow a conversation in a chat-like mode with a given format, etc.\nYou could make a base model follow instructions but that requires configuring the model via prompts to do so.\nUsually, base models are used for fine-tune your model based on the base one.\nWe can make a base model behave like an instruct model by formatting our prompts in a consistent way that the model can understand. That&rsquo;s done via chat templates. If you want to learn more about chat templates, read this. You can see the chat template for an instruct model in the tokenizer_config.json (example).\nAspect Base Models Instruct Models Training Objective General language modeling. Fine-tuned for instruction following. Focus Broad and generic text understanding. Task-specific, user-centric interactions. Performance Literal, unrefined responses. Context-aware, tailored responses. Safety and Alignment Lower alignment with human values. Higher alignment due to RLHF. Examples of Usage Pre-training for fine-tuning tasks. User-facing applications like chatbots. RLHF -&gt; Reinforcement Learning from Human Feedback\nBase Models: Useful as a starting point for further fine-tuning for specific tasks. Instruct Models: Ideal for deployment in interactive environments where users provide natural-language instructions. You may want to use base when you train the model yourself or you want to do purely text\/code continuation.\nWhat are Parameters in a LLM Model? In a Large Language Model (LLM), parameters refer to the numerical values within the model that determine how it processes and generates text. These parameters are the weights and biases of the neural network, which are adjusted during the training process.\nTeacher vs Critic vs Judge Model Teacher Model A teacher model in many cases is a large, high-performing model whose outputs are used to train a smaller, more efficient student model. This process (called knowledge distillation) typically involves having the teacher model generate &ldquo;soft labels&rdquo; or guidance on either the same dataset or additional unlabeled data, which helps the student learn more nuanced patterns. A teacher model can also be used to generate synthetic data from a curated dataset (i.e: one carefully selected or labeled by humans).\nCritic Model A critic model is designed to evaluate or critique the output of another model. Its role is typically focused on assessing the quality, relevance, accuracy, or coherence of generated outputs and identifying areas of improvement.\nCritic models are often used during training to evaluate outputs from the teacher model.\nJudge Model A judge model is designed to evaluate and rank the performance of multiple outputs. It acts more as an arbiter than a feedback provider, making decisions about which output is &ldquo;better&rdquo; according to predefined criteria. Depending on the setup, its role can overlap with or complement that of a critic model.\nJudge models can sometimes be trained on human preference data, which helps them simulate human judgement more closely.\nLLM as a Judge Using LLMs as judges is a powerful solution to asses outputs in a human way, without requiring costly human time. The idea is simple: ask an LLM to do the grading for you.\nYou can read more about this in this hugging face cookbook.\nCritic and Judge models collaboration In advanced LLM setups, critic and judge models often work together:\nCritic improves candidate outputs by iterating over feedback. Judge evaluates the improved outputs to decide the final response. This dynamic can be crucial in applications where fine-tuned outputs, such as accurate medical advice, high-quality creative writing, or nuanced technical analysis, are required.\nRAG vs Fine Tuning The difference between RAG and fine-tuning is that RAG augments a\u00a0natural language processing (NLP)\u00a0model by connecting it to an organization\u2019s proprietary database, while fine-tuning optimizes\u00a0deep learning\u00a0models for domain-specific tasks. RAG and fine-tuning have the same intended outcome: enhancing a model\u2019s performance to maximize value for the enterprise that uses it.\nRAG uses an organization\u2019s internal data to augment prompt engineering, while fine-tuning retrains a model on a focused set of external data to improve performance.\nWhen we talk about fine-tuning most of the time we refer to parameter-efficient fine-tuning (PEFT) which focuses on tuning only the relevant parameters to make the mode more effective in a certain domain, this helps keeping training costs low.\nAspect RAG (Retrieval-Augmented Generation) Fine-Tuning Knowledge Source External, dynamically retrieved. Internal, baked into the model\u2019s weights. Adaptation Method Combines retrieval and generation dynamically. Updates model weights with new training data. Scalability Scales easily with growing knowledge bases. Requires retraining for new domains. Flexibility Can adapt to changing information in real-time. Static after training; requires retraining for updates. Cost and Time Requires infrastructure for retrieval; no retraining cost. Computationally expensive and time-consuming. Performance Dependent on the quality of the retrieval system. Highly accurate for specific tasks if trained well. Use Cases Open-domain, dynamic tasks needing current data. Fixed-domain, static tasks requiring precision. Evaluating Models In order to evaluate a LLM performance there are different benchmarks that can be used, there are several benchmarks available, two of the most common ones are:\nMMLU: Massive Multitask Language Understanding, tests a model\u2019s proficiency across a wide range of subjects, ensuring broad knowledge coverage. MATH: Evaluates mathematical problem-solving abilities, ensuring that models can handle numerical and logical challenges What is quantization? Quantization is a compression technique in order to reduce model&rsquo;s size. It maps high precision values to lower precision values for the model&rsquo;s weights and activations. This compression has an impact on the model accuracy, in some cases comparable results can be achieve with lower precision.\nThe way it works is by representing a range of full precision float32 numbers (FP32) in half precision float16 numbers (FP16), and sometimes even integer numbers like int 4 bits (INT4). Usually quantization is done from FP32 to INT8.\nFor example, if we have a 2B parameter model with half precision FP16 where each parameter takes 16 bits (2bytes), it means the model will weight ~4GB:\n(2000000000*2)\/1024\/1024\/1024 = 3.7\nMore info available here.\nWhat is a distilled model? A distilled model is a smaller, more efficient version of a larger model, trained using a technique called knowledge distillation. The goal is to retain as much of the original model&rsquo;s performance as possible while reducing its size and computational requirements.\nHow Knowledge Distillation Works A large model (teacher) generates outputs on a dataset.\nA smaller model (student) is trained to mimic the outputs of the teacher model, often learning from both:\nThe original dataset. The teacher model\u2019s predictions, probabilities, or reasoning steps. The student model achieves similar accuracy with fewer parameters, making it faster and cheaper to use.\nThis approach is common in LLMs to create lighter, optimized versions for deployment in real-world applications with limited computing power.\nWhat are tokens in the context of LLMs? We can think of a token as if it was a word, but a token is not always a whole word. For example, English has around ~600k words, while an LLM might have a vocabulary of around ~32k tokens (i.e: llama2).\nTokenization works on sub-words units that can be combined. For example, the tokens &ldquo;play&rdquo; and &ldquo;ful&rdquo; can be combined to form &ldquo;playful&rdquo;. Or we can append &ldquo;ed&rdquo; to form &ldquo;played&rdquo;.\nYou can see a tokenizer in action in this hugging face tokenizer playground.\nLLMs use special tokens specific to the models to open and close the structured components of its generation. The most important special token is the End of sequence token (EOS). For example SmolLM2 from hugging face uses the following EOS token &lt;|im_end|&gt;. You can see the special tokens for models in the tokenizer_config.json.\nExample for SomlLM2.\nLLMs will predict continue predicting words until the next word with the highest score is the EOS token.\nYou can see how the decoding process works here. And a more advanced strategy here.\nWhat is the context window\/context length\/model max length? It&rsquo;s the maximum number of tokens the model can process in a single input sequence (including both the prompt and any output generated during a single pass).\nLet&rsquo;s say we have a context window of 2048, if we have one input that takes 1000, we have 1048 left for the model to reply.\nRemember that LLMs doesn&rsquo;t have memory, if you&rsquo;re in a chat and the model is remembering the conversation is because on each iteration the previous context is being sent as well.\nKeep in mind that the greater the context length is, the more memory it takes to run the model.\nThe maximum context window that a model can handle is often found in the tokenizer_config.json and\/or in the config.json files for safetensors models.\nYou can look for model_max_length in tokenizer_config.json and if the value doesn&rsquo;t make sense, look for max_position_embeddings in config.json.\nThe values in these files may be higher than a power-of-2 size, so for example if the setting says 131072, that would be 128k model max length.\nAn alternative is looking for this information in LLM Explorer.\nWhat is the embedding size? The embedding size refers to the number of dimensions used to represent each token as a numerical vector. For example, if a model has an embedding size of 768, each token is represented as a 768-dimensional vector.\nLarger embedding sizes capture more nuanced meanings and relationships between words, improving model performance.\nThe larger the embedding size is, the larger the computational requirements are.\nWhat are weights and activations? Weights are trainable parameters that a model learns during training, defining the strength of connections between neurons across different layers. They control how much influence input data has on each neuron&rsquo;s output. In LLMs, such as transformer models, weights capture complex language patterns like grammar, context, and semantics by determining relationships between words and distributing attention.\nActivations, on the other hand, are the outputs produced by neurons after applying an activation function (e.g., ReLU, Sigmoid, or Tanh) to the weighted sum of inputs. They introduce non-linearity, enabling the model to learn and represent complex patterns that linear functions cannot capture. In LLMs, activations help the model represent nuanced aspects of language, such as the relative importance of words or phrases in a given context.\nTogether, weights and activations work in tandem: weights adjust the flow and influence of information through the network during training, while activations determine the processed outputs at each neuron, ultimately allowing models to perform tasks like text generation, translation, and summarization effectively.\nSafetensors vs GGUF models Both are common formats for sharing LLM models, we can think of safetensors as the raw files, more convenient for fine-tuning and tinkering, while the gguf can be seen as a binary format more convenient for sharing and consume.\nRequired vRAM for LLM Models A basic formula to estimate vRAM usage is:\nNumber of parameters x (Precision \/ 8 ) x 1.2\nFor example for a 2B parameter using FP32\nThis calculation assumes a maximum sequence length of 512, a batch size of 8, and the use of a single GPU.\n2000000000 x (32\/8) x 1.2 \/ 1024 \/ 1024 \/ 1024 = 8.9\nSome models also publish the amount of memory they take, for example Mistral publishes sizes here.\nThese estimations are for inference, training takes more memory.\nThere are also some tools to know if you can run a given model in your hardware:\nhttps:\/\/huggingface.co\/spaces\/Vokturz\/can-it-run-llm https:\/\/vram.asmirnov.xyz\/ https:\/\/rahulschand.github.io\/gpu_poor LLM Models Naming There is no naming convention, but the more common way of naming models is like this:\nFor example given the name codellama-70b-python.Q4_K_S.gguf we can tell:\n70B &ndash;&gt; 70 billion parameters. Q4 &ndash;&gt; Quantization level. The lower the number, the lower the memory required (and also the precision). _0|_1|_K &ndash;&gt; Rounding method used for the weights. _S|_M|_L &ndash;&gt; Size category from small to large. The lower the letter, the lower the memory required (and also the precision). What does it mean model names like 8x7B It means the model is a mixture of experts of 8 models. Each model with 7B parameters.\nPadding in LLM Models In the context of LLMs, padding refers to the practice of adding dummy tokens (usually a special &lt;PAD&gt; token) to sequences to make them all the same length. Padding is used in situations where batches of text sequences need to be processed together.\nFor example:\nGiven sentences of varying lengths like [&quot;Hello&quot;, &quot;How are you?&quot;, &quot;Good morning&quot;], they might be padded to a common length (e.g., 3 tokens) as: [&#34;Hello&#34;, &#34;&lt;PAD&gt;&#34;, &#34;&lt;PAD&gt;&#34;] [&#34;How&#34;, &#34;are&#34;, &#34;you?&#34;] [&#34;Good&#34;, &#34;morning&#34;, &#34;&lt;PAD&gt;&#34;] Padding helps with:\nBatch Processing: Modern LLMs are highly parallelized and operate more efficiently when sequences are grouped and processed together in batches. Padding ensures all sequences in a batch have the same length. Fixed-Length Input: Many models expect fixed-length input tensors (e.g., max_length), so padding helps conform variable-length data to this requirement. Efficient GPU Utilization: Padding aligns data to the tensor shapes required by hardware accelerators (like GPUs\/TPUs) to optimize memory and compute usage. What Are Padding-Free LLM Models? Models designed to eliminate the need for padding by processing sequences of varying lengths more dynamically. These models do not require all input sequences to be the same length and instead handle variable-length data directly.\nPadding free helps with:\nEfficiency: Avoiding padding minimizes redundant computations, leading to faster processing. Memory Usage: Padding-free models save memory by not storing unnecessary padding tokens. Scalability: These models are more adaptable to varying sequence lengths, especially for real-time or online processing tasks. Prompts Prompts are the text inputs provided to a large language model (LLM) that guide its responses. They can be simple questions, detailed instructions, or context-setting narratives. The design and clarity of a prompt directly influence the quality and relevance of the generated output. In essence, prompts tell the model what to do, framing the task and setting the context for the answer.\nSystem Prompt The system prompt is an instruction provided by the system to guide the behavior of a language model. It sets the context, defines roles, and establishes rules for how the model should respond during an interaction. This prompt is usually hidden from the end user but is crucial in shaping the overall output and ensuring consistency in the model&rsquo;s behavior.\nWhen running LLMs in your own infrastructure you can define your own system prompts. While this is often hidden from the end user, there are models such as Claude, publishing their system prompt.\nChain of Thought \/ Reasoning Models New reasoning models use chain-of-thought techniques, prompting the model to generate intermediate reasoning steps before providing a final answer. Unlike regular models that generate outputs in one go, these models break down the problem into smaller, logical steps. This approach improves accuracy and transparency, especially for complex tasks requiring multi-step reasoning and logical deduction.\nNo CoT vs Zero-shot CoT vs Manual CoT No CoT In this approach, the model is given the question without any guidance on reasoning or intermediate steps. The model is expected to generate an answer directly without an explicit chain of thought.\nZero-shot CoT Here, a simple prompt like &ldquo;Think step by step&rdquo; is added to the question. This minimal instruction encourages the model to generate a chain of thought implicitly, but without detailed guidance on how to structure its reasoning.\nThis is also referred as Re-Act (Reasoning Act) approach.\nPrompting the model to think &ldquo;step by step&rdquo; encourages the decoding process toward next tokens that generate a plan, rather than a final solution.\nManual CoT This method involves providing detailed, step-by-step instructions or examples that illustrate the desired reasoning process. By showing how to break down and solve similar problems, manual CoT guides the model explicitly on structuring its chain of thought to arrive at an answer.\nLLM Agents LLM agents are programs that combine one or more large language models with various tools\u2014such as APIs, databases, or knowledge sources\u2014to analyze inputs, reason through tasks, and execute actions or automations autonomously. Their primary use case is to streamline and automate complex workflows by integrating natural language understanding with practical tool usage.\nWhen deploying these agents, it\u2019s crucial to implement robust guardrails. These may include action constraints, monitoring mechanisms, fail-safes, and ethical guidelines to prevent unintended behavior and ensure safe, reliable operation.\nWhen building agents there are no-code and pro-code alternatives, for example:\nNo-code: https:\/\/n8n.io\/ \/ https:\/\/github.com\/n8n-io\/n8n\nPro-code: https:\/\/www.langchain.com\/langgraph \/ https:\/\/github.com\/langchain-ai\/langgraph\nHugging Face course on AI Agents: https:\/\/huggingface.co\/learn\/agents-course\/unit0\/introduction\nExample use cases An agent that monitors system logs for errors and tries to fix stuff before it breaks. It analyzes the content of the log, checks if it has a solution for that error in its knowledge base and runs the tools for fixing it. If it doesn&rsquo;t know how to fix it, analyzes the log and transforms it to natural language, after that it opens a support case and routes it to the proper team.\nModel Context Protocol (MCP) The Model Context Protocol is an open standard that enables developers to build secure, two-way connections between their data sources and AI-powered tools. The architecture is straightforward: developers can either expose their data through MCP servers or build AI applications (MCP clients) that connect to these servers.\nLearn more in the Anthropic announcement, and official docs. And check available servers upstream.\nLLM Training and Fine-Tuning Concepts This section describes general concepts around LLM Training and Fine-Tuning.\nSynthetic Data Generation (SDG) We use SDG for generating training data using what is called a teacher model. The teacher model generates further training data based on the human-crafted training data.\nIn InstructLab there is a SDG 1.5 Pipeline that adds a Critic model that filters, analyzes, critiques, plans, revises and judges the a first draft of generated data and generates the final training data set.\nYou can read more on how InstructLab does SDG here.\nOverfitting and Underfitting We say a model is overfitted when it becomes too complex and starts to memorize the training data instead of learning the underlying patters. It will perform extremely well on the training data but will struggle with unseen data. On the other hand a model is underfitted when it lacks the capacity to graps intricate patterns. It will poorly perform with the training data as well as with unseen data.\nRequired number of epochs Epochs is the number of runs that are repeated on the same data set. Training with high epochs usually end up with model overfitting.\nThere is no magic number and each model will require different number of epochs, you can use benchmarks to see how the model performs. People tend to say 3 to 6 epochs is enough for fine tuning. For example, instruct-gpt from OpenAI was trained (not fine-tuned) on 16 epochs.\nEffective Batch Size Refers to the total number of training examples processed in one update step of the model&rsquo;s parameters. It takes into account both the batch size per device (or per GPU\/TPU) and the gradient accumulation across multiple forward and backward passes.\n","permalink":"https:\/\/linuxera.org\/introduction-to-llm-concepts\/","summary":"Introduction to LLM concepts In this post, I&rsquo;ll cover various LLM concepts and the questions I asked myself while diving deep into the world of LLMs. I expect this post to be updated as I continue to learn more things around LLMs.\nAttention\nThis post is the result of my exploratory work on LLMs. While I\u2019ve made a strong effort to ensure the information is accurate, I\u2019m far from an expert on the topic, and some details may not be entirely correct.","title":"Introduction to LLM concepts"},{"content":"Signing and verifying container images with Cosign and your own PKI In this post we are going to cover how we can sign and verify container images using Cosign and our own PKI. You can learn more on how to build your own PKI with CFSSL in this post.\nWarning\nThe way we will see to sign and verify images in this post is not the recommended approach. For production usage, you should use ephemeral keys as described here. Validity of certificates generated during this post it&rsquo;s not recommended for production usage, make sure in production you have proper validity periods and rotation capabilities in place.\nSolution Overview We have our own Root CA that issued an Intermediate CA. This Intermediate CA issued two certificates, one for Team A to sign their images and another one for Team B to sign their images.\nThen, verification of image signatures will be done by using the Root CA public certificate.\nGenerating PKI with CFSSL Install required CFSSL binaries:\nsudo curl -L https:\/\/github.com\/cloudflare\/cfssl\/releases\/download\/v1.6.5\/cfssl_1.6.5_linux_amd64 -o \/usr\/local\/bin\/cfssl sudo curl -L https:\/\/github.com\/cloudflare\/cfssl\/releases\/download\/v1.6.5\/cfssljson_1.6.5_linux_amd64 -o \/usr\/local\/bin\/cfssljson sudo chmod +x \/usr\/local\/bin\/{cfssl,cfssljson} Define workdir for the files that will be generated during the post:\nexport WORKDIR=\/var\/tmp\/cosign\/ Generate Root and Intermediate CAs:\nmkdir -p $WORKDIR\/cafiles\/{root,intermediate,config,certificates} # Generate Root CA csr cat &lt;&lt; &#34;EOF&#34; &gt; $WORKDIR\/cafiles\/root\/root-csr.json { &#34;CN&#34;: &#34;Linuxera Root Certificate Authority&#34;, &#34;key&#34;: { &#34;algo&#34;: &#34;ecdsa&#34;, &#34;size&#34;: 256 }, &#34;names&#34;: [ { &#34;C&#34;: &#34;ES&#34;, &#34;L&#34;: &#34;Valencia&#34;, &#34;O&#34;: &#34;IT&#34;, &#34;OU&#34;: &#34;Security&#34;, &#34;ST&#34;: &#34;Valencia&#34; } ], &#34;ca&#34;: { &#34;expiry&#34;: &#34;87600h&#34; } } EOF # Generate Intermediate CA csr cat &lt;&lt; &#34;EOF&#34; &gt; $WORKDIR\/cafiles\/intermediate\/intermediate-csr.json { &#34;CN&#34;: &#34;Linuxera Intermediate Certificate Authority&#34;, &#34;key&#34;: { &#34;algo&#34;: &#34;ecdsa&#34;, &#34;size&#34;: 256 }, &#34;names&#34;: [ { &#34;C&#34;: &#34;ES&#34;, &#34;L&#34;: &#34;Valencia&#34;, &#34;O&#34;: &#34;IT&#34;, &#34;OU&#34;: &#34;Security&#34;, &#34;ST&#34;: &#34;Valencia&#34; } ] } EOF # Issue RootCA keypair cfssl gencert -initca $WORKDIR\/cafiles\/root\/root-csr.json | cfssljson -bare $WORKDIR\/cafiles\/root\/root-ca # Generate Intermediate CA key cfssl genkey $WORKDIR\/cafiles\/intermediate\/intermediate-csr.json | cfssljson -bare $WORKDIR\/cafiles\/intermediate\/intermediate-ca # Define cfssl profile for the intermediate CA cat &lt;&lt; &#34;EOF&#34; &gt; $WORKDIR\/cafiles\/config\/config.json { &#34;signing&#34;: { &#34;default&#34;: { &#34;expiry&#34;: &#34;8760h&#34; }, &#34;profiles&#34;: { &#34;intermediate&#34;: { &#34;usages&#34;: [&#34;cert sign&#34;, &#34;crl sign&#34;], &#34;expiry&#34;: &#34;70080h&#34;, &#34;ca_constraint&#34;: { &#34;is_ca&#34;: true, &#34;max_path_len&#34;: 1 } } } } } EOF # Issue Intermediate CA cert using RootCA cfssl sign -ca $WORKDIR\/cafiles\/root\/root-ca.pem -ca-key $WORKDIR\/cafiles\/root\/root-ca-key.pem -config $WORKDIR\/cafiles\/config\/config.json -profile intermediate $WORKDIR\/cafiles\/intermediate\/intermediate-ca.csr | cfssljson -bare $WORKDIR\/cafiles\/intermediate\/intermediate-ca # Put RootCA key to sleep rm -f $WORKDIR\/cafiles\/root\/root-ca-key.pem Generate container signing certificates for Team A and Team B:\nAttention\nFor Cosign v2 verification to work, we need our certificates to provide some information in the SAN. We require it to provide a valid email and also to provide a valid oidcIssuer. The oidcIssuer is added via OID, you can find the details here. In the certs below you can see two OIDs added as extensions, the value for the one ending in 1,1 is a base64 encoded raw string, while the one ending in 1,8 is the base64 encoded ASN.1 string (you can check the code here to generate the string).\n# Define a new cosign profile cat &lt;&lt; &#34;EOF&#34; &gt; $WORKDIR\/cafiles\/config\/config.json { &#34;signing&#34;: { &#34;default&#34;: { &#34;expiry&#34;: &#34;8760h&#34; }, &#34;profiles&#34;: { &#34;intermediate&#34;: { &#34;usages&#34;: [&#34;cert sign&#34;, &#34;crl sign&#34;], &#34;expiry&#34;: &#34;70080h&#34;, &#34;ca_constraint&#34;: { &#34;is_ca&#34;: true, &#34;max_path_len&#34;: 1, &#34;copy_extensions&#34;: true } }, &#34;cosign&#34;: { &#34;usages&#34;: [&#34;signing&#34;, &#34;digital signing&#34;], &#34;expiry&#34;: &#34;8760h&#34;, &#34;copy_extensions&#34;: true } } } } EOF # Generate cosign keypair for team-a and team-b # cosign v2 requires email and uri SAN values which are configured under hosts cat &lt;&lt; &#34;EOF&#34; &gt; $WORKDIR\/cafiles\/certificates\/team-a-csr.json { &#34;CN&#34;: &#34;Team A Cosign Certificate&#34;, &#34;key&#34;: { &#34;algo&#34;: &#34;ecdsa&#34;, &#34;size&#34;: 256 }, &#34;names&#34;: [ { &#34;C&#34;: &#34;ES&#34;, &#34;L&#34;: &#34;Valencia&#34;, &#34;O&#34;: &#34;IT&#34;, &#34;OU&#34;: &#34;Security&#34; } ], &#34;hosts&#34;: [ &#34;team-a@linuxera.org&#34; ], &#34;extensions&#34;: [ { &#34;id&#34;: [1,3,6,1,4,1,57264,1,8], &#34;value&#34;: &#34;ExRodHRwczovL2xpbnV4ZXJhLm9yZw==&#34; }, { &#34;id&#34;: [1,3,6,1,4,1,57264,1,1], &#34;value&#34;: &#34;aHR0cHM6Ly9saW51eGVyYS5vcmc=&#34; } ] } EOF cat &lt;&lt; &#34;EOF&#34; &gt; $WORKDIR\/cafiles\/certificates\/team-b-csr.json { &#34;CN&#34;: &#34;Team B Cosign Certificate&#34;, &#34;key&#34;: { &#34;algo&#34;: &#34;ecdsa&#34;, &#34;size&#34;: 256 }, &#34;names&#34;: [ { &#34;C&#34;: &#34;ES&#34;, &#34;L&#34;: &#34;Valencia&#34;, &#34;O&#34;: &#34;IT&#34;, &#34;OU&#34;: &#34;Security&#34; } ], &#34;hosts&#34;: [ &#34;team-b@linuxera.org&#34; ], &#34;extensions&#34;: [ { &#34;id&#34;: [1,3,6,1,4,1,57264,1,8], &#34;value&#34;: &#34;ExRodHRwczovL2xpbnV4ZXJhLm9yZw==&#34; }, { &#34;id&#34;: [1,3,6,1,4,1,57264,1,1], &#34;value&#34;: &#34;aHR0cHM6Ly9saW51eGVyYS5vcmc=&#34; } ] } EOF # Issue certificates via the intermediate CA cfssl gencert -ca $WORKDIR\/cafiles\/intermediate\/intermediate-ca.pem -ca-key $WORKDIR\/cafiles\/intermediate\/intermediate-ca-key.pem -config $WORKDIR\/cafiles\/config\/config.json -profile cosign $WORKDIR\/cafiles\/certificates\/team-a-csr.json | cfssljson -bare $WORKDIR\/cafiles\/certificates\/team-a cfssl gencert -ca $WORKDIR\/cafiles\/intermediate\/intermediate-ca.pem -ca-key $WORKDIR\/cafiles\/intermediate\/intermediate-ca-key.pem -config $WORKDIR\/cafiles\/config\/config.json -profile cosign $WORKDIR\/cafiles\/certificates\/team-b-csr.json | cfssljson -bare $WORKDIR\/cafiles\/certificates\/team-b Alternative OpenSSL commands In case you want to rather use OpenSSL, these are the commands you need to run. Thanks to Fr\u00e9d\u00e9ric Herrmann for sharing the information.\nAttention\nCommands below use RSA as encryption algorithm.\nGenerate Root CA\nopenssl req -x509 -newkey rsa:4096 -keyout root-ca-key.pem -sha256 -noenc -days 9999 -subj &#34;\/C=ES\/L=Valencia\/O=IT\/OU=Security\/CN=Linuxera Root Certificate Authority&#34; -out root-ca.pem Generate Intermediate CA\n# Create request openssl req -noenc -newkey rsa:4096 -keyout intermediate-ca-key.pem -addext &#34;subjectKeyIdentifier = hash&#34; -addext &#34;keyUsage = critical,keyCertSign&#34; -addext &#34;basicConstraints = critical,CA:TRUE,pathlen:2&#34; -subj &#34;\/C=ES\/L=Valencia\/O=IT\/OU=Security\/CN=Linuxera Intermediate Certificate Authority&#34; -out intermediate-ca.csr # Issue cert with Root CA openssl x509 -req -days 9999 -sha256 -in intermediate-ca.csr -CA root-ca.pem -CAkey root-ca-key.pem -copy_extensions copy -out intermediate-ca.pem Issue Team A cert\n# OID_1_1 is the hexadecimal representation of the oidcissuer url OID_1_1=$(echo -n &#34;https:\/\/linuxera.org&#34; | xxd -p -u) # Create request openssl req -noenc -newkey rsa:4096 -keyout team-a-key.pem -addext &#34;subjectKeyIdentifier = hash&#34; -addext &#34;basicConstraints = critical,CA:FALSE&#34; -addext &#34;keyUsage = critical,digitalSignature&#34; -addext &#34;subjectAltName = email:team-a@linuxera.org&#34; -addext &#34;1.3.6.1.4.1.57264.1.1 = DER:${OID_1_1}&#34; -addext &#34;1.3.6.1.4.1.57264.1.8 = ASN1:UTF8String:https:\/\/linuxera.org&#34; -subj &#34;\/C=ES\/L=Valencia\/O=IT\/OU=Security\/CN=Team A Cosign Certificate&#34; -out team-a.csr # Issue cert with Intermediate CA openssl x509 -req -in team-a.csr -CA intermediate-ca.pem -CAkey intermediate-ca-key.pem -copy_extensions copy -days 9999 -sha256 -out team-a.pem Issue Team B cert\n# OID_1_1 is the hexadecimal representation of the oidcissuer url OID_1_1=$(echo -n &#34;https:\/\/linuxera.org&#34; | xxd -p -u) # Create request openssl req -noenc -newkey rsa:4096 -keyout team-b-key.pem -addext &#34;subjectKeyIdentifier = hash&#34; -addext &#34;basicConstraints = critical,CA:FALSE&#34; -addext &#34;keyUsage = critical,digitalSignature&#34; -addext &#34;subjectAltName = email:team-b@linuxera.org&#34; -addext &#34;1.3.6.1.4.1.57264.1.1 = DER:${OID_1_1}&#34; -addext &#34;1.3.6.1.4.1.57264.1.8 = ASN1:UTF8String:https:\/\/linuxera.org&#34; -subj &#34;\/C=ES\/L=Valencia\/O=IT\/OU=Security\/CN=Team B Cosign Certificate&#34; -out team-b.csr # Issue cert with Intermediate CA openssl x509 -req -in team-b.csr -CA intermediate-ca.pem -CAkey intermediate-ca-key.pem -copy_extensions copy -days 9999 -sha256 -out team-b.pem Generate our container image We need a container image we will sign, on top of that we require our registry to support the upload of Cosign signatures. For this post I&rsquo;ll be using quay.io.\nDefine our Quay image repository:\nIMAGE_ENDPOINT=quay.io\/example\/signingtest Generate a Dockerfile:\ncat &lt;&lt;&#39;EOF&#39; &gt; $WORKDIR\/Dockerfile FROM registry.fedoraproject.org\/fedora-minimal:39 ARG GREETING RUN echo $GREETING &gt; \/tmp\/HelloWorld USER 1024 CMD [&#34;sleep&#34;, &#34;infinity&#34;] EOF Build the images for Team A and Team B:\npodman build -f $WORKDIR\/Dockerfile --build-arg GREETING=&#34;Hello from Team A&#34; -t $IMAGE_ENDPOINT:team-a podman build -f $WORKDIR\/Dockerfile --build-arg GREETING=&#34;Hello from Team B&#34; -t $IMAGE_ENDPOINT:team-b Push the images to the registry and store the images digest locally, this is required since we sign image digests, not tags:\npodman push --digestfile $WORKDIR\/image-digest-team-a $IMAGE_ENDPOINT:team-a podman push --digestfile $WORKDIR\/image-digest-team-b $IMAGE_ENDPOINT:team-b Signing container images with Cosign Attention\nDuring the exploratory work I started testing Cosign v1, that&rsquo;s why I will document here how you can sign container images using v1. The steps that differ between both versions will have both options described. Nevertheless, you should be using v2.\nDownload Cosign CLI\nsudo curl -L https:\/\/github.com\/sigstore\/cosign\/releases\/download\/v1.13.6\/cosign-linux-amd64 -o \/usr\/local\/bin\/cosign-v1 sudo curl -L https:\/\/github.com\/sigstore\/cosign\/releases\/download\/v2.2.4\/cosign-linux-amd64 -o \/usr\/local\/bin\/cosign-v2 sudo chmod +x \/usr\/local\/bin\/cosign-v1 sudo chmod +x \/usr\/local\/bin\/cosign-v2 Build trust chain bundle (must start with the parent intermediate CA certificate of the signing certificate and end with the root certificate):\ncat $WORKDIR\/cafiles\/intermediate\/intermediate-ca.pem $WORKDIR\/cafiles\/root\/root-ca.pem &gt; $WORKDIR\/ca-bundle.pem Team-A Image Signing Store container image digest:\nTEAM_A_IMAGE_DIGEST=$(cat $WORKDIR\/image-digest-team-a) Import key into Cosign:\nWith v1:\ncosign-v1 import-key-pair --key $WORKDIR\/cafiles\/certificates\/team-a-key.pem mv import-cosign.key $WORKDIR\/import-team-a.key mv import-cosign.pub $WORKDIR\/import-team-a.pub With v2:\ncosign-v2 import-key-pair --key $WORKDIR\/cafiles\/certificates\/team-a-key.pem --output-key-prefix=$WORKDIR\/import-team-a Sign with Cosign and our own key without uploading to transparency log:\nWith v1:\ncosign-v1 sign --key $WORKDIR\/import-team-a.key --no-tlog-upload --cert $WORKDIR\/cafiles\/certificates\/team-a.pem --cert-chain $WORKDIR\/ca-bundle.pem --sign-container-identity $IMAGE_ENDPOINT:team-a $IMAGE_ENDPOINT@$TEAM_A_IMAGE_DIGEST With v2:\ncosign-v2 sign --key $WORKDIR\/import-team-a.key --tlog-upload=false --cert $WORKDIR\/cafiles\/certificates\/team-a.pem --cert-chain $WORKDIR\/ca-bundle.pem --sign-container-identity $IMAGE_ENDPOINT:team-a $IMAGE_ENDPOINT@$TEAM_A_IMAGE_DIGEST Team-B Image Signing Store container image digest:\nTEAM_B_IMAGE_DIGEST=$(cat $WORKDIR\/image-digest-team-b) Import key into Cosign:\nWith v1:\ncosign-v1 import-key-pair --key $WORKDIR\/cafiles\/certificates\/team-b-key.pem mv import-cosign.key $WORKDIR\/import-team-b.key mv import-cosign.pub $WORKDIR\/import-team-b.pub With v2:\ncosign-v2 import-key-pair --key $WORKDIR\/cafiles\/certificates\/team-b-key.pem --output-key-prefix=$WORKDIR\/import-team-b Sign with Cosign and our own key without uploading to transparency log:\nWith v1:\ncosign-v1 sign --key $WORKDIR\/import-team-b.key --no-tlog-upload --cert $WORKDIR\/cafiles\/certificates\/team-b.pem --cert-chain $WORKDIR\/ca-bundle.pem --sign-container-identity $IMAGE_ENDPOINT:team-b $IMAGE_ENDPOINT@$TEAM_B_IMAGE_DIGEST With v2:\ncosign-v2 sign --key $WORKDIR\/import-team-b.key --tlog-upload=false --cert $WORKDIR\/cafiles\/certificates\/team-b.pem --cert-chain $WORKDIR\/ca-bundle.pem --sign-container-identity $IMAGE_ENDPOINT:team-b $IMAGE_ENDPOINT@$TEAM_B_IMAGE_DIGEST Verifying container images with Cosign and our Root CA We can verify the image signature in multiple ways, in this case we want to use only the Root CA public certificate to run the verification. Keep in mind that Cosign v2 doesn&rsquo;t work with BYOK like v1 used to do. More info here.\nCosign v1 We need to disable rekor-url since we haven&rsquo;t uploaded anything to the transparency log. More here.\nSIGSTORE_ROOT_FILE=$WORKDIR\/cafiles\/root\/root-ca.pem COSIGN_EXPERIMENTAL=1 cosign-v1 verify --rekor-url=&#34;&#34; $IMAGE_ENDPOINT@$TEAM_A_IMAGE_DIGEST $IMAGE_ENDPOINT@$TEAM_B_IMAGE_DIGEST Verification for quay.io\/example\/signingtest@sha256:81a274fb4ed001132969dcf03de244d6f9b36d42d2b688b09a1c2d67691e6e41 -- The following checks were performed on each of these signatures: - The cosign claims were validated - Any certificates were verified against the Fulcio roots. [{&#34;critical&#34;:{&#34;identity&#34;:{&#34;docker-reference&#34;:&#34;quay.io\/example\/signingtest&#34;},&#34;image&#34;:{&#34;docker-manifest-digest&#34;:&#34;sha256:81a274fb4ed001132969dcf03de244d6f9b36d42d2b688b09a1c2d67691e6e41&#34;},&#34;type&#34;:&#34;cosign container image signature&#34;},&#34;optional&#34;:{&#34;1.3.6.1.4.1.57264.1.1&#34;:&#34;https:\/\/linuxera.org&#34;,&#34;Issuer&#34;:&#34;https:\/\/linuxera.org&#34;,&#34;Subject&#34;:&#34;team-a@linuxera.org&#34;}}] Verification for quay.io\/example\/signingtest@sha256:3bf90da5cd72d0057e4f06faf5669004262885005e662a93706fa85627d62cc5 -- The following checks were performed on each of these signatures: - The cosign claims were validated - Any certificates were verified against the Fulcio roots. [{&#34;critical&#34;:{&#34;identity&#34;:{&#34;docker-reference&#34;:&#34;quay.io\/example\/signingtest&#34;},&#34;image&#34;:{&#34;docker-manifest-digest&#34;:&#34;sha256:3bf90da5cd72d0057e4f06faf5669004262885005e662a93706fa85627d62cc5&#34;},&#34;type&#34;:&#34;cosign container image signature&#34;},&#34;optional&#34;:{&#34;1.3.6.1.4.1.57264.1.1&#34;:&#34;https:\/\/linuxera.org&#34;,&#34;Issuer&#34;:&#34;https:\/\/linuxera.org&#34;,&#34;Subject&#34;:&#34;team-b@linuxera.org&#34;}}] Cosign v2 For Cosign v2 to work we need to have an email and uri defined in the SAN fields of the signing certificate. On top of that, we need to pass a certificate identity and a certificate oidc issuer to the verify command. We can pass specific identities and issuers, or use a regexp. We will show both.\nUse specific issuers and identities:\nTeam A:\ncosign-v2 verify --certificate-identity=&#39;team-a@linuxera.org&#39; --certificate-oidc-issuer=&#39;https:\/\/linuxera.org&#39; --insecure-ignore-sct --insecure-ignore-tlog --cert-chain=$WORKDIR\/cafiles\/root\/root-ca.pem $IMAGE_ENDPOINT@$TEAM_A_IMAGE_DIGEST Team B:\ncosign-v2 verify --certificate-identity=&#39;team-b@linuxera.org&#39; --certificate-oidc-issuer=&#39;https:\/\/linuxera.org&#39; --insecure-ignore-sct --insecure-ignore-tlog --cert-chain=$WORKDIR\/cafiles\/root\/root-ca.pem $IMAGE_ENDPOINT@$TEAM_B_IMAGE_DIGEST Use a regexp:\ncosign-v2 verify --certificate-identity-regexp=&#39;team-.*@linuxera.org&#39; --certificate-oidc-issuer-regexp=&#39;https:\/\/linuxer.*.org&#39; --insecure-ignore-sct --insecure-ignore-tlog --cert-chain=$WORKDIR\/cafiles\/root\/root-ca.pem $IMAGE_ENDPOINT@$TEAM_A_IMAGE_DIGEST $IMAGE_ENDPOINT@$TEAM_B_IMAGE_DIGEST Do not verify identities or issuers:\ncosign-v2 verify --certificate-identity-regexp=&#39;.*&#39; --certificate-oidc-issuer-regexp=&#39;.*&#39; --insecure-ignore-sct --insecure-ignore-tlog --cert-chain=$WORKDIR\/cafiles\/root\/root-ca.pem $IMAGE_ENDPOINT@$TEAM_A_IMAGE_DIGEST $IMAGE_ENDPOINT@$TEAM_B_IMAGE_DIGEST The output for the different validations will be the same as seen in v1.\nGet signature details from our image with Skopeo We can check the containers signature details by using Skopeo. Let&rsquo;s see an example for Team A image.\nGet the signature tag:\nSIGNATURE_TAG=$(echo $TEAM_A_IMAGE_DIGEST | sed &#34;s\/:\/-\/&#34; | sed &#34;s\/$\/.sig\/&#34;) Get the certificate that signed the image:\nskopeo inspect docker:\/\/$IMAGE_ENDPOINT:$SIGNATURE_TAG | jq -r &#39;.LayersData[].Annotations.&#34;dev.sigstore.cosign\/certificate&#34;&#39; | sed &#39;s\/\\\\n\/\\n\/g&#39; | grep -v null | openssl x509 -text Get the trust chain for the certificate:\nskopeo inspect docker:\/\/$IMAGE_ENDPOINT:$SIGNATURE_TAG | jq -r &#39;.LayersData[].Annotations.&#34;dev.sigstore.cosign\/chain&#34;&#39; | sed &#39;s\/\\\\n\/\\n\/g&#39; | grep -v null Get the signature:\nskopeo inspect docker:\/\/$IMAGE_ENDPOINT:$SIGNATURE_TAG | jq -r &#39;.LayersData[].Annotations.&#34;dev.cosignproject.cosign\/signature&#34;&#39; References https:\/\/docs.sigstore.dev\/key_management\/signing_with_self-managed_keys\/ https:\/\/github.com\/sigstore\/cosign\/issues\/2632 https:\/\/github.com\/sigstore\/cosign\/issues\/2858 https:\/\/github.com\/sigstore\/cosign\/issues\/3616 Generate ASN.1 string for Fulcio Extensions Note\nThanks to Hayden Blauzvern for providing the information below and helping with the certificate extensions correctness in the certificate generation section.\nIn Fulcio&rsquo;s cert profile, extensions 1,1 through 1,6 are raw strings. In 1,8 and future Fulcio extensions this changes to ASN.1 encoded string. You can encode a string using the code below.\npackage main import ( &#34;encoding\/asn1&#34; &#34;encoding\/base64&#34; &#34;fmt&#34; ) func main() { s := &#34;https:\/\/linuxera.org&#34; a, _ := asn1.Marshal(s) fmt.Println(a) fmt.Println(base64.StdEncoding.EncodeToString(a)) } ","permalink":"https:\/\/linuxera.org\/signing-verifying-container-images-with-cosign-own-pki\/","summary":"Signing and verifying container images with Cosign and your own PKI In this post we are going to cover how we can sign and verify container images using Cosign and our own PKI. You can learn more on how to build your own PKI with CFSSL in this post.\nWarning\nThe way we will see to sign and verify images in this post is not the recommended approach. For production usage, you should use ephemeral keys as described here.","title":"Signing and verifying container images with Cosign and your own PKI"},{"content":"Extending a VXLAN across nodes with Wireguard Virtualizing environments is something I do quite often in a day-to-day basis, usually, these environments live in different hypervisors. While I don&rsquo;t always need these environments to talk to each other, from time to time I need some sort of connectivity between them.\nGetting the VMs running on these hypervisors routed through the lab network is one of the solutions I have been using for a long time. For the last few days, I have been thinking of extending a virtual network across two hypervisors. This allows me to run VMs on this virtual network and get VMs to talk to each other without having to run these VMs in a routed lab network.\nFor this solution to work, we will be using Wireguard to create a tunnel between the two hypervisors using a routed lab network and VXLAN to encapsulate our virtual network in the Wireguard tunnel.\nThe instructions in this blog were tested on RHEL 9. This focuses on IPv4 VXLAN network, but the same should be doable with IPv6.\nWarning\nI&rsquo;m far (like really far) from being a Networking expert, take the information in this post with a grain of salt since it may not be 100% accurate (but it works though).\nSolution Overview In the diagram above we can see we have two hypervisors which are connected to a routed lab network via their eth0 interface. We will configure a Wireguard tunnel using this interface, the Wireguard interface will be named wg0. On top of that, we will configure a VXLAN interface that we will connect to the bridge named br0 which will be configured to send traffic via the wg0 tunnel.\nBoth hypervisors will follow this setup. When we create a VM on these hypervisors, we will connect the VM&rsquo;s eth0 interface to the bridge br0 and that will place the VM in the VXLAN network. If everything goes according to the plan, we will be able to connect from VM1 in Hypervisor 1 to VM1 in Hypervisor 2 and vice versa.\nInstalling Wireguard Attention\nSteps below must be done on every hypervisor node.\nInstall epel-release repository by following the instructions here.\nInstall elrepo repository by following the instructions here.\nInstall the required packages:\nsudo dnf install -y kmod-wireguard wireguard-tools bridge-utils Make sure the wireguard kernel module is loaded (if you get an error when trying to load the module, you may need to reboot into a newer kernel):\nsudo modprobe wireguard Attention\nIf you get the following error when trying to load the module: modprobe: ERROR: could not insert 'wireguard': Required key not available.\nThis means that you are trying to use ELRepo&rsquo;s kernel modules (kmod packages) on a system with Secure Boot enabled, therefore this must import the ELRepo Secure Boot public key into their Machine Owner Key (MOK) list.\nsudo curl -L https:\/\/elrepo.org\/SECURE-BOOT-KEY-elrepo.org.der -o \/etc\/pki\/elrepo\/SECURE-BOOT-KEY-elrepo.org.der Install the downloaded key:\nsudo mokutil --import \/etc\/pki\/elrepo\/SECURE-BOOT-KEY-elrepo.org.der When prompted, enter a password of your choice. This password will be used when enrolling the key into the MOK list. Reboot the system and follow-up the BMC interface for entrolling the MOK key. Once the boot finished:\nsudo modprobe wireguard sudo lsmod | grep wireguard wireguard 212992 0 ip6_udp_tunnel 16384 1 wireguard udp_tunnel 20480 1 wireguard Configuring Wireguard Tunnel (wg0) First we need to enable IPv4 forwarding in both hypervisors.\ncat &lt;&lt;EOF | sudo tee \/etc\/sysctl.d\/wireguard.conf net.ipv4.ip_forward=1 EOF sudo sysctl -p \/etc\/sysctl.d\/wireguard.conf Generate Wireguard keys in both hypervisors.\nsudo mkdir -p \/etc\/wireguard\/certs\/ sudo wg genkey &gt; \/etc\/wireguard\/certs\/private_key sudo wg pubkey &lt; \/etc\/wireguard\/certs\/private_key &gt; \/etc\/wireguard\/certs\/public_key sudo chmod 600 \/etc\/wireguard\/certs\/private_key sudo chmod 644 \/etc\/wireguard\/certs\/public_key Configuring Wireguard in Hypervisor 1 Hypervisor 1 has its eth0 interface connected to the lab network and configured with the 10.19.3.4\/26 IP. Hypervisor 1 can reach Hypervisor 2 at 10.19.3.5\/26. Hypervisor 1 will configure 172.16.0.1\/16 IP for wg0 and will NAT traffic through its eth0 which is connected to the routed lab network. Hypervisor 1 Priv Key in this example is: QP1LNvlaejugxgHj+DtDOX20DvBilOCn1RPRBQFakFs= Hypervisor 1 Pub Key in this example is: 3TxNmlyWmNeL4EavtHi9dRfsqPHcEeiexKzMDF7n7nU= Hypervisor 2 Priv Key in this example is: sIWrsVAvFm\/VIHQhHRPaCzBOTWK\/jmM6NkGYEwd\/oXk= Hypervisor 2 Pub Key in this example is: GmG2HkjvV8OebDy9ezHPG\/+ODb6CMv51oSEKz4StdHQ= Configure wg0:\nAttention\nMake sure you change the PrivateKey and PublicKey to match the specifics for your environment.\nHYPERVISOR_EXT_NIC=eth0 cat &lt;&lt;EOF | sudo tee \/etc\/wireguard\/wg0.conf [Interface] PrivateKey = QP1LNvlaejugxgHj+DtDOX20DvBilOCn1RPRBQFakFs= Address = 172.16.0.1\/16 ListenPort = 51820 PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o ${HYPERVISOR_EXT_NIC} -j MASQUERADE PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o ${HYPERVISOR_EXT_NIC} -j MASQUERADE [Peer] PublicKey = GmG2HkjvV8OebDy9ezHPG\/+ODb6CMv51oSEKz4StdHQ= Endpoint = 10.19.3.5:51820 AllowedIPs = 172.16.0.0\/16 PersistentKeepalive = 25 EOF Configuring Wireguard in Hypervisor 2 Hypervisor 2 has its eth0 interface connected to the lab network and configured with the 10.19.3.5\/26 IP. Hypervisor 1 can reach Hypervisor 1 at 10.19.3.4\/26. Hypervisor 2 will configure 172.16.0.2\/16 IP for wg0 and will NAT traffic through its eth0 which is connected to the routed lab network. Hypervisor 1 Priv Key in this example is: QP1LNvlaejugxgHj+DtDOX20DvBilOCn1RPRBQFakFs= Hypervisor 1 Pub Key in this example is: 3TxNmlyWmNeL4EavtHi9dRfsqPHcEeiexKzMDF7n7nU= Hypervisor 2 Priv Key in this example is: sIWrsVAvFm\/VIHQhHRPaCzBOTWK\/jmM6NkGYEwd\/oXk= Hypervisor 2 Pub Key in this example is: GmG2HkjvV8OebDy9ezHPG\/+ODb6CMv51oSEKz4StdHQ= Configure wg0:\nAttention\nMake sure you change the PrivateKey and PublicKey to match the specifics for your environment.\nHYPERVISOR_EXT_NIC=eth0 cat &lt;&lt;EOF | sudo tee \/etc\/wireguard\/wg0.conf [Interface] PrivateKey = sIWrsVAvFm\/VIHQhHRPaCzBOTWK\/jmM6NkGYEwd\/oXk= Address = 172.16.0.2\/16 ListenPort = 51820 PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o ${HYPERVISOR_EXT_NIC} -j MASQUERADE PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o ${HYPERVISOR_EXT_NIC} -j MASQUERADE [Peer] PublicKey = 3TxNmlyWmNeL4EavtHi9dRfsqPHcEeiexKzMDF7n7nU= Endpoint = 10.19.3.4:51820 AllowedIPs = 172.16.0.0\/16 PersistentKeepalive = 25 EOF Starting and verifying Wireguard Tunnel In both hypervisors run the following command:\nsudo systemctl enable wg-quick@wg0.service --now If everything went well, Hypervisors should be able to reach each other over the 172.16.0.0\/16 network.\nWe can check wg0 state in Hypervisor 1:\nwg show wg0 interface: wg0 public key: 3TxNmlyWmNeL4EavtHi9dRfsqPHcEeiexKzMDF7n7nU= private key: (hidden) listening port: 51820 peer: GmG2HkjvV8OebDy9ezHPG\/+ODb6CMv51oSEKz4StdHQ= endpoint: 10.19.3.5:51820 allowed ips: 172.16.0.0\/16 latest handshake: 1 minute, 15 seconds ago transfer: 1.56 MiB received, 105.65 MiB sent Same in Hypervisor 2:\nwg show wg0 interface: wg0 public key: GmG2HkjvV8OebDy9ezHPG\/+ODb6CMv51oSEKz4StdHQ= private key: (hidden) listening port: 51820 peer: 3TxNmlyWmNeL4EavtHi9dRfsqPHcEeiexKzMDF7n7nU= endpoint: 10.19.3.4:51820 allowed ips: 172.16.0.0\/16 latest handshake: 1 minute, 21 seconds ago transfer: 105.76 MiB received, 1.82 MiB sent Hypervisor 1 pings Hypervisor 2:\nping -I wg0 -c 1 172.16.0.2 PING 172.16.0.2 (172.16.0.2) from 172.16.0.1 wg0: 56(84) bytes of data. 64 bytes from 172.16.0.2: icmp_seq=1 ttl=64 time=0.523 ms --- 172.16.0.2 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min\/avg\/max\/mdev = 0.523\/0.523\/0.523\/0.000 ms Configuring VXLAN (br0) Now that we have the Wireguard tunnel up and running, next step is defining the VXLAN interface, plug it to a bridge interface and get the traffic encapsulated in the Wireguard tunnel.\nIn this example the VXLAN has a CIDR 172.16.30.0\/24.\nConfiguring VXLAN in Hypervisor 1 Hypervisor 1 has its wg0 interface configured with the 172.16.0.1 IP and can reach the Hypervisor 2 at 172.16.0.2 through the Wireguard tunnel. Hypervisor 1 will configure 172.16.30.1\/16 IP for br0. to-node2 VXLAN interface will be configured with the 172.16.0.2 remote and plugged into the br0 interface. Below commands rely on the nmcli tool, if your environment do not have it, you can refer to alternative commands to nmcli section.\nCreate the bridge interface:\nAttention\nI&rsquo;m creating the bridge with spanning tree protocol disabled, you may want to enable it depending on your lab needs.\nsudo nmcli con add ifname br0 type bridge con-name br0 stp no ipv4.addresses 172.16.30.1\/24 ipv4.method manual Create the VXLAN interface:\nsudo nmcli con add ifname to-node2 type vxlan con-name to-node2 remote 172.16.0.2 id 1 destination-port 4789 ipv4.method disabled Add the VXLAN interface to the bridge:\nsudo nmcli con modify to-node2 master br0 Bring up the bridge interface:\nWarning\nBe patient, the bridge may take a few seconds to be up.\nsudo nmcli con up br0 Configuring VXLAN in Hypervisor 2 Hypervisor 2 has its wg0 interface configured with the 172.16.0.2 IP and can reach the Hypervisor 1 at 172.16.0.1 through the Wireguard tunnel. Hypervisor 2 will configure 172.16.30.2\/16 IP for br0. to-node1 VXLAN interface will be configured with the 172.16.0.1 remote and plugged into the br0 interface. Create the bridge interface:\nAttention\nI&rsquo;m creating the bridge with spanning tree protocol disabled, you may want to enable it depending on your lab needs.\nsudo nmcli con add ifname br0 type bridge con-name br0 stp no ipv4.addresses 172.16.30.2\/24 ipv4.method manual Create the VXLAN interface:\nsudo nmcli con add ifname to-node1 type vxlan con-name to-node1 remote 172.16.0.1 id 1 destination-port 4789 ipv4.method disabled Add the VXLAN interface to the bridge:\nsudo nmcli con modify to-node1 master br0 Bring up the bridge interface:\nWarning\nBe patient, the bridge may take a few seconds to be up.\nsudo nmcli con up br0 Verifying VXLAN configuration If everything went well, Hypervisors should be able to reach each other over the 172.16.30.0\/24 network.\nHypervisor 1 pings Hypervisor 2:\nping -I br0 -c 1 172.16.30.2 PING 172.16.30.2 (172.16.30.2) from 172.16.30.1 br0: 56(84) bytes of data. 64 bytes from 172.16.30.2: icmp_seq=1 ttl=64 time=1.38 ms --- 172.16.30.2 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min\/avg\/max\/mdev = 1.381\/1.381\/1.381\/0.000 ms Configuring VMs on VXLAN network For this part I&rsquo;ll be using the kcli tool to interact with my KVM Hypervisors.\nIf we check in our hypervisors we will have a new network available for our VMs, the br0 network of type bridged:\nkcli list networks Listing Networks... +-----------------+---------+---------------------+-------+-------------------+----------+ | Network | Type | Cidr | Dhcp | Domain | Mode | +-----------------+---------+---------------------+-------+-------------------+----------+ | eth0 | bridged | 10.19.3.0\/26 | N\/A | N\/A | N\/A | | br0 | bridged | 172.16.30.0\/24 | N\/A | N\/A | N\/A | | default | routed | 192.168.122.0\/24 | True | default | nat | +-----------------+---------+---------------------+-------+-------------------+----------+ I configured a DHCP server in the VXLAN network with DNSMasq, the relevant configuration can be found below:\nAttention\nI&rsquo;m running this DNSMasq in one of my hypervisors, node1 to be exact. Note that this node will act as router for the VXLAN network as well.\ndhcp-range=br0,172.16.30.50,172.16.30.200,255.255.255.0,24h dhcp-option=br0,option:dns-server,172.16.30.1 dhcp-option=br0,option:ntp-server,172.16.30.1 dhcp-option=br0,option:router,172.16.30.1 We can plug a new VM into this network, I&rsquo;ll run the command below in both hypervisors:\nkcli download image centos9stream kcli create vm -i centos9stream -P nets=[br0] -P name=vm-hypervisorX If I list the VMs in both hypervisors this is what I see:\nHypervisor 1:\nkcli list vm +------------------+--------+---------------+ | Name | Status | Ip | +------------------+--------+---------------+ | vm-hypervisor1 | up | 172.16.30.59 | +------------------+--------+---------------+ Hypervisor 2:\nkcli list vm +------------------+--------+----------------+ | Name | Status | Ip | +------------------+--------+----------------+ | vm-hypervisor2 | up | 172.16.30.143 | +------------------+--------+----------------+ As you can see both VMs got their IP via DHCP, we could have used static addressing as well. We can access one of the VMs and ping the other one.\nkcli ssh vm-hypervisor1 [cloud-user@vm-hypervisor1 ~]$ ping -c1 172.16.30.143 PING 172.16.30.143 (172.16.30.143) 56(84) bytes of data. 64 bytes from 172.16.30.143: icmp_seq=1 ttl=64 time=1.94 ms --- 172.16.30.143 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min\/avg\/max\/mdev = 1.935\/1.935\/1.935\/0.000 ms We were able to reach the other VM, if we try now to access internet or any other network not directly connected to our hypervisor node doing the routing this is what happens:\n[cloud-user@vm-hypervisor1 ~]$ ping -c1 1.1.1.1 PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data. From 172.16.30.1 icmp_seq=1 Time to live exceeded --- 1.1.1.1 ping statistics --- 1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0ms If we want this VXLAN to access other networks we need to NAT the traffic, we can do that by running the following command in the hypervisor node doing the routing. Hypervisor 1 in my case:\nsudo iptables -t nat -A POSTROUTING -s 172.16.30.0\/24 -j MASQUERADE If we try the ping again:\n[cloud-user@vm-hypervisor1 ~]$ ping -c1 1.1.1.1 PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data. 64 bytes from 1.1.1.1: icmp_seq=1 ttl=41 time=27.2 ms --- 1.1.1.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min\/avg\/max\/mdev = 27.175\/27.175\/27.175\/0.000 ms Cleaning up the environment In case we want to get rid of this setup we can run the following commands.\nMake sure all VMs using the VXLAN network are stopped and removed from the network.\nIn Hypervisor 1 run:\nsudo nmcli con del br0 sudo nmcli con del to-node2 sudo systemctl stop wg-quick@wg0.service sudo systemctl disable wg-quick@wg0.service sudo iptables -t nat -D POSTROUTING -s 172.16.30.0\/24 -j MASQUERADE In Hypervisor 2 run:\nsudo nmcli con del br0 sudo nmcli con del to-node1 sudo systemctl stop wg-quick@wg0.service sudo systemctl disable wg-quick@wg0.service Alternative commands to nmcli In case you don&rsquo;t have nmcli in your environment you can use the following IP commands instead:\nHypervisor 1\nsudo ip link add name br0 type bridge stp_state 0 sudo ip address add dev br0 172.16.30.1\/24 sudo ip link add to-node2 type vxlan remote 172.16.0.2 id 1 dstport 4789 sudo ip link set up dev br0 sudo ip link set up to-node2 sudo ip link set to-node2 master br0 Hypervisor 2\nsudo ip link add name br0 type bridge stp_state 0 sudo ip address add dev br0 172.16.30.2\/24 sudo ip link add to-node1 type vxlan remote 172.16.0.1 id 1 dstport 4789 sudo ip link set up dev br0 sudo ip link set up to-node1 sudo ip link set to-node1 master br0 Cleanup\nsudo ip link del br0 sudo ip link del to-node1 sudo ip link del to-node2 References In order to achieve the work described here I used several resources from different places. I want to thank these wonderful people that created such awesome content I could make this work.\nhttps:\/\/gist.github.com\/pamolloy\/f464c2b54af03c436491f42abf0bbff9 https:\/\/jrcichra.dev\/posts\/transparent-wireguard-networks-in-kvm\/ https:\/\/www.tallwireless.com\/posts\/2020\/03\/21\/tunnels-tunnels-tunnels\/ https:\/\/rob-turner.net\/post\/vx-lan\/ ","permalink":"https:\/\/linuxera.org\/extending-vxlan-across-nodes-with-wireguard\/","summary":"Extending a VXLAN across nodes with Wireguard Virtualizing environments is something I do quite often in a day-to-day basis, usually, these environments live in different hypervisors. While I don&rsquo;t always need these environments to talk to each other, from time to time I need some sort of connectivity between them.\nGetting the VMs running on these hypervisors routed through the lab network is one of the solutions I have been using for a long time.","title":"Extending a VXLAN across nodes with Wireguard"},{"content":"Running Vault on Podman This post explains how to run a local Vault deployment on Podman for non-production use. I typically use this setup for my lab environments.\nThis setup was tested with:\nPodman v4.7.2 Podman-compose v1.0.6 Vault v1.15.2 Prerequisites Install the vault client, you can get the binary for your O.S here.\ncurl -L https:\/\/releases.hashicorp.com\/vault\/1.15.2\/vault_1.15.2_linux_amd64.zip -o \/tmp\/vault.zip unzip \/tmp\/vault.zip &amp;&amp; rm -f \/tmp\/vault.zip sudo mv vault \/usr\/local\/bin\/ Generate folder for storing the configs, data, and certs.\nmkdir -p ${HOME}\/vault-server\/data\/{certs,storage} Generate self-signed cert.\nAttention\nMake sure to edit certificate details to match your environment.\nopenssl req -new -newkey rsa:2048 -sha256 -days 3650 -nodes -x509 -extensions v3_ca -keyout ${HOME}\/vault-server\/data\/certs\/private.key -out ${HOME}\/vault-server\/data\/certs\/public.crt -subj &#34;\/C=ES\/ST=Valencia\/L=Valencia\/O=Linuxera\/OU=Blog\/CN=vault.linuxera.org&#34; -addext &#34;subjectAltName = DNS:vault.linuxera.org,IP:192.168.122.1&#34; Configure privileges.\nsudo chmod 777 ${HOME}\/vault-server\/data\/storage sudo chmod 744 ${HOME}\/vault-server\/data\/certs\/{private.key,public.crt} At this point you can go for Vault in-memory or for Vault in-disk depending on your data persistency preference.\nVault storage in-memory Generate Vault server config.\ncat &lt;&lt;EOF &gt; ${HOME}\/vault-server\/data\/in-memory-config.hcl ui = true default_lease_ttl = &#34;168h&#34; max_lease_ttl = &#34;720h&#34; api_addr = &#34;https:\/\/127.0.0.1:8201&#34; disable_mlock = true storage &#34;inmem&#34; {} listener &#34;tcp&#34; { address = &#34;0.0.0.0:8201&#34; tls_disable = &#34;0&#34; tls_cert_file = &#34;\/data\/certs\/public.crt&#34; tls_key_file = &#34;\/data\/certs\/private.key&#34; } EOF Generate podman-compose config.\ncat &lt;&lt;EOF &gt; ${HOME}\/vault-server\/vault-compose-in-memory.yaml version: &#39;3.6&#39; services: vault: image: docker.io\/hashicorp\/vault:1.15.2 container_name: vault restart: on-failure:10 ports: - &#34;8201:8201&#34; environment: VAULT_ADDR: &#39;https:\/\/0.0.0.0:8201&#39; cap_add: - IPC_LOCK volumes: - $HOME\/vault-server\/data:\/data:rw,Z healthcheck: retries: 5 command: server -config \/data\/in-memory-config.hcl EOF Run. Once the server is up you can continue reading the section Initialize Vault Server.\nAttention\nThe secrets stored in this Vault instance will be lost once the server is stopped.\npodman-compose -f $HOME\/vault-server\/vault-compose-in-memory.yaml up -d Stop.\npodman-compose -f $HOME\/vault-server\/vault-compose-in-memory.yaml down Vault storage in-disk Generate Vault server config.\ncat &lt;&lt;EOF &gt; ${HOME}\/vault-server\/data\/persistent-config.hcl ui = true default_lease_ttl = &#34;168h&#34; max_lease_ttl = &#34;720h&#34; api_addr = &#34;https:\/\/127.0.0.1:8201&#34; disable_mlock = true storage &#34;file&#34; { path = &#34;\/data\/storage&#34; } listener &#34;tcp&#34; { address = &#34;0.0.0.0:8201&#34; tls_disable = &#34;0&#34; tls_cert_file = &#34;\/data\/certs\/public.crt&#34; tls_key_file = &#34;\/data\/certs\/private.key&#34; } EOF Generate podman-compose config.\ncat &lt;&lt;EOF &gt; ${HOME}\/vault-server\/vault-compose-file-storage.yaml version: &#39;3.6&#39; services: vault: image: docker.io\/hashicorp\/vault:1.15.2 container_name: vault restart: on-failure:10 ports: - &#34;8201:8201&#34; environment: VAULT_ADDR: &#39;https:\/\/0.0.0.0:8201&#39; cap_add: - IPC_LOCK volumes: - $HOME\/vault-server\/data:\/data:rw,Z healthcheck: retries: 5 command: server -config \/data\/persistent-config.hcl EOF Run. Once the server is up you can continue reading the section Initialize Vault Server.\npodman-compose -f $HOME\/vault-server\/vault-compose-file-storage.yaml up -d Stop.\npodman-compose -f $HOME\/vault-server\/vault-compose-file-storage.yaml down Initialize Vault Server Initialize the Vault.\nNote\nYou can export the VAULT_SKIP_VERIFY env var with its value set to true to ignore self-signed certs.\nexport VAULT_ADDR=&#39;https:\/\/192.168.122.1:8201&#39; vault operator init | grep -E &#34;Unseal Key|Initial Root&#34; &gt; $HOME\/vault-server\/init-keys.txt Unseal the Vault and login.\nUNSEAL_KEY1=$(grep &#34;Key 1&#34; $HOME\/vault-server\/init-keys.txt | awk -F &#34;: &#34; &#39;{print $2}&#39;) UNSEAL_KEY2=$(grep &#34;Key 2&#34; $HOME\/vault-server\/init-keys.txt | awk -F &#34;: &#34; &#39;{print $2}&#39;) UNSEAL_KEY3=$(grep &#34;Key 3&#34; $HOME\/vault-server\/init-keys.txt | awk -F &#34;: &#34; &#39;{print $2}&#39;) VAULT_TOKEN=$(grep &#34;Root Token&#34; $HOME\/vault-server\/init-keys.txt | awk -F &#34;: &#34; &#39;{print $2}&#39;) vault operator unseal $UNSEAL_KEY1 vault operator unseal $UNSEAL_KEY2 vault operator unseal $UNSEAL_KEY3 vault login $VAULT_TOKEN Enable the kv secrets engine v2.\nvault secrets enable -version=2 kv Configure the ACL for our user.\ncat &lt;&lt;EOF &gt; $HOME\/vault-server\/team1.hcl path &#34;kv\/data\/team1\/*&#34; { capabilities = [&#34;create&#34;, &#34;update&#34;, &#34;read&#34;, &#34;delete&#34;, &#34;list&#34;] } EOF vault policy write team1-policy $HOME\/vault-server\/team1.hcl Enable userpass auth and add a user.\nvault auth enable userpass vault write auth\/userpass\/users\/mario password=str0ngp4ss policies=team1-policy Login with the user.\nvault login -method=userpass username=mario password=str0ngp4ss Put a key\/value into the Vault.\nvault kv put -mount=kv team1\/mysecret foo=a bar=b Get a key\/value from the Vault.\nvault kv get -mount=kv team1\/mysecret Access the WebUI by pointing your browser to the IP where podman is exposing port 8201. For example https:\/\/192.168.122.1:8201\/ui.\nUseful Resources Vault Docs Vault Introduction ","permalink":"https:\/\/linuxera.org\/running-vault-on-podman\/","summary":"Running Vault on Podman This post explains how to run a local Vault deployment on Podman for non-production use. I typically use this setup for my lab environments.\nThis setup was tested with:\nPodman v4.7.2 Podman-compose v1.0.6 Vault v1.15.2 Prerequisites Install the vault client, you can get the binary for your O.S here.\ncurl -L https:\/\/releases.hashicorp.com\/vault\/1.15.2\/vault_1.15.2_linux_amd64.zip -o \/tmp\/vault.zip unzip \/tmp\/vault.zip &amp;&amp; rm -f \/tmp\/vault.zip sudo mv vault \/usr\/local\/bin\/ Generate folder for storing the configs, data, and certs.","title":"Running Vault on Podman"},{"content":"Integrating cert-manager with CFSSL Multirootca In a previous post we saw how we could run our own PKI using the CFSSL tooling. This post assumes you have read the previous one.\nThe starting point is an empty Kubernetes cluster, we want to deploy cert-manager on it and on top of that we want to get it configured to issue certificates with our own PKI infrastructure running Multirootca.\nI\u2019ll be using a Kubernetes v1.27 (latest at the time of this writing). The tool used to create the cluster is kcli and the command used was:\nkcli create kube generic -P ctlplanes=1 -P workers=1 -P ctlplane_memory=4096 -P numcpus=8 -P worker_memory=8192 -P image=fedora37 -P sdn=calico -P version=1.27 -P domain=linuxera.org cert-manager-cluster Introduction to cert-manager I recommend reading the official introduction from the cert-manager project page.\nWe are going to configure cert-manager to talk to our multirootca server in order to request certificates. The external provider we will be using is the one created by Wikimedia here.\nYou can read more about external providers here.\nDeploying cert-manager We will be using helm to deploy cert-manager, the official steps are documented here.\nAdd the helm repository:\nhelm repo add jetstack https:\/\/charts.jetstack.io helm repo update jetstack Deploy cert-manager:\nhelm install \\ cert-manager jetstack\/cert-manager \\ --namespace cert-manager \\ --create-namespace \\ --version v1.12.3 \\ --set installCRDs=true If the deployment went well, we should have cert-manager running in our cluster:\nkubectl -n cert-manager get pods NAME READY STATUS RESTARTS AGE cert-manager-875c7579b-qx62m 1\/1 Running 0 2m16s cert-manager-cainjector-7bb6786867-q4t4x 1\/1 Running 0 2m16s cert-manager-webhook-89dc55877-flj7g 1\/1 Running 0 2m16s Integrating cert-manager with multirootca As we mentioned earlier, we will be using the Wikimedia CFSSL issuer external provider.\nLet&rsquo;s start by deploying the external provider into our cluster.\nAdd the helm repository:\nhelm repo add wikimedia-charts https:\/\/helm-charts.wikimedia.org\/stable helm repo update wikimedia-charts Deploy the required CRDs:\nhelm install \\ cfssl-issuer-crds wikimedia-charts\/cfssl-issuer-crds Deploy the external provider controller:\nhelm install \\ cfssl-issuer wikimedia-charts\/cfssl-issuer \\ --namespace cert-manager A new pod should be running in the cert-manager namespace:\nkubectl -n cert-manager get pods -l app.kubernetes.io\/name=cfssl-issuer NAME READY STATUS RESTARTS AGE cfssl-issuer-64f564f78f-gq4n9 1\/1 Running 0 29s Configuring the CFSSL ClusterIssuer Now that we have the external provider running, we will go ahead and configure a ClusterIssuer that will be available to all namespaces to request certificates. You can read more on Issuers here.\nCreate a secret with the auth key required by the multirootca to sign the certificate requests.\nkubectl -n cert-manager create secret generic \\ cfssl-linuxera-internal-ca-key --from-literal=key=b50ed348c4643d34706470f36a646fd4 Since the certificate that exposes our multirootca server has been signed with an unknown CA to our Kubernetes cluster, request by cert-manager will fail due to untrusted CA. We have two options to get this sorted out: First option would be adding our intermediate ca to the Kubernetes cluster trusted CA bundle, the second option (and the one I&rsquo;ll be using) is mounting the intermediate CA inside the external provider controller pod.\nNote\nThe intermediate-ca.pem is a file that contains the CA certificate for our intermediate CA that will sign the certificates.\nCreate a ConfigMap with the internal CA certificate.\nkubectl -n cert-manager create configmap \\ internal-ca-chain --from-file=ca-bundle.crt=\/path\/to\/intermediate-ca.pem Patch the cfssl-issuer deployment to mount this ConfigMap\nkubectl -n cert-manager patch deployment \\ cfssl-issuer -p &#39;{&#34;spec&#34;:{&#34;template&#34;:{&#34;spec&#34;:{&#34;$setElementOrder\/containers&#34;:[{&#34;name&#34;:&#34;cfssl-issuer&#34;}],&#34;containers&#34;:[{&#34;name&#34;:&#34;cfssl-issuer&#34;,&#34;volumeMounts&#34;:[{&#34;mountPath&#34;:&#34;\/etc\/pki\/tls\/certs\/&#34;,&#34;name&#34;:&#34;internal-ca-chain&#34;}]}],&#34;volumes&#34;:[{&#34;configMap&#34;:{&#34;name&#34;:&#34;internal-ca-chain&#34;},&#34;name&#34;:&#34;internal-ca-chain&#34;}]}}}}&#39; Next, create the issuer. Here we define how to reach the multirootca server.\ncat &lt;&lt;EOF | kubectl apply -f - apiVersion: cfssl-issuer.wikimedia.org\/v1alpha1 kind: ClusterIssuer metadata: name: cfssl-internal-linuxera-ca spec: authSecretName: &#34;cfssl-linuxera-internal-ca-key&#34; bundle: false label: &#34;linuxeraintermediate&#34; profile: &#34;host&#34; url: &#34;https:\/\/multirootca-server.linuxera.org:8000&#34; EOF We can check the Issuer status:\nkubectl get clusterissuer.cfssl-issuer cfssl-internal-linuxera-ca -o yaml status: conditions: - lastTransitionTime: &#34;2023-08-10T13:39:31Z&#34; message: Success reason: cfssl-issuer.IssuerController.Reconcile status: &#34;True&#34; type: Ready Requesting Certificates via cert-manager At this point the ClusterIssuer is ready and we can request certificates to be signed by our multirootca instance from Kubernetes via cert-manager. Let&rsquo;s see how.\nCreate a Certificate request.\ncat &lt;&lt;EOF | kubectl -n default apply -f - apiVersion: cert-manager.io\/v1 kind: Certificate metadata: name: test-host-cert-linuxera spec: secretName: test-host-cert-linuxera duration: 2160h # 90d renewBefore: 360h # 15d subject: organizations: - Linuxera Internal commonName: testhost-certmanager.linuxera.org isCA: false privateKey: algorithm: RSA encoding: PKCS1 size: 2048 usages: - server auth dnsNames: - testhost-certmanager.linuxera.org uris: - spiffe:\/\/cluster.local\/ns\/default\/sa\/default ipAddresses: - 192.168.122.50 issuerRef: name: cfssl-internal-linuxera-ca kind: ClusterIssuer group: cfssl-issuer.wikimedia.org EOF We will get our cert issued and stored in a secret.\nkubectl -n default get secret test-host-cert-linuxera -o jsonpath=&#39;{.data.tls\\.crt}&#39; | base64 -d | openssl x509 -noout -subject -issuer -startdate -enddate subject=O = Linuxera Internal, CN = testhost-certmanager.linuxera.org issuer=C = ES, ST = Valencia, L = Valencia, O = Linuxera Internal, OU = Linuxera Internal Intermediate CA, CN = Linuxera Intermediate CA notBefore=Aug 10 13:41:00 2023 GMT notAfter=Aug 9 13:41:00 2024 GMT Useful Resources https:\/\/cert-manager.io\/docs\/configuration\/ https:\/\/cert-manager.io\/docs\/usage\/certificate\/ https:\/\/gerrit.wikimedia.org\/r\/plugins\/gitiles\/operations\/software\/cfssl-issuer\/ ","permalink":"https:\/\/linuxera.org\/integrating-cert-manager-with-cfssl-multirootca\/","summary":"Integrating cert-manager with CFSSL Multirootca In a previous post we saw how we could run our own PKI using the CFSSL tooling. This post assumes you have read the previous one.\nThe starting point is an empty Kubernetes cluster, we want to deploy cert-manager on it and on top of that we want to get it configured to issue certificates with our own PKI infrastructure running Multirootca.\nI\u2019ll be using a Kubernetes v1.","title":"Integrating cert-manager with CFSSL Multirootca"},{"content":"PKI with CFSSL In this post we will learn how to deploy our own Public Key Infrastructure (PKI) by using the CFSSL tooling. This may be useful if you want to run your own Certificate Authority (CA) in order to issue certificates for your systems and\/or users.\nIntroduction to CFSSL CFSSL is a tool set created by Cloudflare and released as Open Source software. Before you continue reading this post I&rsquo;d suggest reading this introductory post to PKI and CFSSL by Cloudflare.\nThis post assumes you already have basic knowledge on PKI and in how the CFSSL tooling works, if you don&rsquo;t have it, go read the post linked above.\nInstalling the CFSSL tooling In order to install the CFSSL tooling you can go to the GitHub Releases and download the binaries from there.\nWarning\nBelow commands will only work for Linux x86_64 machines.\nsudo curl -L https:\/\/github.com\/cloudflare\/cfssl\/releases\/download\/v1.6.4\/cfssl_1.6.4_linux_amd64 -o \/usr\/local\/bin\/cfssl sudo curl -L https:\/\/github.com\/cloudflare\/cfssl\/releases\/download\/v1.6.4\/cfssljson_1.6.4_linux_amd64 -o \/usr\/local\/bin\/cfssljson sudo curl -L https:\/\/github.com\/cloudflare\/cfssl\/releases\/download\/v1.6.4\/multirootca_1.6.4_linux_amd64 -o \/usr\/local\/bin\/multirootca sudo chmod +x \/usr\/local\/bin\/{cfssl,cfssljson,multirootca} PKI Organization For this example, the following organization will be used.\nCreating the Root CA Let&rsquo;s create a folder to store the PKI files:\nmkdir -p ~\/cafiles\/{root,intermediate,config,certificates} Before issuing the Root CA, we need to define its config:\nNote\nThe expiration is 10 years. You want to have a long expiration time for your Root CA to avoid having to re-roll the PKI too often.\ncat &lt;&lt; &#34;EOF&#34; &gt; ~\/cafiles\/root\/root-csr.json { &#34;CN&#34;: &#34;Linuxera Root Certificate Authority&#34;, &#34;key&#34;: { &#34;algo&#34;: &#34;ecdsa&#34;, &#34;size&#34;: 256 }, &#34;names&#34;: [ { &#34;C&#34;: &#34;ES&#34;, &#34;L&#34;: &#34;Valencia&#34;, &#34;O&#34;: &#34;Linuxera Internal&#34;, &#34;OU&#34;: &#34;CA Services&#34;, &#34;ST&#34;: &#34;Valencia&#34; } ], &#34;ca&#34;: { &#34;expiry&#34;: &#34;87600h&#34; } } EOF Issue the Root CA with cfssl:\ncfssl gencert -initca ~\/cafiles\/root\/root-csr.json | cfssljson -bare ~\/cafiles\/root\/root-ca At this point, we have our Root CA ready.\nCreating the Intermediate CA Issuing certificates directly with the Root CA is not advised. You should be issuing intermediary CAs with the Root CA instead. This allows for better organization of your PKI, and in case of a security incident you won&rsquo;t have to re-roll the whole PKI, instead you will only re-roll the affected Intermediate CA.\nFor this test, we will be issuing only an Intermediate CA. In real scenarios, is pretty common having multiple intermediates, and sometimes these intermediate CAs will be used to issue other intermediate CAs.\nDefine the Intermediate CA config:\nNote\nThe expiration is 8 years. For Intermediate CAs you also want to have quite a long expiration time.\ncat &lt;&lt; &#34;EOF&#34; &gt; ~\/cafiles\/intermediate\/intermediate-csr.json { &#34;CN&#34;: &#34;Linuxera Intermediate CA&#34;, &#34;key&#34;: { &#34;algo&#34;: &#34;ecdsa&#34;, &#34;size&#34;: 256 }, &#34;names&#34;: [ { &#34;C&#34;: &#34;ES&#34;, &#34;L&#34;: &#34;Valencia&#34;, &#34;O&#34;: &#34;Linuxera Internal&#34;, &#34;OU&#34;: &#34;Linuxera Internal Intermediate CA&#34;, &#34;ST&#34;: &#34;Valencia&#34; } ] } EOF Generate the key for the Intermediate CA:\ncfssl genkey ~\/cafiles\/intermediate\/intermediate-csr.json | cfssljson -bare ~\/cafiles\/intermediate\/intermediate-ca Define a CFSSL signing profile for the Intermediate CAs. This is done via a config file.\ncert sign and crl sign Expiration set to 8 years. CA constraints define that the certificates issued will be used by CAs is_ca: true and max_path_len: 1 limits this intermediate CA to only be able to issue sub-intermediate CAs that cannot issue additional CAs. (This could be allowed with max_path_len: 0 and max_path_len_zero: true). cat &lt;&lt; &#34;EOF&#34; &gt; ~\/cafiles\/config\/config.json { &#34;signing&#34;: { &#34;default&#34;: { &#34;expiry&#34;: &#34;8760h&#34; }, &#34;profiles&#34;: { &#34;intermediate&#34;: { &#34;usages&#34;: [&#34;cert sign&#34;, &#34;crl sign&#34;], &#34;expiry&#34;: &#34;70080h&#34;, &#34;ca_constraint&#34;: { &#34;is_ca&#34;: true, &#34;max_path_len&#34;: 1 } } } } } EOF Sign the Intermediate CA with the Root CA:\ncfssl sign -ca ~\/cafiles\/root\/root-ca.pem -ca-key ~\/cafiles\/root\/root-ca-key.pem -config ~\/cafiles\/config\/config.json -profile intermediate ~\/cafiles\/intermediate\/intermediate-ca.csr | cfssljson -bare ~\/cafiles\/intermediate\/intermediate-ca At this point, our Intermediate CA is ready to issue certificates, and we can take our Root CA offline. Usually, the private key gets stored in an HSM and after that it&rsquo;s deleted from the file system.\nrm -f ~\/cafiles\/root\/root-ca-key.pem Issuing certificates with the Intermediate CA Before issuing the certificate, we will add a new signing profile to our config. We will be defining a host signing profile that defines different usages as well as an expiration of 1 year for the certificates.\ncat &lt;&lt; &#34;EOF&#34; &gt; ~\/cafiles\/config\/config.json { &#34;signing&#34;: { &#34;default&#34;: { &#34;expiry&#34;: &#34;8760h&#34; }, &#34;profiles&#34;: { &#34;intermediate&#34;: { &#34;usages&#34;: [&#34;cert sign&#34;, &#34;crl sign&#34;], &#34;expiry&#34;: &#34;70080h&#34;, &#34;ca_constraint&#34;: { &#34;is_ca&#34;: true, &#34;max_path_len&#34;: 1 } }, &#34;host&#34;: { &#34;usages&#34;: [&#34;signing&#34;, &#34;digital signing&#34;, &#34;key encipherment&#34;, &#34;server auth&#34;], &#34;expiry&#34;: &#34;8760h&#34; } } } } EOF With the profile ready, let&rsquo;s create the certificate config:\ncat &lt;&lt; &#34;EOF&#34; &gt; ~\/cafiles\/certificates\/my-host-csr.json { &#34;CN&#34;: &#34;testhost.linuxera.org&#34;, &#34;hosts&#34;: [&#34;testhost.linuxera.org&#34;, &#34;192.168.122.120&#34;], &#34;names&#34;: [ { &#34;C&#34;: &#34;ES&#34;, &#34;L&#34;: &#34;Valencia&#34;, &#34;O&#34;: &#34;Linuxera Internal&#34;, &#34;OU&#34;: &#34;Linuxera Internal Hosts&#34; } ] } EOF Finally, use the cfssl tooling to issue this certificate with the Intermediate CA using the host profile:\ncfssl gencert -ca ~\/cafiles\/intermediate\/intermediate-ca.pem -ca-key ~\/cafiles\/intermediate\/intermediate-ca-key.pem -config ~\/cafiles\/config\/config.json -profile host ~\/cafiles\/certificates\/my-host-csr.json | cfssljson -bare ~\/cafiles\/certificates\/my-host At this point, we can verify the cert we just created:\nopenssl x509 -in ~\/cafiles\/certificates\/my-host.pem -noout -subject -issuer -startdate -enddate Note\nWe can see the issuer is our Intermediate CA.\nsubject=C = ES, L = Valencia, O = Linuxera Internal, OU = Linuxera Internal Hosts, CN = testhost.linuxera.org issuer=C = ES, ST = Valencia, L = Valencia, O = Linuxera Internal, OU = Linuxera Internal Intermediate CA, CN = Linuxera Intermediate CA notBefore=Aug 9 10:09:00 2023 GMT notAfter=Aug 8 10:09:00 2024 GMT If we check the certificate file ~\/cafiles\/certificates\/my-host.pem, we will see that it only contains the certificate for the host and not the full bundle (Intermediate CAs + Cert). We can generate a full chain cert with the command below:\nNote\nBundles are useful when you intend to use the certificate for an app like a web server, that way you will be sending the certificate + all the intermediate CAs certificates up to the Root CA so the client can verify its trust. Including the Root CA cert is not required, your client should already trust the Root CA, if it doesn&rsquo;t trust it that won&rsquo;t change even if you send it as part of the bundle.\ncfssl bundle -ca-bundle ~\/cafiles\/root\/root-ca.pem -int-bundle ~\/cafiles\/intermediate\/intermediate-ca.pem -cert ~\/cafiles\/certificates\/my-host.pem | cfssljson -bare ~\/cafiles\/certificates\/my-host-fullchain We should have the bundled cert available:\nWarning\nIn some Linux distributions, the previous cfssl bundle command may not generate the bundled cert. If that&rsquo;s the case you can get the same result by running cat ~\/cafiles\/certificates\/my-host.pem ~\/cafiles\/intermediate\/intermediate-ca.pem &gt; ~\/cafiles\/certificates\/my-host-fullchain.pem\ncat ~\/cafiles\/certificates\/my-host-fullchain.pem -----BEGIN CERTIFICATE----- MII... -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MII... -----END CERTIFICATE----- Finally, we could verify the cert:\nopenssl verify -CAfile &lt;(cat ~\/cafiles\/root\/root-ca.pem ~\/cafiles\/intermediate\/intermediate-ca.pem) ~\/cafiles\/certificates\/my-host.pem \/home\/mario\/cafiles\/certificates\/my-host.pem: OK Exposing our PKI to remote systems with MultiRootCA So far, we have been using cfssl tooling to issue certificates while connected to a system where our PKI is stored. In real environments, you may need to issue certificates for different people\/systems in a more convenient way.\nThe MultiRootCA program is an authenticated-signer-only server that is used as a remote server for cfssl instances. It is intended for:\nRunning cfssl as a service on servers to generate keys. Act as a remote signer to manage the CA keys for issuing certificates. Let&rsquo;s start by issuing a certificate for the multirooca server:\ncat &lt;&lt; &#34;EOF&#34; &gt; ~\/cafiles\/certificates\/multirootca-server-csr.json { &#34;CN&#34;: &#34;multirootca-server.linuxera.org&#34;, &#34;hosts&#34;: [&#34;multirootca-server.linuxera.org&#34;, &#34;192.168.122.153&#34;], &#34;names&#34;: [ { &#34;C&#34;: &#34;ES&#34;, &#34;L&#34;: &#34;Valencia&#34;, &#34;O&#34;: &#34;Linuxera Internal&#34;, &#34;OU&#34;: &#34;Linuxera Internal Hosts&#34; } ] } EOF cfssl gencert -ca ~\/cafiles\/intermediate\/intermediate-ca.pem -ca-key ~\/cafiles\/intermediate\/intermediate-ca-key.pem -config ~\/cafiles\/config\/config.json -profile host ~\/cafiles\/certificates\/multirootca-server-csr.json | cfssljson -bare ~\/cafiles\/certificates\/multirootca-server We will secure the signing profiles in our config. We will be defining an auth_key that clients requesting a signed certificate must provide in order to get it signed.\nNote\nThe Auth Key is a 16 byte hexadecimal string. You can generate one by running openssl rand -hex 16\ncat &lt;&lt; &#34;EOF&#34; &gt; ~\/cafiles\/config\/config.json { &#34;signing&#34;: { &#34;default&#34;: { &#34;expiry&#34;: &#34;8760h&#34; }, &#34;profiles&#34;: { &#34;intermediate&#34;: { &#34;usages&#34;: [&#34;cert sign&#34;, &#34;crl sign&#34;], &#34;expiry&#34;: &#34;70080h&#34;, &#34;ca_constraint&#34;: { &#34;is_ca&#34;: true, &#34;max_path_len&#34;: 1 } }, &#34;host&#34;: { &#34;usages&#34;: [&#34;signing&#34;, &#34;digital signing&#34;, &#34;key encipherment&#34;, &#34;server auth&#34;, &#34;client auth&#34;], &#34;expiry&#34;: &#34;8760h&#34;, &#34;auth_key&#34;: &#34;default&#34; } } }, &#34;auth_keys&#34;: { &#34;default&#34;: { &#34;key&#34;: &#34;b50ed348c4643d34706470f36a646fd4&#34;, &#34;type&#34;: &#34;standard&#34; } } } EOF We need to tell multirootca where to find the different certificates for our Intermediate CA:\ncat &lt;&lt;EOF &gt; ~\/cafiles\/config\/multiroot-profile.ini [linuxeraintermediate] private = file:\/\/${HOME}\/cafiles\/intermediate\/intermediate-ca-key.pem certificate = ${HOME}\/cafiles\/intermediate\/intermediate-ca.pem config = ${HOME}\/cafiles\/config\/config.json EOF Finally, we can run the multirootca server:\nmultirootca -a 0.0.0.0:8000 -l default -roots ~\/cafiles\/config\/multiroot-profile.ini -tls-cert ~\/cafiles\/certificates\/multirootca-server.pem -tls-key ~\/cafiles\/certificates\/multirootca-server-key.pem A more appropriate way of running the server would be using a systemd service:\ncat &lt;&lt;EOF | sudo tee \/etc\/systemd\/system\/multirootca.service [Unit] Description=CFSSL PKI Certificate Authority After=network.target [Service] User=${USER} ExecStart=\/usr\/local\/bin\/multirootca -a 0.0.0.0:8000 -l linuxeraintermediate -roots ${HOME}\/cafiles\/config\/multiroot-profile.ini -tls-cert ${HOME}\/cafiles\/certificates\/multirootca-server.pem -tls-key ${HOME}\/cafiles\/certificates\/multirootca-server-key.pem Restart=on-failure Type=simple [Install] WantedBy=multi-user.target EOF sudo systemctl daemon-reload sudo systemctl enable multirootca --now Requesting certificates to the multirootca Now that the Intermediate CA has been exposed with the multirootca program, we can go ahead and request it to sign some certificates. We can do this from a remote location, or from the same server where multirootca is running.\nGenerate a certificate config:\ncat &lt;&lt; &#34;EOF&#34; &gt; my-cert-request-csr.json { &#34;CN&#34;: &#34;myserver.linuxera.org&#34;, &#34;hosts&#34;: [&#34;myserver.linuxera.org&#34;, &#34;192.168.122.222&#34;], &#34;names&#34;: [ { &#34;C&#34;: &#34;ES&#34;, &#34;L&#34;: &#34;Valencia&#34;, &#34;O&#34;: &#34;Linuxera Internal&#34;, &#34;OU&#34;: &#34;Linuxera Internal Hosts&#34; } ] } EOF Generate a request profile. This is required for cfssl to know how to request the certificate to the multirootca:\nWarning\nWe need to define the Auth key, otherwise multirootca will not sign our certificate. And the location of the multirootca server, we can use IP:Port or DNS:Port.\ncat &lt;&lt;EOF &gt; request-profile.json { &#34;signing&#34;: { &#34;default&#34;: { &#34;auth_remote&#34;: { &#34;remote&#34;: &#34;ca_server&#34;, &#34;auth_key&#34;: &#34;default&#34; } } }, &#34;auth_keys&#34;: { &#34;default&#34;: { &#34;key&#34;: &#34;b50ed348c4643d34706470f36a646fd4&#34;, &#34;type&#34;: &#34;standard&#34; } }, &#34;remotes&#34;: { &#34;ca_server&#34;: &#34;https:\/\/multirootca-server.linuxera.org:8000&#34; } } EOF Finally, we send the request by specifying the host profile, which is the one we will be using for signing host certificates:\nWarning\nWe need to specify the Intermediate CA certificate via the -tls-remote-ca flag.\ncfssl gencert -config .\/request-profile.json -tls-remote-ca .\/intermediate-ca.pem -profile host .\/my-cert-request-csr.json | cfssljson -bare my-cert 2023\/08\/09 11:43:15 [INFO] generate received request 2023\/08\/09 11:43:15 [INFO] received CSR 2023\/08\/09 11:43:15 [INFO] generating key: ecdsa-256 2023\/08\/09 11:43:15 [INFO] encoded CSR 2023\/08\/09 11:43:15 [INFO] Using trusted CA from tls-remote-ca: .\/intermediate-ca.pem We should have a valid certificate now:\nopenssl x509 -in .\/my-cert.pem -noout -subject -issuer -startdate -enddate subject=C = ES, L = Valencia, O = Linuxera Internal, OU = Linuxera Internal Hosts, CN = myserver.linuxera.org issuer=C = ES, ST = Valencia, L = Valencia, O = Linuxera Internal, OU = Linuxera Internal Intermediate CA, CN = Linuxera Intermediate CA notBefore=Aug 9 11:38:00 2023 GMT notAfter=Aug 8 11:38:00 2024 GMT Closing Thoughts We have seen how to run our own PKI with the CFSSL tooling, in the next post we will see how to leverage this PKI from Kubernetes by using cert-manager.\nUseful Resources https:\/\/blog.cloudflare.com\/how-to-build-your-own-public-key-infrastructure\/ https:\/\/www.ekervhen.xyz\/posts\/private-ca-with-cfssl\/ ","permalink":"https:\/\/linuxera.org\/pki-with-cfssl\/","summary":"PKI with CFSSL In this post we will learn how to deploy our own Public Key Infrastructure (PKI) by using the CFSSL tooling. This may be useful if you want to run your own Certificate Authority (CA) in order to issue certificates for your systems and\/or users.\nIntroduction to CFSSL CFSSL is a tool set created by Cloudflare and released as Open Source software. Before you continue reading this post I&rsquo;d suggest reading this introductory post to PKI and CFSSL by Cloudflare.","title":"PKI with CFSSL"},{"content":"Gateway API for Kubernetes In this post we will go over a new project by the SIG-NETWORK that aims to evolve Kubernetes service networking.\nI&rsquo;ll be using a Kubernetes v1.26 (latest at the time of this writing). The tool used to create the cluster is kcli and the command used was:\nkcli create kube generic -P ctlplanes=1 -P workers=1 -P ctlplane_memory=4096 -P numcpus=8 -P worker_memory=8192 -P image=fedora37 -P sdn=calico -P version=1.26 -P ingress=false -P metallb=true -P domain=linuxera.org gateway-api-cluster Introduction to Kubernetes Gateway API As we said in the previous section, Gateway API is a new project by the SIG-NETWORK. This project aims to become the preferred solution for managing external traffic into a Kubernetes cluster.\nCompared to traditional Ingress Controllers, Gateway API provides a more declarative and standardized approach to configuring and managing network traffic.\nFor example, Gateway API allows the definition and configuration for routing, load balancing, and other traffic policies in a more consistent and unified manner, regardless of the underlying infrastructure or cloud provider.\nOn top of that, effort has been put in making Gateway API more extensible and support a wider range of uses cases, making it a more future-proof solution for managing traffic in modern cloud-native environments.\nNew APIs Gateway API introduces new APIs to our Kubernetes clusters, you can see the APIs as well as the target personas in the image below:\nImage Source\nGatewayClass The infrastructure provider will offer one or more GatewayClasses for the user. A decoupling mechanism will implement the Gateway (usually a controller) from the user.\nFor example, the infrastructure provider could create two GatewayClasses:\ninternal: Can be used to expose apps internally. external: Can be used to expose apps externally. Then some Gateway will implement these GatewayClasses and the user don&rsquo;t need to know how that&rsquo;s implemented, instead user only chooses if the app gets externally published or not.\nYou can read more about the GatewayClass here.\nGateway When the cluster operator creates a Gateway that triggers an action in the infrastructure like:\nCall a cloud API to create a Load Balancer. Deploy a software load balancer in the cluster. etc. The Gateway always has a reference to the GatewayClass that it implements, and at the same time the GatewayClass has a reference to the controller (or decoupling mechanism) that implements the GatewayClass itself.\nThe Gateway object defines some other properties like which ports, protocols, tls settings, etc.\nYou can read more about the Gateway here.\nHTTPRoute Application developers will make use of HTTPRoutes in order to get ingress traffic to their applications. This API specifies the routing behavior for HTTP\/s requests from the Gateway listener to a service.\nBelow image shows how traffic flows from client to pod:\nImage Source\nYou can read more about the HTTPRoute here.\nTrying Gateway API with NGinx Gateway Controller In this section we will be deploying all the required bits to expose an application via HTTP\/s using HTTPRoutes. Three scenarios will be covered:\nExposing an APP via HTTP. Blue\/Green with weights. Exposing an APP via HTTPs. The following software versions were used:\nKubernetes v1.26.4 Gateway API v0.6.2 MetalLB v0.13.9 Deploying the Gateway API For this introduction we are deploying the standard APIs, so we won&rsquo;t get support for TCPRoute, TLSRoute, etc. Only basic support for HTTPRoute will be available.\nDeploy the Gateway API CRDs and admission server\nkubectl apply -f https:\/\/github.com\/kubernetes-sigs\/gateway-api\/releases\/download\/v0.6.2\/standard-install.yaml If we check the pods created in the gateway-system namespace, we will see the admission server running:\nkubectl -n gateway-system get pods NAME READY STATUS RESTARTS AGE gateway-api-admission-l2dnj 0\/1 Completed 0 30s gateway-api-admission-patch-sh6tw 0\/1 Completed 1 30s gateway-api-admission-server-546bdb8747-q5jxw 1\/1 Running 0 30s At this point we have the Gateway API running, next step will be choosing the Gateway API implementation we want to use. You can find a list of current implementations here. For this post, we will be using the NGinx Gateway implementation.\nDeploying the NGinx Gateway Controller The code for the controller can be found here.\nThe instructions to deploy the controller use the commit 23092c6e1b17e91177bdb5f43bef477f90d1cc63 which is the content of the main branch as of April 24th.\nCreate the namespace where the controller will be deployed:\nkubectl apply -f https:\/\/raw.githubusercontent.com\/nginxinc\/nginx-kubernetes-gateway\/23092c6e1b17e91177bdb5f43bef477f90d1cc63\/deploy\/manifests\/namespace.yaml Create the njs-modules, this is used by NGinx to implement the data plane:\nNote\nnjs is a subset of the JavaScript language that allows extending nginx functionality.\ncurl -L https:\/\/raw.githubusercontent.com\/nginxinc\/nginx-kubernetes-gateway\/23092c6e1b17e91177bdb5f43bef477f90d1cc63\/internal\/nginx\/modules\/src\/httpmatches.js -o \/tmp\/httpmatches.js kubectl -n nginx-gateway create configmap njs-modules --from-file=\/tmp\/httpmatches.js rm -f \/tmp\/httpmatches.js Create the GatewayClass that will use the nginx controller as backend:\nkubectl apply -f https:\/\/raw.githubusercontent.com\/nginxinc\/nginx-kubernetes-gateway\/23092c6e1b17e91177bdb5f43bef477f90d1cc63\/deploy\/manifests\/gatewayclass.yaml Finally, deploy the NGinx Gateway Controller:\nNote\nContainer nginx-gateway is using ghcr.io\/nginxinc\/nginx-kubernetes-gateway:edge which at the time of this writing points to ghcr.io\/nginxinc\/nginx-kubernetes-gateway@sha256:e67a8e8553a581404cfbf1343f60c67cd9a6c68436b7367bb1ea8fbbef862c8e.\nkubectl apply -f https:\/\/raw.githubusercontent.com\/nginxinc\/nginx-kubernetes-gateway\/23092c6e1b17e91177bdb5f43bef477f90d1cc63\/deploy\/manifests\/nginx-gateway.yaml After a few moments, the controller pod will be running:\nkubectl -n nginx-gateway get pods NAME READY STATUS RESTARTS AGE nginx-gateway-54dc684b98-xnrv8 2\/2 Running 0 30s We need to expose the gateway controller, we will be using a LoadBalancer service for that. In our cluster we are using MetalLB.\nNote\nYou can read how to deploy MetalLB on the official docs. If you&rsquo;re running on a cloud provider, you should be good to go without MetalLB.\nkubectl apply -f https:\/\/raw.githubusercontent.com\/nginxinc\/nginx-kubernetes-gateway\/23092c6e1b17e91177bdb5f43bef477f90d1cc63\/deploy\/manifests\/service\/loadbalancer.yaml We should have a Service with an external IP set:\nkubectl -n nginx-gateway get svc NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE nginx-gateway LoadBalancer 10.107.59.82 192.168.122.240 80:30970\/TCP,443:31783\/TCP 7s In order to be able to expose our applications we need proper DNS resolution, we will be configuring a wildcard record in our DNS server. In this case we&rsquo;re creating a record *.apps.gateway-api.test.lab that points to the external IP 192.168.122.240.\nNote\nThis wildcard domain will be used when exposing our apps.\ndig +short anything.apps.gateway-api.test.lab 192.168.122.240 At this point we are ready to start exposing our applications with the NGinx Gateway.\nExposing applications with the NGinx Gateway As previously stated, the following scenarios will be covered:\nExposing an APP via HTTP. Blue\/Green with weights. Exposing an APP via HTTPs. Exposing an APP via HTTP For this scenario we are just deploying a simple app and making it available for HTTP calls.\nDeploy the simple app:\ncat &lt;&lt;EOF | kubectl apply -f - --- apiVersion: v1 kind: Namespace metadata: name: reverse-words --- apiVersion: apps\/v1 kind: Deployment metadata: name: reverse-words-blue namespace: reverse-words labels: app: reverse-words-blue spec: replicas: 1 selector: matchLabels: app: reverse-words-blue template: metadata: labels: app: reverse-words-blue spec: containers: - name: reverse-words image: quay.io\/mavazque\/reversewords:0.27 ports: - containerPort: 8080 name: http env: - name: RELEASE value: &#34;Blue&#34; livenessProbe: httpGet: path: \/health port: 8080 initialDelaySeconds: 5 timeoutSeconds: 2 periodSeconds: 15 readinessProbe: httpGet: path: \/health port: 8080 initialDelaySeconds: 10 timeoutSeconds: 2 periodSeconds: 15 --- apiVersion: v1 kind: Service metadata: labels: app: reverse-words-blue name: reverse-words-blue namespace: reverse-words spec: ports: - port: 8080 protocol: TCP targetPort: http name: http selector: app: reverse-words-blue type: ClusterIP EOF With the app running we will create a Gateway resource pointing to the NGinx Gateway Class created earlier. On top of that, it will only listen for HTTP connections on port 80:\nNote\nWhen creating HTTPRoutes in the reverse-words namespace we will reference this Gateway and the listener to be used to expose our application. We can have multiple Gateways per namespace, for example: One Gateway that exposes services using NGinx, another one that uses HAProxy, and a third one that uses F5 Big IP, etc.\ncat &lt;&lt;EOF | kubectl apply -f - apiVersion: gateway.networking.k8s.io\/v1beta1 kind: Gateway metadata: name: gateway namespace: reverse-words labels: domain: k8s-gateway.nginx.org spec: gatewayClassName: nginx listeners: - name: http port: 80 protocol: HTTP EOF Finally, let&rsquo;s create the HTTPRoute:\nNote\nThis HTTPRoute uses the Gateway named gateway in this namespace, and will use the listener http to publish the route. The Service being exposed is the reverse-words-blue service on port 8080.\ncat &lt;&lt;EOF | kubectl apply -f - apiVersion: gateway.networking.k8s.io\/v1beta1 kind: HTTPRoute metadata: name: reversewords namespace: reverse-words spec: parentRefs: - name: gateway sectionName: http hostnames: - reverse-words.apps.gateway-api.test.lab rules: - backendRefs: - name: reverse-words-blue port: 8080 EOF We can now access our application:\ncurl http:\/\/reverse-words.apps.gateway-api.test.lab Reverse Words Release: Blue. App version: v0.0.27 Blue\/Green with weights In this scenario we have two versions of the same service, and we will move traffic gradually to the newer version.\nAttention\nThis scenario relies on the application deployed on the previous section.\nDeploy the new version of our application (Green)\ncat &lt;&lt;EOF | kubectl apply -f - apiVersion: apps\/v1 kind: Deployment metadata: name: reverse-words-green namespace: reverse-words labels: app: reverse-words-green spec: replicas: 1 selector: matchLabels: app: reverse-words-green template: metadata: labels: app: reverse-words-green spec: containers: - name: reverse-words image: quay.io\/mavazque\/reversewords:0.28 ports: - containerPort: 8080 name: http env: - name: RELEASE value: &#34;Green&#34; livenessProbe: httpGet: path: \/health port: 8080 initialDelaySeconds: 5 timeoutSeconds: 2 periodSeconds: 15 readinessProbe: httpGet: path: \/health port: 8080 initialDelaySeconds: 10 timeoutSeconds: 2 periodSeconds: 15 --- apiVersion: v1 kind: Service metadata: labels: app: reverse-words-green name: reverse-words-green namespace: reverse-words spec: ports: - port: 8080 protocol: TCP targetPort: http name: http selector: app: reverse-words-green type: ClusterIP EOF Patch the old HTTPRoute and add the new backend + weights:\nNote\nBelow route will send most of the request to the old service (Blue) and a few ones to the new one (Green).\ncat &lt;&lt;EOF | kubectl apply -f - apiVersion: gateway.networking.k8s.io\/v1beta1 kind: HTTPRoute metadata: name: reversewords namespace: reverse-words spec: parentRefs: - name: gateway sectionName: http hostnames: - reverse-words.apps.gateway-api.test.lab rules: - backendRefs: - name: reverse-words-blue port: 8080 weight: 90 - name: reverse-words-green port: 8080 weight: 10 EOF If we try to access our application this is what we will get:\nfor i in $(seq 1 10);do curl http:\/\/reverse-words.apps.gateway-api.test.lab; done Reverse Words Release: Blue. App version: v0.0.27 Reverse Words Release: Blue. App version: v0.0.27 Reverse Words Release: Blue. App version: v0.0.27 Reverse Words Release: Blue. App version: v0.0.27 Reverse Words Release: Blue. App version: v0.0.27 Reverse Words Release: Blue. App version: v0.0.27 Reverse Words Release: Blue. App version: v0.0.27 Reverse Words Release: Green. App version: v0.0.28 Reverse Words Release: Blue. App version: v0.0.27 Reverse Words Release: Blue. App version: v0.0.27 We can update the weights, so traffic gets distributed evenly:\nkubectl -n reverse-words patch httproute reversewords -p &#39;{&#34;spec&#34;:{&#34;rules&#34;:[{&#34;backendRefs&#34;:[{&#34;group&#34;:&#34;&#34;,&#34;kind&#34;:&#34;Service&#34;,&#34;name&#34;:&#34;reverse-words-blue&#34;,&#34;port&#34;:8080,&#34;weight&#34;:50},{&#34;group&#34;:&#34;&#34;,&#34;kind&#34;:&#34;Service&#34;,&#34;name&#34;:&#34;reverse-words-green&#34;,&#34;port&#34;:8080,&#34;weight&#34;:50}],&#34;matches&#34;:[{&#34;path&#34;:{&#34;type&#34;:&#34;PathPrefix&#34;,&#34;value&#34;:&#34;\/&#34;}}]}]}}&#39; --type merge And check the impact:\nfor i in $(seq 1 10);do curl http:\/\/reverse-words.apps.gateway-api.test.lab; done Reverse Words Release: Blue. App version: v0.0.27 Reverse Words Release: Green. App version: v0.0.28 Reverse Words Release: Blue. App version: v0.0.27 Reverse Words Release: Blue. App version: v0.0.27 Reverse Words Release: Blue. App version: v0.0.27 Reverse Words Release: Blue. App version: v0.0.27 Reverse Words Release: Green. App version: v0.0.28 Reverse Words Release: Blue. App version: v0.0.27 Reverse Words Release: Green. App version: v0.0.28 Reverse Words Release: Green. App version: v0.0.28 We can move weight to 0 to remove the old service (Blue) from the load balancing:\nkubectl -n reverse-words patch httproute reversewords -p &#39;{&#34;spec&#34;:{&#34;rules&#34;:[{&#34;backendRefs&#34;:[{&#34;group&#34;:&#34;&#34;,&#34;kind&#34;:&#34;Service&#34;,&#34;name&#34;:&#34;reverse-words-blue&#34;,&#34;port&#34;:8080,&#34;weight&#34;:0},{&#34;group&#34;:&#34;&#34;,&#34;kind&#34;:&#34;Service&#34;,&#34;name&#34;:&#34;reverse-words-green&#34;,&#34;port&#34;:8080,&#34;weight&#34;:100}],&#34;matches&#34;:[{&#34;path&#34;:{&#34;type&#34;:&#34;PathPrefix&#34;,&#34;value&#34;:&#34;\/&#34;}}]}]}}&#39; --type merge for i in $(seq 1 10);do curl http:\/\/reverse-words.apps.gateway-api.test.lab; done Reverse Words Release: Green. App version: v0.0.28 Reverse Words Release: Green. App version: v0.0.28 Reverse Words Release: Green. App version: v0.0.28 Reverse Words Release: Green. App version: v0.0.28 Reverse Words Release: Green. App version: v0.0.28 Reverse Words Release: Green. App version: v0.0.28 Reverse Words Release: Green. App version: v0.0.28 Reverse Words Release: Green. App version: v0.0.28 Reverse Words Release: Green. App version: v0.0.28 Reverse Words Release: Green. App version: v0.0.28 Exposing an APP via HTTPs For this scenario we are just configuring the Gateway to do TLS termination at the edge, after that we will expose our simple app via HTTPs and redirect HTTP requests to the HTTPs port.\nAttention\nThis scenario relies on the application deployed on the previous section.\nWe need a TLS cert, let&rsquo;s generate a self-signed one:\nopenssl req -new -newkey rsa:2048 -sha256 -days 3650 -nodes -x509 -extensions v3_ca -keyout \/tmp\/tls.key -out \/tmp\/tls.crt -subj &#34;\/C=ES\/ST=Valencia\/L=Valencia\/O=IT\/OU=IT\/CN=*.apps.gateway-api.test.lab&#34; -addext &#34;subjectAltName = DNS:*.apps.gateway-api.test.lab&#34; The certificate needs to be stored in a secret:\nkubectl -n reverse-words create secret tls reversewords-gateway-tls --cert=\/tmp\/tls.crt --key=\/tmp\/tls.key The Gateway needs to be updated, a new listener for the https protocol will be created on port 443. This listener will be our TLS terminator and will use the certificate we just created:\ncat &lt;&lt;EOF | kubectl apply -f - apiVersion: gateway.networking.k8s.io\/v1beta1 kind: Gateway metadata: name: gateway namespace: reverse-words labels: domain: k8s-gateway.nginx.org spec: gatewayClassName: nginx listeners: - name: http port: 80 protocol: HTTP - name: https port: 443 protocol: HTTPS tls: mode: Terminate certificateRefs: - kind: Secret name: reversewords-gateway-tls namespace: reverse-words EOF Let&rsquo;s remove the old HTTPRoute and create a new one exposing the app via HTTPs:\nkubectl -n reverse-words delete httproute reversewords cat &lt;&lt;EOF | kubectl apply -f - apiVersion: gateway.networking.k8s.io\/v1beta1 kind: HTTPRoute metadata: name: reversewords namespace: reverse-words spec: parentRefs: - name: gateway sectionName: https hostnames: - reverse-words.apps.gateway-api.test.lab rules: - backendRefs: - name: reverse-words-green port: 8080 EOF We can now access our app via https:\ncurl -k https:\/\/reverse-words.apps.gateway-api.test.lab Reverse Words Release: Green. App version: v0.0.28 If we try to access the app via http:\ncurl http:\/\/reverse-words.apps.gateway-api.test.lab Note\nOur HTTPRoute does not expose the app via http, this is expected.\n&lt;html&gt; &lt;head&gt;&lt;title&gt;404 Not Found&lt;\/title&gt;&lt;\/head&gt; &lt;body&gt; &lt;center&gt;&lt;h1&gt;404 Not Found&lt;\/h1&gt;&lt;\/center&gt; &lt;hr&gt;&lt;center&gt;nginx\/1.23.4&lt;\/center&gt; &lt;\/body&gt; &lt;\/html&gt; Usually you want to redirect users hitting the HTTP endpoint to the HTTPs endpoint, lets configure that:\nNote\nWe need to create a new HTTPRoute, but if you take a closer look you will not see any backends being referenced, instead we are applying a RequestRedirect filter to tell the client to go look the HTTPs endpoint. More on filters here.\ncat &lt;&lt;EOF | kubectl apply -f - apiVersion: gateway.networking.k8s.io\/v1beta1 kind: HTTPRoute metadata: name: reversewords-tls-redirect namespace: reverse-words spec: parentRefs: - name: gateway sectionName: http hostnames: - reverse-words.apps.gateway-api.test.lab rules: - filters: - type: RequestRedirect requestRedirect: scheme: https port: 443 EOF If we access the HTTP endpoint, we&rsquo;re told to go somewhere else:\ncurl http:\/\/reverse-words.apps.gateway-api.test.lab &lt;html&gt; &lt;head&gt;&lt;title&gt;302 Found&lt;\/title&gt;&lt;\/head&gt; &lt;body&gt; &lt;center&gt;&lt;h1&gt;302 Found&lt;\/h1&gt;&lt;\/center&gt; &lt;hr&gt;&lt;center&gt;nginx\/1.23.4&lt;\/center&gt; &lt;\/body&gt; &lt;\/html&gt; If we tell curl to follow redirects (-L):\ncurl -Lk http:\/\/reverse-words.apps.gateway-api.test.lab Reverse Words Release: Green. App version: v0.0.28 Closing Thoughts Gateway API is a step forward in terms of standardization, allowing better integrations with 3rd party providers as well as providing a more general API for proxying that can be used for more protocols than just HTTP.\nIt&rsquo;s important to keep in mind that Gateway API will not be replacing the Ingress API, instead as stated above it will be used to enable proxying of other protocols on top of HTTP like gRPC, TCP, etc.\nUseful Resources https:\/\/gateway-api.sigs.k8s.io\/ https:\/\/gateway-api.sigs.k8s.io\/v1alpha2\/guides\/ https:\/\/gateway-api.sigs.k8s.io\/api-types\/httproute\/ https:\/\/gateway-api.sigs.k8s.io\/api-types\/referencegrant\/ https:\/\/github.com\/nginxinc\/nginx-kubernetes-gateway\/blob\/main\/docs\/installation.md ","permalink":"https:\/\/linuxera.org\/gateway-api-kubernetes\/","summary":"Gateway API for Kubernetes In this post we will go over a new project by the SIG-NETWORK that aims to evolve Kubernetes service networking.\nI&rsquo;ll be using a Kubernetes v1.26 (latest at the time of this writing). The tool used to create the cluster is kcli and the command used was:\nkcli create kube generic -P ctlplanes=1 -P workers=1 -P ctlplane_memory=4096 -P numcpus=8 -P worker_memory=8192 -P image=fedora37 -P sdn=calico -P version=1.","title":"Gateway API for Kubernetes"},{"content":"CPU and Memory Management on Kubernetes with Cgroupsv2 In this post I&rsquo;ll try to explain how CPU and Memory management works under the hood on Kubernetes. If you ever wondered what happens when you set requests and limits for your pods, keep reading!\nAttention\nThis is the result of my exploratory work around cgroupsv2 and their application to Kubernetes. Even though I tried really hard to make sure the information in this post is accurate, I&rsquo;m far from being an expert on the topic and some information may not be 100% accurate. If you detect something that is missing \/ wrong, please comment on the post!\nI&rsquo;ll be using a Kubernetes v1.26 (latest at the time of this writing) with an operating system with support for cgroupsv2 like Fedora 37. The tool used to create the cluster is kcli and the command used was:\nkcli create kube generic -P ctlplanes=1 -P workers=1 -P ctlplane_memory=4096 -P numcpus=8 -P worker_memory=8192 -P image=fedora37 -P sdn=calico -P version=1.26 -P ingress=true -P ingress_method=nginx -P metallb=true -P domain=linuxera.org resource-mgmt-cluster Introduction to Cgroups As we explained in a previous post, Cgroups can be used to limit what resources are available to processes on the system, since containers are processes this applies to them as well. In Kubernetes it&rsquo;s not different.\nCgroups version 2 introduces improvements and new features on top of Cgroups version 1, you can read more about what changed in this link.\nIn the next sections we will see how we can limit memory and cpu for processes.\nLimiting memory using Cgroupsv2 An evolved memory controller is available in Cgroupsv2, it allows for better management of memory resources for the processes inside the cgroup. In this section we will cover how to hard limit a process to a given amount of memory, and how to use new controls to make our programs work on memory-restricted environments.\nHard limiting memory Hard limiting memory is pretty straightforward, we just set a memory.max and since the memory is a resource that cannot be compressed, once the process reaches the limit it will be killed.\nWe will be using this python script:\ncat &lt;&lt;EOF &gt; \/opt\/dumb.py f = open(&#34;\/dev\/urandom&#34;, &#34;r&#34;, encoding = &#34;ISO-8859-1&#34;) data = &#34;&#34; i=0 while i &lt; 20: data += f.read(10485760) # 10MiB i += 1 print(&#34;Used %d MiB&#34; % (i * 10)) EOF Let&rsquo;s create a new cgroup under the system.slice:\nsudo mkdir -p \/sys\/fs\/cgroup\/system.slice\/memorytest Set a limit of 200MiB of RAM for this cgroup and disable swap:\necho &#34;200M&#34; &gt; \/sys\/fs\/cgroup\/system.slice\/memorytest\/memory.max echo &#34;0&#34; &gt; \/sys\/fs\/cgroup\/system.slice\/memorytest\/memory.swap.max Add the current shell process to the cgroup:\necho $$ &gt; \/sys\/fs\/cgroup\/system.slice\/memorytest\/cgroup.procs Run the python script:\npython3 \/opt\/dumb.py Attention\nEven if the script stopped at 80MB that&rsquo;s caused because the python interpreter + shared libraries consume also memory. We can check the current memory usage in the cgroup by using the systemd-cgtop system.slice\/memorytest command or with something like this MEMORY=$(cat \/sys\/fs\/cgroup\/system.slice\/memorytest\/memory.current);echo $(( $MEMORY \/ 1024 \/ 1024 ))MiB\nUsed 10 MiB Used 20 MiB Used 30 MiB Used 40 MiB Used 50 MiB Used 60 MiB Used 70 MiB Used 80 MiB Killed Remove the cgroup:\nWarning\nMake sure you closed the shell attached to the cgroup before running the command below, otherwise it will fail.\nsudo rmdir \/sys\/fs\/cgroup\/system.slice\/memorytest\/ Better memory management In the previous section we have seen how to hard-limit our processes to a given amount of memory, in this section we will be making use of new configurations to better allow our program to run under memory-restricted scenarios.\nAs we said, memory cannot be compressed, and as such, when a process reaches the limit set it will be OOMKilled. While this remains true, some memory in use by our program can be reclaimed by the kernel. This will free some memory that is no longer in use.\nIn Cgroupsv2 we can work with the following memory configurations:\nmemory.high: Memory usage throttle limit. If the cgroup goes over this limit, the cgroup processes will be throttled and put under heavy reclaim pressure. memory.max: As we saw earlier, this is the memory usage hard limit. Anything going beyond this number gets OOMKilled. memory.low: Best-effort memory protection. While processes in this cgroup or child cgroups are below this threshold, the cgroup memory won&rsquo;t be reclaimed unless it cannot be reclaimed from other unprotected cgroups. memory.min: Specifies a minimum amount of memory that the cgroup must always retain and that won&rsquo;t be reclaimed by the system under any conditions as long as the memory usage is below the threshold defined. memory.swap.high: Same as memory.high but for swap. memory.swap.max: Same as memory.max but for swap. Note\nMemory throttling is a resource control mechanism that limits the amount of memory a process can use, when throttled the kernel will try to reclaim memory. Keep in mind that memory reclaiming is an I\/O expensive process.\nIn order to demonstrate how this works, we will be using the same python script we used previously.\nLet&rsquo;s create a new cgroup under the system.slice:\nsudo mkdir -p \/sys\/fs\/cgroup\/system.slice\/memorytest2 Set a limit of 200MiB of RAM for this cgroup and disable swap:\necho &#34;200M&#34; &gt; \/sys\/fs\/cgroup\/system.slice\/memorytest2\/memory.max echo &#34;0&#34; &gt; \/sys\/fs\/cgroup\/system.slice\/memorytest2\/memory.swap.max Set a throttle limit of 150MiB:\necho &#34;150M&#34; &gt; \/sys\/fs\/cgroup\/system.slice\/memorytest2\/memory.high Add the current shell process to the cgroup:\necho $$ &gt; \/sys\/fs\/cgroup\/system.slice\/memorytest2\/cgroup.procs Run the python script:\npython3 \/opt\/dumb.py Used 10 MiB Used 20 MiB Used 30 MiB Used 40 MiB Used 50 MiB Used 60 MiB Used 70 MiB &lt;Hangs here&gt; Delete the cgroup:\nWarning\nMake sure you closed the shell attached to the cgroup before running the command below, otherwise it will fail.\nsudo rmdir \/sys\/fs\/cgroup\/system.slice\/memorytest2\/ We tried to limit the memory consumption for our process, and we failed. Determining the exact amount of memory required by an application is a difficult and error-prone task. Luckily for us, Facebook folks created senpain. Let&rsquo;s see how we can use it to better determine the configuration for our process.\nDownload senpai:\ncurl -L https:\/\/raw.githubusercontent.com\/facebookincubator\/senpai\/main\/senpai.py -o \/tmp\/senpai.py Create a new cgroup under the system.slice:\nsudo mkdir -p \/sys\/fs\/cgroup\/system.slice\/memorytest3 Add the current shell process to the cgroup:\necho $$ &gt; \/sys\/fs\/cgroup\/system.slice\/memorytest3\/cgroup.procs Run senpai in a different shell with the following command:\npython3 \/tmp\/senpay.py Run the python script:\npython3 \/opt\/dumb.py At this point senpai should&rsquo;ve set the memory.high restrictions for our cgroups based on the usage of our python script:\ncat \/sys\/fs\/cgroup\/system.slice\/memorytest3\/memory.high 437448704 We can stop senpai. We need around 420MiB memory to run our python script, so a better configuration for it would be:\nAttention\nWe are adding a max swap usage of 50M to ease memory reclaim.\necho &#34;450M&#34; &gt; \/sys\/fs\/cgroup\/system.slice\/memorytest3\/memory.max echo &#34;50M&#34; &gt; \/sys\/fs\/cgroup\/system.slice\/memorytest3\/memory.swap.max At this point we should be able to run the program with no issues:\npython3 \/opt\/dumb.py Used 10 MiB Used 20 MiB ... Used 190 MiB Used 200 MiB Delete the cgroup:\nWarning\nMake sure you closed the shell attached to the cgroup before running the command below, otherwise it will fail.\nsudo rmdir \/sys\/fs\/cgroup\/system.slice\/memorytest3\/ Now that we have seen how to limit memory, let&rsquo;s see how to limit CPU.\nLimiting CPU using Cgroupsv2 Limiting CPU is not as straightforward as limiting memory, since CPU can be compressed we can make sure that a process doesn&rsquo;t use more CPU than allowed without having to kill it.\nWe need to configure the parent cgroup so it has the cpu and cpuset controllers enabled for its children groups. Below example configures the controllers for the system.slice cgroup which is the parent group we will be using. By default, only memory and pids controllers are enabled.\nEnable cpu and cpuset controllers for the \/sys\/fs\/cgroup\/ and \/sys\/fs\/cgroup\/system.slice children groups:\necho &#34;+cpu&#34; &gt;&gt; \/sys\/fs\/cgroup\/cgroup.subtree_control echo &#34;+cpuset&#34; &gt;&gt; \/sys\/fs\/cgroup\/cgroup.subtree_control echo &#34;+cpu&#34; &gt;&gt; \/sys\/fs\/cgroup\/system.slice\/cgroup.subtree_control echo &#34;+cpuset&#34; &gt;&gt; \/sys\/fs\/cgroup\/system.slice\/cgroup.subtree_control Limiting CPU \u2014 Pin process to CPU and limit CPU bandwidth Let&rsquo;s create a new cgroup under the system.slice:\nsudo mkdir -p \/sys\/fs\/cgroup\/system.slice\/cputest Assign only 1 core to this cgroup\nAttention\nBelow command assigns core 0 to our cgroup.\necho &#34;0&#34; &gt; \/sys\/fs\/cgroup\/system.slice\/cputest\/cpuset.cpus Set a limit of half-cpu for this cgroup:\nAttention\nThe value for cpu.max is in units of 1\/1000ths of a CPU core, so 50000 represents 50% of a single core.\necho 50000 &gt; \/sys\/fs\/cgroup\/system.slice\/cputest\/cpu.max Add the current shell process to the cgroup:\necho $$ &gt; \/sys\/fs\/cgroup\/system.slice\/cputest\/cgroup.procs Download the cpuload utility:\ncurl -L https:\/\/github.com\/vikyd\/go-cpu-load\/releases\/download\/0.0.1\/go-cpu-load-linux-amd64 -o \/tmp\/cpuload &amp;&amp; chmod +x \/tmp\/cpuload Run the cpu load:\nAttention\nWe&rsquo;re requesting 1 core and 50% of the CPU, this should fit within the cpu.max setting.\n\/tmp\/cpuload -p 50 -c 1 If we check with systemd-cgtop system.slice\/cputest the usage we will see something like this:\nControl Group Tasks %CPU Memory Input\/s Output\/s system.slice\/cputest 6 47.7 856.0K - - Since we&rsquo;re within the budget, we shouldn&rsquo;t see any throttling happening:\nNote\nCPU throttling is a resource control mechanism that limits the amount of CPU time a process can use, preventing it from consuming excessive CPU resources and affecting the performance of other processes.\ngrep throttled \/sys\/fs\/cgroup\/system.slice\/cputest\/cpu.stat nr_throttled 0 throttled_usec 0 If we stop the cpuload command and request 100% of 1 core we will see throttling:\n\/tmp\/cpuload -p 100 -c 1 Control Group Tasks %CPU Memory Input\/s Output\/s system.slice\/cputest 6 50.0 720.0K - - grep throttled \/sys\/fs\/cgroup\/system.slice\/cputest\/cpu.stat nr_throttled 336 throttled_usec 16640745 Remove the cgroup:\nWarning\nMake sure you closed the shell attached to the cgroup before running the command below, otherwise it will fail.\nsudo rmdir \/sys\/fs\/cgroup\/system.slice\/cputest\/ This use case is very simple, we pinned our process to 1 core and limited the CPU to half a core. Let&rsquo;s see what happens when multiple processes compete for the CPU.\nLimiting CPU \u2014 Pin processes to CPU and limit CPU bandwidth Let&rsquo;s create a new cgroup under the system.slice:\nsudo mkdir -p \/sys\/fs\/cgroup\/system.slice\/compitingcputest Assign only 1 core to this cgroup\nAttention\nBelow command assigns core 0 to our cgroup.\necho &#34;0&#34; &gt; \/sys\/fs\/cgroup\/system.slice\/compitingcputest\/cpuset.cpus Set a limit of one cpu for this cgroup:\nAttention\nThe value for cpu.max is in units of 1\/1000ths of a CPU core, so 100000 represents 100% of a single core.\necho 100000 &gt; \/sys\/fs\/cgroup\/system.slice\/compitingcputest\/cpu.max Open two shells and attach their process to the cgroup:\necho $$ &gt; \/sys\/fs\/cgroup\/system.slice\/compitingcputest\/cgroup.procs Run the cpu load in one of the shells:\nAttention\nWe&rsquo;re requesting 1 core and 100% of the CPU, this should fit within the cpu.max setting.\n\/tmp\/cpuload -p 100 -c 1 If we check for throttling we will see that no throttling is happening.\ngrep throttled \/sys\/fs\/cgroup\/system.slice\/compitingcputest\/cpu.stat nr_throttled 0 throttled_usec 0 Run another instance of cpuload on the other shell:\n\/tmp\/cpuload -p 100 -c 1 At this point, we shouldn&rsquo;t see throttling, but the CPU time would be shared by the two processes, in the top output below we can see that each process is consuming half cpu.\nPID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 822742 root 20 0 4104 2004 1680 S 49.8 0.0 0:24.30 cpuload 822717 root 20 0 4104 2008 1680 S 49.5 0.1 6:28.51 cpuload Close the shells and remove the cgroup:\nWarning\nMake sure you closed the shell attached to the cgroup before running the command below, otherwise it will fail.\nsudo rmdir \/sys\/fs\/cgroup\/system.slice\/compitingcputest\/ In this use case, we pinned our process to 1 core and limited the CPU to one core. On top of that, we spawned two processes that competed for CPU. Since CPU bandwidth distribution was not set, each process got half cpu. In the next section we will see how to distribute CPU across processes using weights.\nLimiting CPU \u2014 Pin processes to CPU, limit and distribute CPU bandwidth Let&rsquo;s create a new cgroup under the system.slice with two sub-groups (appA and appB):\nsudo mkdir -p \/sys\/fs\/cgroup\/system.slice\/distributedbandwidthtest\/{appA,appB} Enable cpu and cpuset controllers for the \/sys\/fs\/cgroup\/system.slice\/distributedbandwidthtest children groups:\necho &#34;+cpu&#34; &gt;&gt; \/sys\/fs\/cgroup\/system.slice\/distributedbandwidthtest\/cgroup.subtree_control echo &#34;+cpuset&#34; &gt;&gt; \/sys\/fs\/cgroup\/system.slice\/distributedbandwidthtest\/cgroup.subtree_control Assign only 1 core to the parent cgroup\nAttention\nBelow command assigns core 0 to our cgroup.\necho &#34;0&#34; &gt; \/sys\/fs\/cgroup\/system.slice\/distributedbandwidthtest\/cpuset.cpus Set a limit of one cpu for this cgroup:\nAttention\nThe value for cpu.max is in units of 1\/1000ths of a CPU core, so 100000 represents 100% of a single core.\necho 100000 &gt; \/sys\/fs\/cgroup\/system.slice\/distributedbandwidthtest\/cpu.max Open two shells and attach their process to the different child cgroups, then run cpuload:\nShell 1\necho $$ &gt; \/sys\/fs\/cgroup\/system.slice\/distributedbandwidthtest\/appA\/cgroup.procs \/tmp\/cpuload -p 100 -c 1 Shell 2\necho $$ &gt; \/sys\/fs\/cgroup\/system.slice\/distributedbandwidthtest\/appB\/cgroup.procs \/tmp\/cpuload -p 100 -c 1 If you check the top output, you will see that CPU is evenly distributed across both processes, let&rsquo;s modify weights to give more CPU to appB cgroup.\nIn cgroupvs1 there was cpu shares concept, in cgroupsv2 this changed and now we use cpu weights. All weights are in the range [1, 10000] with the default at 100. This allows symmetric multiplicative biases in both directions at fine enough granularity while staying in the intuitive range. If we wanted to give appA a 30% of the CPU and appB the other 70%, providing that the parent cgroup CPU weight is set to 100 this is the configuration we will apply:\ncat \/sys\/fs\/cgroup\/system.slice\/distributedbandwidthtest\/cpu.weight 100 Assign 30% of the cpu to appA\necho 30 &gt; \/sys\/fs\/cgroup\/system.slice\/distributedbandwidthtest\/appA\/cpu.weight Assign 70% of the cpu to appB\necho 70 &gt; \/sys\/fs\/cgroup\/system.slice\/distributedbandwidthtest\/appB\/cpu.weight If we look at the top output we will see something like this:\nAttention\nYou can see how one of the cpuload processes is getting 70% of the cpu while the other is getting the other 30%.\nPID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1077 root 20 0 4104 2008 1680 S 70.0 0.1 12:41.27 cpuload 1071 root 20 0 4104 2008 1680 S 30.0 0.1 12:24.14 cpuload Close the shells and remove the cgroups:\nWarning\nMake sure you closed the shell attached to the cgroup before running the command below, otherwise it will fail.\nsudo rmdir \/sys\/fs\/cgroup\/system.slice\/distributedbandwidthtest\/appA\/ sudo rmdir \/sys\/fs\/cgroup\/system.slice\/distributedbandwidthtest\/appB\/ sudo rmdir \/sys\/fs\/cgroup\/system.slice\/distributedbandwidthtest\/ At this point, we should have a clear understanding on how the basics work, next section will introduce these concepts applied to Kubernetes.\nResource Management on Kubernetes We won&rsquo;t be covering the basics, I recommend reading the official docs. We will be focusing on CPU\/Memory requests and limits.\nCgroupsv2 configuration for a Kubernetes node Before describing the cgroupsv2 configuration, we need to understand how Kubelet configurations will impact cgroupsv2 configurations. In our test cluster, we have the following Kubelet settings in order to reserve resources for system daemons:\nsystemReserved: cpu: 500m memory: 500Mi If we describe the node this is what we will see:\noc describe node &lt;compute-node&gt; Attention\nYou can see how half cpu (500m) and 500Mi of memory have been subtracted from the allocatable capacity.\nCapacity: cpu: 4 &lt;omitted&gt; memory: 6069552Ki Allocatable: cpu: 3500m &lt;omitted&gt; memory: 5455152Ki Even if we remove resources from the allocatable capacity, depending on the QoS of our pods we would be able to over commit on resources, at that point, eviction may happen and cgroups will make sure that pods with more priority get the required resources they asked for.\nCgroupsv2 configuration on the node In a regular Kubernetes node we will have at least three main parent cgroups:\nkubepods.slice: Parent cgroup used by Kubernetes to place pod processes. It has two child cgroups named after pod QoS inside: kubepods-besteffort.slice and kubepods-burstable.slice. Guaranteed pods get created inside this parent cgroup. system.slice: Parent cgroup used by the O.S to place system processes. Kubelet, sshd, etc. run here. user.slice: Parent cgroup used by the O.S to place user processes. When you run a regular command, it runs here. Note\nIn Systemd a Slice is a concept for hierarchically managing resources of a group of processes. This management is done by creating a cgroup. Scopes manage a set of externally created processes, the main purpose of a scope is grouping worker processes for managing resources.\n\/sys\/fs\/cgroup\/ \u251c\u2500\u2500 kubepods.slice \u2502\u00a0\u251c\u2500\u2500 kubepods-besteffort.slice \u2502\u00a0\u2502\u00a0\u2514\u2500\u2500 kubepods-besteffort-pod7589d90f_83af_4a05_a4ee_8bb078db72b8.slice \u2502\u00a0\u2502\u00a0\u251c\u2500\u2500 cri-containerd-2be6af51555a1d9ebb8678f3254e81b5f3547dfc230b07a2c1067f5d430b7221.scope \u2502\u00a0\u2502\u00a0\u2514\u2500\u2500 cri-containerd-cbce8911226299472976f069f20afe0ba20c80037f9fd8394c0a8f8aaac60bee.scope \u2502\u00a0\u251c\u2500\u2500 kubepods-burstable.slice \u2502\u00a0\u2502\u00a0\u2514\u2500\u2500 kubepods-burstable-pode00fb079_24be_4039_b2cb_f68876881d70.slice \u2502\u00a0\u2502\u00a0\u251c\u2500\u2500 cri-containerd-a0c611e1b04856e9d565dfef25746d7bdcaaf12bb92fff6221aa6b89a12fbb31.scope \u2502\u00a0\u2502\u00a0\u2514\u2500\u2500 cri-containerd-ea6361278865134bd9d52e718baa556e7693d766ab38d28d64941a1935fae004.scope \u2502\u00a0\u2514\u2500\u2500 kubepods-podbe70a1c9_81c5_4764_b28f_0965edee08d0.slice \u2502\u00a0\u251c\u2500\u2500 cri-containerd-208bf4e7ddeef45a3bd3acff96ff0747b35e9204cea418082b586df6adf022ad.scope \u2502\u00a0\u2514\u2500\u2500 cri-containerd-71305184cec893cd21cfef2cbe699453ad89a51e4f60586670f194574f287a53.scope \u251c\u2500\u2500 system.slice \u2502\u00a0\u251c\u2500\u2500 kubelet.service \u2502\u00a0\u2514\u2500\u2500 sshd.service \u2514\u2500\u2500 user.slice \u2514\u2500\u2500 user-1000.slice In order to get these cgroups created, Kubelet uses one of the two available drivers: systemd or cgroupsfs. Cgroupsv2 are only supported by systemd driver.\nThe root cgroup kubepods.slice and the QoS cgroups kubepods-besteffort.slice and kubepods-burstable.slice are created by Kubelet when it starts, on top of that Kubelet will create a cgroup (using the driver) as soon as a new Pod gets created. The pod will have from 1 to N containers, the cgroups for these containers will be created by the container runtime by using the driver as well.\nOn the output above you can see different cgroups for pods like kubepods-besteffort-pod7589d90f_83af_4a05_a4ee_8bb078db72b8.slice and one for a container like cri-containerd-2be6af51555a1d9ebb8678f3254e81b5f3547dfc230b07a2c1067f5d430b7221.scope.\nSo far, we have been looking at the configuration of cgroups via the filesystem. Systemd tooling can be used for that as well:\nsystemctl show --no-pager cri-containerd-2be6af51555a1d9ebb8678f3254e81b5f3547dfc230b07a2c1067f5d430b7221.scope &lt;OMITTED_OUTPUT&gt; CPUWeight=1 MemoryMax=infinity &lt;OMITTED_OUTPUT&gt; CPU Bandwidth configuration on the node In the previous sections we have talked about how cpu.weight works for distributing CPU bandwidth to processes. The parent cgroups in a Kubernetes node will be configured as follows:\nsystem.slice: A cpu.weight of 100. user.slice: A cpu.weight of 100. In a Kubernetes node, we won&rsquo;t have much\/any user processes running. So at the end, the two cgroups competing for resources will be system.slice and kubepods.slice. But wait, what cpu.weight is configured for kubepods.slice?\nWhen Kubelet starts it detects the number of CPUs available on the node, on top of that it reads the systemReserved.cpu configuration. That will give you a number of milicores available for Kubernetes to use on that node.\nFor example, if I have a 4 CPU node that&rsquo;s 4000 milicores, if I reserved 500m for the system resources (kubelet, sshd, etc.) that leaves Kubernetes with 3500 milicores that can be assigned to workloads.\nNow, Kubelet knows that 3500 milicores is the amount of CPU that can be assigned to workloads (and assigned means that is more or less assured in case workloads request it). The cgroups cpu.weight needs to be configured so CPU get distributed accordingly, let&rsquo;s see how that&rsquo;s done:\nIn the past (cgroupsv1), CPU Shares were used and every CPU was represented by 1024 Shares. Now, we need to translate from shares to weight and the community has a formula for that (more info here). In cgroupsv2 we still use Shares under the hood, but that&rsquo;s only because the formula created to not having to change the specification requires them. So we have a constant that sets the Shares\/CPU to 1024 and a function that translates milicores to shares. Finally, there is a function that translates CPU Shares to CPU Weight using the formula from 1. After we know the weight that needs to be applied to the kubepods.slice, the relevant code that does that is here and here.\nContinuing with the example, the cpu.weight for our 4 CPU node with 500 milicores reserved for system resources would be:\nFormula being used: (((cpuShares - 2) * 9999) \/ 262142) + 1\ncpuShares = 3.5 Cores * 1024 = 3584\ncpu.weight = (((3584 - 2) * 9999) \/ 262142) + 1 = 137,62\nIf we check our node:\ncat \/sys\/fs\/cgroup\/kubepods.slice\/cpu.weight 137 At this point we know how the different cgroups get configured on the node, next let&rsquo;s see what happens when kubepods.slice and system.slice compete for cpu.\nkubepods.slice and system.slice competing for CPU In the previous section we have seen how the different cgroups get configured on our 4 CPU node, in this section we will see what happens when the two slices compete for CPU.\nLet&rsquo;s say that we have two processes, the sshd service and a guaranteed pod. Both processes have access to all 4 CPUs and they&rsquo;re trying to use the 100% of the 4 CPUs.\nTo calculate the percentage of CPU allocated to each process, we can use the following formulas:\nPod Process: (cpu.weight of pod \/ total cpu.weight) * number of CPUs Ssh Process: (cpu.weight of ssh \/ total cpu.weight) * number of CPUs In this case, the total cpu.weight is 237 (137 from kubepods.slice + 100 from system.slice), so:\nPod Process: (137 \/ 237) * 4 = 2.31 CPUs or ~231% Ssh Process: (100 \/ 237) * 4 = 1.68 CPUs or ~168% So pod process would get around 231% of the available CPU (400% -&gt; 4 Cores x 100) and ssh process would get around 168% of the available CPU.\nDanger\nKeep in mind that these calculations are not 100% accurate, since the CFS will try to assign CPU in the fairest way possible and results may vary depending on the system load and other process running on the system.\nCgroupsv2 configuration for a Pod In the previous sections we have focused on the configuration at the node level, but let&rsquo;s see what happens when we create a pod on the different QoS.\nCgroup configuration for a BestEffort Pod We will be using this pod definition:\napiVersion: v1 kind: Pod metadata: creationTimestamp: null labels: run: cputest name: cputest-besteffort spec: containers: - image: quay.io\/mavazque\/trbsht:latest name: cputest resources: {} dnsPolicy: ClusterFirst restartPolicy: Always Once created, in the node where the pod gets scheduled we can find the cgroup that was created by using these commands:\nGet container id:\ncrictl ps | grep cputest-besteffort 2be6af51555a1 b67fff43d1e61 4 minutes ago Running cputest 0 cbce891122629 cputest-besteffort Get the cgroups path:\ncrictl inspect 2be6af51555a1 | jq &#39;.info.runtimeSpec.linux.cgroupsPath&#39; &#34;kubepods-besteffort-pod7589d90f_83af_4a05_a4ee_8bb078db72b8.slice:cri-containerd:2be6af51555a1d9ebb8678f3254e81b5f3547dfc230b07a2c1067f5d430b7221&#34; With above information, the full path will be \/sys\/fs\/cgroup\/kubepods.slice\/kubepods-besteffort.slice\/kubepods-besteffort-pod7589d90f_83af_4a05_a4ee_8bb078db72b8.slice\nIf we check the cpu.max, cpu.weight and memory.max configuration, this is what we see:\ncpu.max is set to max 100000. cpu.weight is set to 1. memory.max is set to max. As we can see, the pod is allowed to use as much CPU as it wants, but it has the lowest weight possible which means that it only will get CPU when other processes with higher weight yield some. You can expect a lot of throttling for these pods when the system is under load. On the memory side, it can use as much memory as it wants, but if the cluster requires evicting this pod to reclaim memory in order to schedule more priority pods the container will be OOMKilled. The max from the cpu.max config means that the processes can use all the CPU time available on the system (which varies depending on the speed of your CPU).\nCgroup configuration for a Burstable Pod We will be using this pod definition:\napiVersion: v1 kind: Pod metadata: creationTimestamp: null labels: run: cputest name: cputest-burstable spec: containers: - image: quay.io\/mavazque\/trbsht:latest name: cputest resources: requests: cpu: 2 memory: 100Mi dnsPolicy: ClusterFirst restartPolicy: Always Once created, in the node where go the cgroup configuration by following the steps described previously and this is the configuration we see:\ncpu.max is set to max 100000. cpu.weight is set to 79. memory.max is set to max. The pod will be allowed to use as much CPU as it wants, and the weight has been set to it has certain priority over other processes running on the system. On the memory side it can use as much memory as it wants, but if the cluster requires evicting this pod to reclaim memory in order to schedule more priority pods the container will be OOMKilled. The cpu.weight value 79 comes from the formula we saw earlier ((((cpuShares - 2) * 9999) \/ 262142) + 1):\ncpuShares = 2 Cores * 1024 = 2048 cpu.weight = (((2048 - 2) * 9999) \/ 262142) + 1 = 79,04 Cgroup configuration for a Guaranteed Pod We will be using this pod definition:\napiVersion: v1 kind: Pod metadata: creationTimestamp: null labels: run: cputest name: cputest-guaranteed spec: containers: - image: quay.io\/mavazque\/trbsht:latest name: cputest resources: requests: cpu: 2 memory: 100Mi limits: cpu: 2 memory: 100Mi dnsPolicy: ClusterFirst restartPolicy: Always Once created, in the node where go the cgroup configuration by following the steps described previously and this is the configuration we see:\ncpu.max is set to 200000 100000. cpu.weight is set to 79. memory.max is set to 104857600 (100Mi = 104857600 bytes). The cpu.max value is different to what we have seen so far, the first value 200000 is the allowed time quota in microseconds for which the process can run during one period. The second value 100000 specific the length of the period. Once the processes consume the time specified by this quota, they will be throttled for the remained of the period and won&rsquo;t be allowed to run until the next period. This specific configuration allows our processes to run every 0.2 seconds of every 1 second (1\/5th). On the memory side, the container can use up to 100Mi once it reaches this value if kernel will try to reclaim some memory, if it cannot be reclaimed the container will be OOMKilled.\nEven if guaranteed QoS will ensure that your application gets the CPU it wants, sometimes your application may benefit from burstable capabilities since the CPU won&rsquo;t be throttled during peaks (e.g: more visits to a web server).\nHow Kubepods Cgroups compete for resources In the previous examples we have seen how the different pods get different CPU configurations. But what happens if they compete against them for resources?\nIn order for the guaranteed pods to have more priority than burstable pods, and these to have more priority than besteffort different weights get set for the three slices. In a 4 CPU node these are the settings we get:\nGuaranteed pods will run under kubepods.slice which has a cpu.weight of 137. Burstable pods will run under kubepods.slice\/kubepods-burstable.slice which has a cpu.weight of 86. BestEffort pods will run under kubepods.slice\/kubepods-besteffort.slice which has a cpu.weight of 1. As we can see from above configuration, the weights define the CPU priority. Keep in mind that pods running inside the same parent slice can compete for resources. In this situation, when they&rsquo;re competing for resources the total cpu.weight will be the one from summing cpu weights from all cpu hungry processes inside a specific parent cgroup. For example:\nWe have two burstable pods, these are the cpu weights that will be configured (based on the formulas we have seen so far):\nbustable1 requests 2 CPUs and gets a cpu.weight of 79 burstable2 requests 1 CPU and gets a cpu.weight of 39 So this is the CPU each one will get (formula: (cpu.weight of pod \/ total cpu.weight) * 100 * number of CPUs):\nDanger\nKeep in mind that these calculations are not 100% accurate, since the CFS will try to assign CPU in the fairest way possible and results may vary depending on the system load and other process running on the system. These calculations assume that there are no guaranteed pods demanding CPU. 118 value comes from summing all the CPU hungry processes from the burstable cgroup (in this case only two pods, burstable1 - cpu.weight=79 and burstable2 - cpu.weight=39).\nburstable1: (79\/118) * 100 * 4 = ~ 267% (or 2.67 CPU) burstable2: (39\/118) * 100 * 4 = ~ 132% (or 1.32 CPU) Closing Thoughts Even if knowing the low-level details about resource management on Kubernetes may not be needed in a day-to-day basis, it&rsquo;s great knowing how the different pieces are tied together. If you&rsquo;re working on environments were performance and latencies are critical, like in telco environments, knowing this information can make the difference!\nOn top of that, some of the new features that cgroupsv2 enable are:\nContainer aware OOMKilled: Useful when you have sidecars, this could be used to OOMKill the sidecar container rather than your application container. Running Kubernetes System components root-less: More secure Kubernetes environments. Kubernetes Memory QoS: Better overall control of the memory used by pods. The Kubernetes Memory QoS kind of relates to this post, so I&rsquo;ll be writing a new post covering that in the future.\nFinally, in the next section I&rsquo;ll put interesting resources around the topic, some of them were my sources when learning all this stuff.\nUseful Resources KubeCon NA 2022 - Cgroupv2 is coming soon to a cluster near you talk. Slides and Recording. FOSDEM 2023 - 7 years of cgroup v2 talk. Slides and Recording. Lisa 2021 - 5 years of cgroup v2 talk. Slides and Recording. KubeCon EU 2020 - Kubernetes On Cgroup v2. Slides and Recording. cgroups man page and kernel docs. RHEL8 cgroupv2 docs. Martin Heinz blog on kubernetes cgroups. Kubernetes cgroups docs. Kubernetes manage resources for containers docs. Kubernetes reserve compute resources docs. Runc Systemd driver docs. Systemd scope and slice docs. ","permalink":"https:\/\/linuxera.org\/cpu-memory-management-kubernetes-cgroupsv2\/","summary":"CPU and Memory Management on Kubernetes with Cgroupsv2 In this post I&rsquo;ll try to explain how CPU and Memory management works under the hood on Kubernetes. If you ever wondered what happens when you set requests and limits for your pods, keep reading!\nAttention\nThis is the result of my exploratory work around cgroupsv2 and their application to Kubernetes. Even though I tried really hard to make sure the information in this post is accurate, I&rsquo;m far from being an expert on the topic and some information may not be 100% accurate.","title":"CPU and Memory Management on Kubernetes with Cgroupsv2"},{"content":"Exposing multiple Kubernetes clusters with a single load balancer and a single public IP My colleague Alberto Losada and I have been working on a lab lately. The lab is composed of three OpenShift clusters on VMs, these VMs are deployed on an isolated libvirt network, which means that we cannot access them from outside the hypervisor.\nIn order to solve this issue, we wanted to expose the three clusters using the public IP available in the hypervisor. This setup should be valid for any Kubernetes cluster.\nAPI and Ingress endpoints In our case, our OpenShift clusters have two different endpoints, one for the Kubernetes API Server, and another one for the cluster Ingress:\nAPI Endpoint: 6443 port on control plane nodes Cluster Ingress: 80 and 443 ports on compute nodes We have three clusters:\nhub-cluster.linuxera.lab managed1.linuxera.lab managed2. linuxera.lab Each cluster has two DNS records:\napi.&lt;clustername&gt;.&lt;basedomain&gt; -&gt; points to the hypervisor public IP *.apps.&lt;clustername&gt;.&lt;basedomain&gt; -&gt; points to the hypervisor public IP For example, for the hub-cluster we will have: api.hub-cluster.linuxera.lab and *.apps.hub-cluster.linuxera.lab.\nLoad balancing requirements Usually, when you want to expose multiple clusters under the same load balancer you either use different public IPs, or different ports. For example, if you wanted to expose three clusters you could use three different IPs. Your load balancer will listen for connections on these IPs and depending on the IP receiving the request the load balancer will redirect traffic to the cluster exposed by that IP.\nA different approach would be using the same IP for the load balancer but different ports, for example cluster1 API will be published in port 6443, cluster2 in port 6444, etc.\nIn this lab environment we only had a public IP, and we didn&rsquo;t want to use different ports. We wanted to be able to route request based on the destination cluster. On top of that, we didn&rsquo;t want to do TLS termination in the load balancer, instead we wanted the different clusters to do that.\nDetecting destination for the connections Users using our clusters will connect to the different clusters APIs and ingress endpoints. When they do that, depending on the destination cluster these connections will have different information that we can use to redirect those connections to the proper cluster.\nFor connections going to the HTTP Ingress endpoint we will use the Host header. For TLS connections going to the HTTPS\/API ingress endpoints we will use the SNI from the TLS handshake.\nOur solution We decided to go with HAProxy. The architecture looks like this:\nAnd our configuration file:\nglobal log 127.0.0.1 local2 maxconn 4000 daemon defaults mode tcp log global retries 3 timeout http-request 10s timeout queue 1m timeout connect 10s timeout client 1m timeout server 1m timeout http-keep-alive 10s timeout check 10s maxconn 3000 listen stats-50000 bind :50000 mode http log global maxconn 10 timeout client 100s timeout server 100s timeout connect 100s stats enable stats hide-version stats refresh 30s stats show-node stats auth admin:password stats uri \/haproxy?stats frontend apis-6443 bind :6443 mode tcp tcp-request inspect-delay 5s tcp-request content accept if { req_ssl_hello_type 1 } acl ACL_hub req_ssl_sni -i api.hub-cluster.linuxera.lab acl ACL_managed1 req_ssl_sni -i api.managed1.linuxera.lab acl ACL_managed2 req_ssl_sni -i api.managed2.linuxera.lab use_backend be_api_hub_6443 if ACL_hub use_backend be_api_managed1_6443 if ACL_managed1 use_backend be_api_managed2_6443 if ACL_managed2 frontend routers-http-80 bind :80 mode http acl ACL_hub hdr(host) -m reg -i ^[^\\.]+\\.apps\\.hub\\.linuxera\\.lab acl ACL_managed1 hdr(host) -m reg -i ^[^\\.]+\\.apps\\.managed1\\.linuxera\\.lab acl ACL_managed2 hdr(host) -m reg -i ^[^\\.]+\\.apps\\.managed2\\.linuxera\\.lab use_backend be_ingress_hub_80 if ACL_hub use_backend be_ingress_managed1_80 if ACL_managed1 use_backend be_ingress_managed2_80 if ACL_managed2 frontend routers-https-443 bind :443 mode tcp tcp-request inspect-delay 5s tcp-request content accept if { req_ssl_hello_type 1 } acl ACL_hub req_ssl_sni -m reg -i ^[^\\.]+\\.apps\\.hub\\.linuxera\\.lab acl ACL_managed1 req_ssl_sni -m reg -i ^[^\\.]+\\.apps\\.managed1\\.linuxera\\.lab acl ACL_managed2 req_ssl_sni -m reg -i ^[^\\.]+\\.apps\\.managed2\\.linuxera\\.lab use_backend be_ingress_hub_443 if ACL_hub use_backend be_ingress_managed1_443 if ACL_managed1 use_backend be_ingress_managed2_443 if ACL_managed2 backend be_api_hub_6443 mode tcp balance source option ssl-hello-chk server controlplane0 192.168.125.20:6443 check inter 1s server controlplane1 192.168.125.21:6443 check inter 1s server controlplane2 192.168.125.22:6443 check inter 1s backend be_api_managed1_6443 mode tcp balance source option ssl-hello-chk server controlplane0 192.168.125.30:6443 check inter 1s server controlplane1 192.168.125.31:6443 check inter 1s server controlplane2 192.168.125.32:6443 check inter 1s backend be_api_managed2_6443 mode tcp balance source option ssl-hello-chk server controlplane0 192.168.125.40:6443 check inter 1s server controlplane1 192.168.125.41:6443 check inter 1s server controlplane2 192.168.125.42:6443 check inter 1s backend be_ingress_hub_80 mode http balance hdr(Host) hash-type consistent option forwardfor http-send-name-header Host server compute0 192.168.125.23:80 check inter 1s server compute1 192.168.125.24:80 check inter 1s server compute2 192.168.125.25:80 check inter 1s backend be_ingress_hub_443 mode tcp balance source option ssl-hello-chk server compute0 192.168.125.23:443 check inter 1s server compute1 192.168.125.24:443 check inter 1s server compute2 192.168.125.25:443 check inter 1s backend be_ingress_managed1_80 mode http balance hdr(Host) hash-type consistent option forwardfor http-send-name-header Host server compute0 192.168.125.33:80 check inter 1s server compute1 192.168.125.34:80 check inter 1s server compute2 192.168.125.35:80 check inter 1s backend be_ingress_managed1_443 mode tcp balance source option ssl-hello-chk server compute0 192.168.125.33:443 check inter 1s server compute1 192.168.125.34:443 check inter 1s server compute2 192.168.125.35:443 check inter 1s backend be_ingress_managed2_80 mode http balance hdr(Host) hash-type consistent option forwardfor http-send-name-header Host server compute0 192.168.125.43:80 check inter 1s server compute1 192.168.125.44:80 check inter 1s server compute2 192.168.125.45:80 check inter 1s backend be_ingress_managed2_443 mode tcp balance source option ssl-hello-chk server compute0 192.168.125.43:443 check inter 1s server compute1 192.168.125.44:443 check inter 1s server compute2 192.168.125.45:443 check inter 1s From this configuration file we can remark the following parameters:\nRedirect to different API backends based on SNI\nacl ACL_hub req_ssl_sni -i api.hub-cluster.linuxera.lab acl ACL_managed1 req_ssl_sni -i api.managed1.linuxera.lab acl ACL_managed2 req_ssl_sni -i api.managed2.linuxera.lab Redirect to different http ingress backends based on Host header and wildcard domain\nacl ACL_hub hdr(host) -m reg -i ^[^\\.]+\\.apps\\.hub\\.linuxera\\.lab acl ACL_managed1 hdr(host) -m reg -i ^[^\\.]+\\.apps\\.managed1\\.linuxera\\.lab acl ACL_managed2 hdr(host) -m reg -i ^[^\\.]+\\.apps\\.managed2\\.linuxera\\.lab Redirect to different https ingress backends based on SNI and wildcard domain\nAttention\nWe also add tcp-request inspect-delay 5s for HAProxy to have enough time to inspect the connection.\ntcp-request inspect-delay 5s tcp-request content accept if { req_ssl_hello_type 1 } acl ACL_hub req_ssl_sni -m reg -i ^[^\\.]+\\.apps\\.hub\\.linuxera\\.lab acl ACL_managed1 req_ssl_sni -m reg -i ^[^\\.]+\\.apps\\.managed1\\.linuxera\\.lab acl ACL_managed2 req_ssl_sni -m reg -i ^[^\\.]+\\.apps\\.managed2\\.linuxera\\.lab ","permalink":"https:\/\/linuxera.org\/exposing-multiple-kubernetes-clusters-single-lb-and-ip\/","summary":"Exposing multiple Kubernetes clusters with a single load balancer and a single public IP My colleague Alberto Losada and I have been working on a lab lately. The lab is composed of three OpenShift clusters on VMs, these VMs are deployed on an isolated libvirt network, which means that we cannot access them from outside the hypervisor.\nIn order to solve this issue, we wanted to expose the three clusters using the public IP available in the hypervisor.","title":"Exposing multiple Kubernetes clusters with a single load balancer and a single public IP"},{"content":"Enhanced Version and Build Information for your Go programs with ldflags In the previous post we show how to create a simple CLI in Go with Cobra. I received a suggestion from one of my colleagues, Andrew Block. He suggested complementing that post with the use of ldflags at build time in order to define specific information to a specific build like build time, git commit, etc.\nAndy is also running a blog, go check it out!\nHow does ldflags improve the build and version information? With the use of ldflags we can change values for variables defined in our go programs at build time. Taking the CLI program we created in the previous post as an example, in the version.go file we defined the following variables:\nvar ( version = &#34;0.0.1&#34; buildTime = &#34;1970-01-01T00:00:00Z&#34; gitCommit = &#34;notSet&#34; binaryName = &#34;example-cli&#34; ) You can see these variables have pre-defined values that are not being set to anything meaningful, some of these variables will benefit from having dynamic values set at build time, like for example buildTime and gitCommit.\nIn this post we will see how we can modify the value of these vars at build time. This information will be helpful in the future if we need to know what code is included in a specific binary or what time it was built at.\nRemember, we&rsquo;re using the CLI program we created in the previous post for the next steps.\nBuilding our Go programs with ldflags The Go ldflags supports passing many link flags, you can find the ldflags documentation here. For now, we&rsquo;re going to focus on how variable values can be changed at build time.\nWe will be using the -X flag which is described in the docs as Set the value of the string variable in importpath named name to value.\nThe syntax is something like this:\ngo build -ldflags=&#34;-X &#39;package_path.variable_name=variable_value&#39;&#34; For example, if we had a variable named version in the main package we could change it like this:\ngo build -ldflags=&#34;-X &#39;main.version=v1.0&#39;&#34; In our example application, the variables we need to modify are present in a sub-package though, so the package_path we need to use is a bit different, and not always easy to deduce. For these cases we can use the go tool nm command to help us find the variables package_path easily.\nIf for example, we would like to change the value for the gitCommit var we would do something like this:\nGet the package_path for the gitCommit variable:\n$ go tool nm .\/example-cli | grep gitCommit 6add80 D github.com\/mvazquezc\/go-cli-template\/pkg\/version.gitCommit Run the go build with ldflags:\ngo build -ldflags=&#34;-X &#39;github.com\/mvazquezc\/go-cli-template\/pkg\/version.gitCommit=changed_at_build_time&#39;&#34; -o example-cli cmd\/main.go If we run our application we will see the new value for the gitCommit variable:\n$ .\/example-cli version | grep commit Git commit: changed_at_build_time Warning\nldflags only support changing variables of type string. On top of that, these variables cannot be constants or get their value set from a function call.\nNow that we explained how ldflags can be used, let&rsquo;s finish our example with relevant information by using commands to gather the data at build time.\ngo build -ldflags=&#34;-X &#39;github.com\/mvazquezc\/go-cli-template\/pkg\/version.gitCommit=$(git rev-parse HEAD)&#39; -X &#39;github.com\/mvazquezc\/go-cli-template\/pkg\/version.buildTime=$(date +%Y-%m-%dT%H:%M:%SZ)&#39;&#34; -o example-cli cmd\/main.go The result will be something like this:\n$ .\/example-cli version Build time: 2023-01-19T19:11:37Z Git commit: 23456bce1170173af228f47162fa7c70ae884d02 Go version: go1.18.8 Go compiler: gc Go Platform: linux\/amd64 Closing Thoughts Adding information like this to your Go programs can help you in different ways, for example when someone reports a regression bug having information about the git commit can help you identify when the regression was introduced. There are multiple use cases, now it&rsquo;s your turn to investigate how you can leverage ldflags in your builds!\n","permalink":"https:\/\/linuxera.org\/enhanced-version-and-build-information-for-your-go-programs\/","summary":"Enhanced Version and Build Information for your Go programs with ldflags In the previous post we show how to create a simple CLI in Go with Cobra. I received a suggestion from one of my colleagues, Andrew Block. He suggested complementing that post with the use of ldflags at build time in order to define specific information to a specific build like build time, git commit, etc.\nAndy is also running a blog, go check it out!","title":"Enhanced Version and Build Information for your Go programs with ldflags"},{"content":"Writing CLIs in Go using Cobra A few months ago, I was working with my colleague Alberto in a CLI. The language of choice was Go and I manage to learn a thing or two. In today&rsquo;s post we will see a very basic skeleton for a CLI written in Go. This will certainly help me in the future as a template for the next CLI, and maybe it helps you too!\nBefore we start, Alberto has also a blog where he shares his knowledge, don&rsquo;t forget to check it out.\nCobra If you searched for CLI libraries in Go, I&rsquo;m 100% sure that you already know Cobra. It&rsquo;s the most used library for writing CLI tools and projects such as Kubernetes, Hugo, and GitHub CLI use it under the hood.\nCobra is the library we will be using for building our CLI.\nProject structure Note\nYou can find the example project at https:\/\/github.com\/mvazquezc\/go-cli-template\nWe will structure our CLI project as follows:\n. \u251c\u2500\u2500 cmd \u2502\u00a0\u251c\u2500\u2500 cli \u2502\u00a0\u2502\u00a0\u251c\u2500\u2500 run.go \u2502\u00a0\u2502\u00a0\u2514\u2500\u2500 version.go \u2502\u00a0\u2514\u2500\u2500 main.go \u2514\u2500\u2500 pkg \u251c\u2500\u2500 example \u2502\u00a0\u2514\u2500\u2500 run.go \u2514\u2500\u2500 version \u2514\u2500\u2500 version.go The cmd folder will have the root command implementation defined in the main.go file and a sub-folder named cli. This sub-folder will have the implementation of the different sub-commands for our CLI. In this example we have two sub-commands: run and version. The pkg folder will have the libraries required by our sub-commands. This is optional, but in our case we implement the run sub-command functionality in a package named example and the version sub-command functionality in a package named version. CLI Implementation In this section we will go over the CLI implementation, we will start with the root command and will continue with the sub-commands and packages.\nRoot Command The root command is implemented in the cmd\/main.go file, below the code used with comments:\n\/\/ This is our main package package main \/\/ Import required packages import ( color &#34;github.com\/TwiN\/go-color&#34; &#34;github.com\/mvazquezc\/go-cli-template\/cmd\/cli&#34; &#34;github.com\/spf13\/cobra&#34; &#34;log&#34; &#34;os&#34; ) \/\/ Our CLI main function func main() { \/\/ Create a cobra command that will be the CLI entry-point command := newRootCommand() \/\/ If the command execution fails return the error (this includes errors raised at sub-commands) if err := command.Execute(); err != nil { log.Fatalf(color.InRed(&#34;[ERROR] &#34;)+&#34;%s&#34;, err.Error()) } } \/\/ newRootCommand implements the root command of example-ci func newRootCommand() *cobra.Command { \/\/ Define a new cobra command with the binary name of our CLI and the \/\/ This command run without sub-commands will return the help c := &amp;cobra.Command{ Use: &#34;example-cli&#34;, Short: &#34;Example cli written in go&#34;, Run: func(cmd *cobra.Command, args []string) { \/\/ Return help if no sub-command received cmd.Help() os.Exit(1) }, } \/\/ Add sub-commands to our main command c.AddCommand(cli.NewRunCommand()) c.AddCommand(cli.NewVersionCommand()) return c } Run Command The run command is implemented in the cmd\/cli\/run.go file, below the code used with comments:\n\/\/ This is our cli package package cli \/\/ Import required packages import ( &#34;errors&#34; &#34;github.com\/mvazquezc\/go-cli-template\/pkg\/example&#34; &#34;github.com\/spf13\/cobra&#34; ) \/\/ Define vars used to store sub-command parameters var ( stringParameter string intParameter int stringArrayParameter []string ) \/\/ NewRunCommand implements the run sub-command of example-ci func NewRunCommand() *cobra.Command { \/\/ Define a new cobra command for the run sub-command cmd := &amp;cobra.Command{ Use: &#34;run&#34;, Short: &#34;Exec the run command&#34;, SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) error { \/\/ Validate command Args with the validateRunCommandArgs function we created err := validateRunCommandArgs() \/\/ If arguments are not valid, return error to the user if err != nil { return err } \/\/ run command logic is implemented in the example package, we call the function here err = example.RunCommandRun(stringParameter) \/\/ If the command fails, retun error to the user if err != nil { return err } return err }, } \/\/ Add run sub-command flags using the function we created addRunCommandFlags(cmd) return cmd } \/\/ addRunCommandFlags receives a cobra command and adds flags to it func addRunCommandFlags(cmd *cobra.Command) { \/\/ Define the flags we want to use for our run sub-command flags := cmd.Flags() flags.StringVarP(&amp;stringParameter, &#34;string-parameter&#34;, &#34;s&#34;, &#34;&#34;, &#34;A string parameter&#34;) flags.IntVarP(&amp;intParameter, &#34;int-parameter&#34;, &#34;i&#34;, 1, &#34;An int parameter&#34;) flags.StringArrayVarP(&amp;stringArrayParameter, &#34;string-array&#34;, &#34;a&#34;, []string{&#34;example&#34;}, &#34;A string array parameter&#34;) \/\/ We can make flags required cmd.MarkFlagRequired(&#34;string-parameter&#34;) } \/\/ validateCommandArgs validates that arguments passed by the user are valid func validateRunCommandArgs() error { if intParameter != 1 { return errors.New(&#34;Not valid int-parameter&#34;) } return nil } Run Command Logic The run command logic is implemented in the pkg\/example\/run.go file, below the code used with comments:\n\/\/ This is our example package package example import &#34;fmt&#34; \/\/ RunCommandRun has the logic for running the run sub-command func RunCommandRun(stringParameter string) error { fmt.Printf(&#34;Run command executed with string parameter set to %s\\n.&#34;, stringParameter) return nil } Version Command The version command is implemented in the cmd\/cli\/version.go file, below the code used with comments:\n\/\/ This is our cli package package cli \/\/ Import required packages import ( &#34;fmt&#34; &#34;github.com\/mvazquezc\/go-cli-template\/pkg\/version&#34; &#34;github.com\/spf13\/cobra&#34; ) \/\/ Define vars used to store sub-command parameters var ( short bool ) \/\/ NewRunCommand implements the version sub-command of example-ci func NewVersionCommand() *cobra.Command { \/\/ Define a new cobra command for the version sub-command cmd := &amp;cobra.Command{ Use: &#34;version&#34;, Short: &#34;Display version information&#34;, RunE: func(cmd *cobra.Command, args []string) error { if !short { fmt.Printf(&#34;Build time: %s\\n&#34;, version.GetBuildTime()) fmt.Printf(&#34;Git commit: %s\\n&#34;, version.GetGitCommit()) fmt.Printf(&#34;Go version: %s\\n&#34;, version.GetGoVersion()) fmt.Printf(&#34;Go compiler: %s\\n&#34;, version.GetGoCompiler()) fmt.Printf(&#34;Go Platform: %s\\n&#34;, version.GetGoPlatform()) } else { fmt.Printf(&#34;%s\\n&#34;, version.PrintVersion()) } return nil }, } \/\/ Add run sub-command flags using the function we created addVersionFlags(cmd) return cmd } \/\/ addVersionCommandFlags receives a cobra command and adds flags to it func addVersionFlags(cmd *cobra.Command) { flags := cmd.Flags() flags.BoolVar(&amp;short, &#34;short&#34;, false, &#34;show only the version number&#34;) } Version Command Logic The run command logic is implemented in the pkg\/version\/version.go file, below the code used with comments:\n\/\/ This is our version package package version import ( &#34;fmt&#34; &#34;runtime&#34; ) \/\/ Define vars used by our package var ( version = &#34;0.0.1&#34; buildTime = &#34;1970-01-01T00:00:00Z&#34; gitCommit = &#34;notSet&#34; binaryName = &#34;example-cli&#34; ) \/\/ PrintVersion prints our root command version func PrintVersion() string { version := fmt.Sprintf(&#34;%s v%s+%s&#34;, binaryName, version, gitCommit) return version } \/\/ GetGitCommit returns the gitCommit func GetGitCommit() string { return gitCommit } \/\/ GetBuildTime returns the buildTime func GetBuildTime() string { return buildTime } \/\/ GetGoVersion returns the Version func GetGoVersion() string { return runtime.Version() } \/\/ GetGoPlatform returns the go platform func GetGoPlatform() string { return runtime.GOOS + &#34;\/&#34; + runtime.GOARCH } \/\/ GetGoCompiler returns the go compiler func GetGoCompiler() string { return runtime.Compiler } CLI in Action Once we have the CLI implemented, this is what we will get.\nCompile the CLI:\ngo build -o example-cli cmd\/main.go If we run the CLI without any sub-command, we will get the CLI help:\n.\/example-cli Example cli written in go Usage: example-cli [flags] example-cli [command] Available Commands: completion Generate the autocompletion script for the specified shell help Help about any command run Exec the run command version Display version information Flags: -h, --help help for example-cli Use &#34;example-cli [command] --help&#34; for more information about a command. We can go ahead and execute the version sub-command with the --sort flag:\n.\/example-cli version --short example-cli v0.0.1+notSet We can also execute the run sub-command:\n.\/example-cli run -s hello Run command executed with string parameter set to hello And if something goes wrong, the user will be notified:\n.\/example-cli run -s hello -i 3 Error: Not valid int-parameter Usage: example-cli run [flags] Flags: -h, --help help for run -i, --int-parameter int An int parameter (default 1) -a, --string-array stringArray A string array parameter (default [example]) -s, --string-parameter string A string parameter 2023\/01\/15 23:46:17 [ERROR] Not valid int-parameter Closing Thoughts As you have seen, writing CLIs in Go is pretty easy with the help of libraries like Cobra. If you want to see a more advanced implementation of a CLI you can check the CLI Alberto and I built here.\nYou can improve the version information for this CLI by using ldflags at build time, read this post to know more.\n","permalink":"https:\/\/linuxera.org\/writing-clis-go-cobra\/","summary":"Writing CLIs in Go using Cobra A few months ago, I was working with my colleague Alberto in a CLI. The language of choice was Go and I manage to learn a thing or two. In today&rsquo;s post we will see a very basic skeleton for a CLI written in Go. This will certainly help me in the future as a template for the next CLI, and maybe it helps you too!","title":"Writing CLIs in Go with Cobra"},{"content":"User Certificates in OpenShift 4 Attention\nThe information described in this blog post may not be a supported configuration for OpenShift 4. Please, refer to the official docs for supported documentation.\nIn this blog we will see how we can create OpenShift Users using client certificates and how to configure the API Server, so we can create client certificates using custom CAs. The information described in this blog was last tested with OpenShift 4.11.\nOpenShift Authentication As you may know, OpenShift 4 supports different authentication providers. By default, once your cluster is installed you will get a kubeadmin user to access the UI and a kubeconfig file configured with a client cert to access the API Server as cluster-admin.\nOn top of that you get an OAuth Server that can be configured for adding different authentication sources like GitHub, LDAP, etc. This post will focus on creating new client certificates to access the API Server via kubeconfig files.\nThe scenario will be as follows:\nA client certificate for the user luffy will be issued using a self-signed CA named customer-signer-custom. A client certificate for the user zoro will be issued using a self-signed CA named customer-signer-custom-2. A client certificate for the user nami will be issued using the internal OpenShift CA via a CertificateSigningRequest. Creating the client certificate for Nami using the internal OpenShift CA Before we create this first user, we need to understand how usernames and groups are assigned in Kubernetes when using client certificates. Groups for the user will be configured in the Organization field while username will be configured in the Common Name field.\nLet&rsquo;s get startes by creating a CSR for the client certificate using the openssl client:\nNote\nWe are using group &ldquo;system:admin&rdquo; and username &ldquo;nami&rdquo; for this client certificate.\nopenssl req -nodes -newkey rsa:4096 -keyout \/tmp\/nami.key -subj &#34;\/O=system:admin\/CN=nami&#34; -out \/tmp\/nami.csr Now that we have the csr, let&rsquo;s submit the CSR to OpenShift in order to sign it with the internal CA later:\ncat &lt;&lt; EOF | oc create -f - apiVersion: certificates.k8s.io\/v1 kind: CertificateSigningRequest metadata: name: nami-access spec: signerName: kubernetes.io\/kube-apiserver-client groups: - system:authenticated request: $(cat \/tmp\/nami.csr | base64 -w0) usages: - client auth EOF Next, time to approve the certificate request:\noc adm certificate approve nami-access The certificate has been approved, we can get it now from the cluster:\noc get csr nami-access -o jsonpath=&#39;{.status.certificate}&#39; | base64 -d &gt; \/tmp\/nami.crt At this point we&rsquo;re all set, next step will be creating a kubeconfig file for nami to log into our cluster, we will leave that for later. For now, let&rsquo;s continue creating the client certificates for luffy and zoro.\nCreating the client certificate for Luffy using the customer-signer-custom self-signed CA We need a self-signed CA, although this could be an existing CA that already exists in your environment, for this post we will create one using the openssl client:\nopenssl genrsa -out \/tmp\/customer-ca.key 4096 openssl req -x509 -new -nodes -key \/tmp\/customer-ca.key -sha256 -days 9999 -out \/tmp\/customer-ca.crt -subj &#34;\/OU=openshift\/CN=customer-signer-custom&#34; Now that we have the CA, let&rsquo;s create the luffy client certificate request:\nNote\nWe are using group &ldquo;system:admin&rdquo; and username &ldquo;luffy&rdquo; for this client certificate.\nopenssl req -nodes -newkey rsa:4096 -keyout \/tmp\/luffy.key -subj &#34;\/O=system:admin\/CN=luffy&#34; -out \/tmp\/luffy.csr We can now sign the csr:\nopenssl x509 -extfile &lt;(printf &#34;extendedKeyUsage = clientAuth&#34;) -req -in \/tmp\/luffy.csr -CA \/tmp\/customer-ca.crt -CAkey \/tmp\/customer-ca.key -CAcreateserial -out \/tmp\/luffy.crt -days 9999 -sha256 And we&rsquo;re done here, next step would be the kubeconfig creation. Let&rsquo;s continue with zoro's client certificate before we start creating the kubeconfig files.\nCreating the client certificate for Zoro using the customer-signer-custom-2 self-signed CA Note\nWe are using group &ldquo;system:admin&rdquo; and username &ldquo;zoro&rdquo; for this client certificate.\n# Create self-signed CA openssl genrsa -out \/tmp\/customer-ca-2.key 4096 openssl req -x509 -new -nodes -key \/tmp\/customer-ca-2.key -sha256 -days 9999 -out \/tmp\/customer-ca-2.crt -subj &#34;\/OU=openshift\/CN=customer-signer-custom-2&#34; # Create CSR for zoro&#39;s client cert openssl req -nodes -newkey rsa:4096 -keyout \/tmp\/zoro.key -subj &#34;\/O=system:admin\/CN=zoro&#34; -out \/tmp\/zoro.csr # Sign CSR openssl x509 -extfile &lt;(printf &#34;extendedKeyUsage = clientAuth&#34;) -req -in \/tmp\/zoro.csr -CA \/tmp\/customer-ca-2.crt -CAkey \/tmp\/customer-ca-2.key -CAcreateserial -out \/tmp\/zoro.crt -days 9999 -sha256 Creating the kubeconfig files for Nami, Luffy and Zoro Before we start creating the kubeconfig files we need to get the public cert of our API server, this will be used by the kubectl\/oc clients in order to trust the API Server certificate.\nexport OPENSHIFT_API_SERVER_ENDPOINT=api.cluster.example.com:6443 openssl s_client -showcerts -connect ${OPENSHIFT_API_SERVER_ENDPOINT} &lt;\/dev\/null 2&gt;\/dev\/null|openssl x509 -outform PEM &gt; \/tmp\/ocp-apiserver-cert.crt Let&rsquo;s start with Nami's kubeconfig:\noc --kubeconfig \/tmp\/nami config set-credentials nami --client-certificate=\/tmp\/nami.crt --client-key=\/tmp\/nami.key --embed-certs=true oc --kubeconfig \/tmp\/nami config set-cluster openshift-cluster-dev --certificate-authority=\/tmp\/ocp-apiserver-cert.crt --embed-certs=true --server=https:\/\/${OPENSHIFT_API_SERVER_ENDPOINT} oc --kubeconfig \/tmp\/nami config set-context openshift-dev --cluster=openshift-cluster-dev --namespace=default --user=nami oc --kubeconfig \/tmp\/nami config use-context openshift-dev Now let&rsquo;s do Zoro's:\noc --kubeconfig \/tmp\/zoro config set-credentials zoro --client-certificate=\/tmp\/zoro.crt --client-key=\/tmp\/zoro.key --embed-certs=true oc --kubeconfig \/tmp\/zoro config set-cluster openshift-cluster-dev --certificate-authority=\/tmp\/ocp-apiserver-cert.crt --embed-certs=true --server=https:\/\/${OPENSHIFT_API_SERVER_ENDPOINT} oc --kubeconfig \/tmp\/zoro config set-context openshift-dev --cluster=openshift-cluster-dev --namespace=default --user=zoro oc --kubeconfig \/tmp\/zoro config use-context openshift-dev And finally Luffy's:\noc --kubeconfig \/tmp\/luffy config set-credentials luffy --client-certificate=\/tmp\/luffy.crt --client-key=\/tmp\/luffy.key --embed-certs=true oc --kubeconfig \/tmp\/luffy config set-cluster openshift-cluster-dev --certificate-authority=\/tmp\/ocp-apiserver-cert.crt --embed-certs=true --server=https:\/\/${OPENSHIFT_API_SERVER_ENDPOINT} oc --kubeconfig \/tmp\/luffy config set-context openshift-dev --cluster=openshift-cluster-dev --namespace=default --user=luffy oc --kubeconfig \/tmp\/luffy config use-context openshift-dev Accessing our cluster with the new kubeconfig files: oc --kubeconfig \/tmp\/luffy whoami error: You must be logged in to the server (Unauthorized) oc --kubeconfig \/tmp\/zoro whoami error: You must be logged in to the server (Unauthorized) oc --kubeconfig \/tmp\/nami whoami nami As you can see from the above output only Nami can access the cluster, but why? - Well, the API Server doesn&rsquo;t trust the self-signed CAs we created. We need to configure it to trust them, let&rsquo;s do it:\nNote\nSince we have two self-signed CAs and the APIServer only accepts 1 ConfigMap, we need to create a bundle with all the CAs we want to trust when using client certificates authentication. This doesn&rsquo;t include the internal OpenShift CA, which is always trusted.\ncat \/tmp\/customer-ca.crt \/tmp\/customer-ca-2.crt &gt; \/tmp\/customer-custom-cas.crt oc create configmap customer-cas-custom -n openshift-config --from-file=ca-bundle.crt=\/tmp\/customer-custom-cas.crt Now that the ConfigMap is ready, let&rsquo;s tell the APIServer to use it:\noc patch apiserver cluster --type=merge -p &#39;{&#34;spec&#34;: {&#34;clientCA&#34;: {&#34;name&#34;: &#34;customer-cas-custom&#34;}}}&#39; If we try the kubeconfig files again, this is the result:\noc --kubeconfig \/tmp\/luffy whoami luffy oc --kubeconfig \/tmp\/zoro whoami zoro oc --kubeconfig \/tmp\/nami whoami nami Now all three work, but if we try to do other stuff like listing pods, nodes, etc. we will see that we don&rsquo;t have access to that. That&rsquo;s expected since in a default OCP installation we don&rsquo;t have RBAC rules for the system:admin group:\noc --kubeconfig \/tmp\/luffy get nodes Error from server (Forbidden): nodes is forbidden: User &#34;luffy&#34; cannot list resource &#34;nodes&#34; in API group &#34;&#34; at the cluster scope oc --kubeconfig \/tmp\/zoro -n default get pods Error from server (Forbidden): pods is forbidden: User &#34;zoro&#34; cannot list resource &#34;pods&#34; in API group &#34;&#34; in the namespace &#34;default&#34; oc --kubeconfig \/tmp\/nami -n default get deployments Error from server (Forbidden): deployments.apps is forbidden: User &#34;nami&#34; cannot list resource &#34;deployments&#34; in API group &#34;apps&#34; in the namespace &#34;default&#34; Let&rsquo;s configure users in the system:admin group as cluster admins:\noc adm policy add-cluster-role-to-group cluster-admin system:admin If we try again:\noc --kubeconfig \/tmp\/luffy get nodes NAME STATUS ROLES AGE VERSION openshift-master-0 Ready master,worker 99d v1.24.0+b62823b openshift-master-1 Ready master,worker 99d v1.24.0+b62823b openshift-master-2 Ready master,worker 99d v1.24.0+b62823b oc --kubeconfig \/tmp\/zoro -n default get pods NAME READY STATUS RESTARTS AGE test-64ccd87d6c-98j45 1\/1 Running 1 4d4h oc --kubeconfig \/tmp\/nami -n default get deployments NAME READY UP-TO-DATE AVAILABLE AGE test 1\/1 1 1 60d That&rsquo;s it! I hope this clears how you can work with client certificates in OpenShift 4.\n","permalink":"https:\/\/linuxera.org\/user-certificates-in-openshift4\/","summary":"User Certificates in OpenShift 4 Attention\nThe information described in this blog post may not be a supported configuration for OpenShift 4. Please, refer to the official docs for supported documentation.\nIn this blog we will see how we can create OpenShift Users using client certificates and how to configure the API Server, so we can create client certificates using custom CAs. The information described in this blog was last tested with OpenShift 4.","title":"OpenShift 4 User Certificates"},{"content":"Working with Pod Security Standards In Kubernetes v1.25 Pod Security admission has moved to stable, replacing Pod Security Policy admission. This feature has been in beta and enabled by default since Kubernetes v1.23 in this post we are going to cover what&rsquo;s new with Pod Security Admission (PSA) and how it affects the workloads being deployed in our clusters.\nNote\nFor this post I&rsquo;ll be running a Kubernetes v1.25 cluster. If you want to try this in your own environment you can use your favorite tool to get a K8s cluster up and running, I&rsquo;ll be using kcli.\n# Create a Kubernetes 1.25 cluster with 1 master and 1 worker using calico as SDN, nginx as ingress controller, metallb for loadbalancer services and CRI-O as container runtime kcli create kube generic -P ctlplanes=1 -P workers=1 -P ctlplane_memory=4096 -P numcpus=2 -P worker_memory=4096 -P sdn=calico -P version=1.25 -P ingress=true -P ingress_method=nginx -P metallb=true -P engine=crio -P domain=linuxera.org psa-cluster This is how our cluster looks like:\nkubectl get nodes NAME STATUS ROLES AGE VERSION psa-cluster-master-0.linuxera.org Ready control-plane,master 4m19s v1.25.0 psa-cluster-worker-0.linuxera.org Ready worker 1m20s v1.25.0 Pod Security Admission The Pod Security Admission relies on both Pod Security Standards which define the different security policies that need to be checked for workloads and Pod Admission Modes that define how the standards are applied for a given namespace.\nPod Security Standards This new admission plugin relies on pre-backed Pod Security Standards. These standards will evolve every Kubernetes release to include \/ adapt new security rules.\nAs of Kubernetes v1.25 there are three Pod Security Standards defined:\nNote\nYou can read each standard requirements on this link.\nprivileged baseline restricted Pod Admission Modes The cluster admin\/namespace admin can configure an admission mode that will be used to do admission validations against workloads being deployed in the namespace. There are three admission modes that can be configured on a namespace:\nenforce: Policy violations will cause the pod to be rejected. audit: Policy violations will be logged in the audit log, pod will be allowed. warn: Policy violations will cause a user-facing warning, pod will be allowed. Each mode can be configured with a different Pod Security Standard. For example, a namespace could enforce using the privileged standard and audit\/warn via therestricted standard.\nThe admission modes and the standards to be used are configured at the namespace level via the use of the pod-security.kubernetes.io\/&lt;MODE&gt;: &lt;LEVEL&gt; label.\nAs earlier mentioned, these Pod Security Standards will evolve over time, and since these are versioned we can specify which version of a specific mode we want to enforce via the use of the pod-security.kubernetes.io\/&lt;MODE&gt;-version: &lt;VERSION&gt; label, where &lt;VERSION&gt; refers to a Kubernetes minor version like v1.25.\nIf we put all this information together, we can get to a namespace definition like the one below:\nNote\nIn the example below we use the version v1.25, a namespace could also point to the latest available by using latest instead.\napiVersion: v1 kind: Namespace metadata: name: test-namespace labels: pod-security.kubernetes.io\/enforce: privileged pod-security.kubernetes.io\/enforce-version: v1.25 pod-security.kubernetes.io\/audit: restricted pod-security.kubernetes.io\/audit-version: v1.25 pod-security.kubernetes.io\/warn: restricted pod-security.kubernetes.io\/warn-version: v1.25 It&rsquo;s important to mention that audit and warning modes are applied to workload resources (resources that have a pod template definition) like Deployments, Jobs, etc. to help catch violations early. On the other hand, enforce mode is applied to the resulting pod object.\nPod Security Admission Configuration Pod Security Admission comes pre-configured in Kubernetes v1.25 with the least restrictive policy, it&rsquo;s possible to modify the default configuration by modifying the admission configuration for this plugin, you can read here how to do it.\nIf you checked the link above, you have seen that exemptions can be configured for the admission, this will allow the cluster admin to configure users, runtime classes or namespaces that won&rsquo;t be evaluated by PSA. From this three exemptions, the runtime class could be helpful if you want to keep a namespace as restrictive as possible by default, but then have some workload that is not evaluated against a PSA.\nPod Security Standards in Action Now that we know the basics around PSA, we can go ahead and run some tests to understand how it works. We will be using a simple go app.\nNon-restrictive namespace In this first example we&rsquo;re going to deploy our workload in a namespace that enforces the privileged standard and audits\/warns the restricted standard.\nCreate the namespace for our workload with the appropriated PSA settings:\ncat &lt;&lt;EOF | kubectl apply -f - apiVersion: v1 kind: Namespace metadata: name: non-restrictive-namespace labels: pod-security.kubernetes.io\/enforce: privileged pod-security.kubernetes.io\/enforce-version: v1.25 pod-security.kubernetes.io\/audit: restricted pod-security.kubernetes.io\/audit-version: v1.25 pod-security.kubernetes.io\/warn: restricted pod-security.kubernetes.io\/warn-version: v1.25 EOF Create the workload:\ncat &lt;&lt;EOF | kubectl -n non-restrictive-namespace apply -f - apiVersion: apps\/v1 kind: Deployment metadata: labels: app: go-app name: go-app spec: replicas: 1 selector: matchLabels: app: go-app strategy: {} template: metadata: labels: app: go-app spec: containers: - image: quay.io\/mavazque\/reversewords:latest name: reversewords resources: {} EOF We got some client warnings (caused by the warn mode) saying the violations of our workload when checked against the restricted standard:\nWarning: would violate PodSecurity &#34;restricted:v1.25&#34;: allowPrivilegeEscalation != false (container &#34;reversewords&#34; must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container &#34;reversewords&#34; must set securityContext.capabilities.drop=[&#34;ALL&#34;]), runAsNonRoot != true (pod or container &#34;reversewords&#34; must set securityContext.runAsNonRoot=true), seccompProfile (pod or container &#34;reversewords&#34; must set securityContext.seccompProfile.type to &#34;RuntimeDefault&#34; or &#34;Localhost&#34;) But the workload is running:\nkubectl -n non-restrictive-namespace get pod NAME READY STATUS RESTARTS AGE go-app-5b954b7b74-kwkwn 1\/1 Running 0 1m30s In the next scenario we will configure the enforce mode to the restricted standard.\nRestrictive namespace Create the namespace for our workload with the appropriated PSA settings:\ncat &lt;&lt;EOF | kubectl apply -f - apiVersion: v1 kind: Namespace metadata: name: restrictive-namespace labels: pod-security.kubernetes.io\/enforce: restricted pod-security.kubernetes.io\/enforce-version: v1.25 pod-security.kubernetes.io\/audit: restricted pod-security.kubernetes.io\/audit-version: v1.25 pod-security.kubernetes.io\/warn: restricted pod-security.kubernetes.io\/warn-version: v1.25 EOF Create the workload:\ncat &lt;&lt;EOF | kubectl -n restrictive-namespace apply -f - apiVersion: apps\/v1 kind: Deployment metadata: labels: app: go-app name: go-app spec: replicas: 1 selector: matchLabels: app: go-app strategy: {} template: metadata: labels: app: go-app spec: containers: - image: quay.io\/mavazque\/reversewords:latest name: reversewords resources: {} EOF Again, we got some client warnings (caused by the warn mode) saying the violations of our workload when checked against the restricted standard:\nWarning: would violate PodSecurity &#34;restricted:v1.25&#34;: allowPrivilegeEscalation != false (container &#34;reversewords&#34; must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container &#34;reversewords&#34; must set securityContext.capabilities.drop=[&#34;ALL&#34;]), runAsNonRoot != true (pod or container &#34;reversewords&#34; must set securityContext.runAsNonRoot=true), seccompProfile (pod or container &#34;reversewords&#34; must set securityContext.seccompProfile.type to &#34;RuntimeDefault&#34; or &#34;Localhost&#34;) And this time, the workload is NOT running:\nkubectl -n restrictive-namespace get pod No resources found in restrictive-namespace namespace. If you remember, the enforce mode is applied against the pod object and not against the workload objects (like Deployment in this case). That&rsquo;s why the deployment was admitted but the pod it&rsquo;s not.\nWe can see in the namespace events \/ replicaset status why the pod is not running:\nkubectl -n restrictive-namespace get events LAST SEEN TYPE REASON OBJECT MESSAGE 3m44s Warning FailedCreate replicaset\/go-app-5b954b7b74 Error creating: pods &#34;go-app-5b954b7b74-dfq9g&#34; is forbidden: violates PodSecurity &#34;restricted:v1.25&#34;: allowPrivilegeEscalation != false (container &#34;reversewords&#34; must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container &#34;reversewords&#34; must set securityContext.capabilities.drop=[&#34;ALL&#34;]), runAsNonRoot != true (pod or container &#34;reversewords&#34; must set securityContext.runAsNonRoot=true), seccompProfile (pod or container &#34;reversewords&#34; must set securityContext.seccompProfile.type to &#34;RuntimeDefault&#34; or &#34;Localhost&#34;) If we want this workload to be admitted in the cluster we need to fine tune the pod&rsquo;s configuration, let&rsquo;s remove the deployment and get it created with a config allowed by the restricted standard.\nRemove the deployment\nkubectl -n restrictive-namespace delete deployment go-app Create the workload with the proper config:\ncat &lt;&lt;EOF | kubectl -n restrictive-namespace apply -f - apiVersion: apps\/v1 kind: Deployment metadata: labels: app: go-app name: go-app spec: replicas: 1 selector: matchLabels: app: go-app strategy: {} template: metadata: labels: app: go-app spec: containers: - image: quay.io\/mavazque\/reversewords:latest name: reversewords resources: {} securityContext: allowPrivilegeEscalation: false capabilities: drop: - ALL runAsNonRoot: true runAsUser: 1024 seccompProfile: type: RuntimeDefault EOF This time we didn&rsquo;t get any warnings and if we check for pods in the namespace we will see our workload is running:\nkubectl -n restrictive-namespace get pod NAME READY STATUS RESTARTS AGE go-app-5f45c655b6-z26kv 1\/1 Running 0 25s Tip 1 - Check if a given workload would be rejected in a given namespace You can try to create a workload against a given namespace in dry-run mode and get client warnings, example:\ncat &lt;&lt;EOF | kubectl -n restrictive-namespace apply --dry-run=server -f - apiVersion: apps\/v1 kind: Deployment metadata: labels: app: go-app name: go-app spec: replicas: 1 selector: matchLabels: app: go-app strategy: {} template: metadata: labels: app: go-app spec: containers: - image: quay.io\/mavazque\/reversewords:latest name: reversewords resources: {} EOF You will get a warning like this:\nWarning: would violate PodSecurity &#34;restricted:v1.25&#34;: allowPrivilegeEscalation != false (container &#34;reversewords&#34; must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container &#34;reversewords&#34; must set securityContext.capabilities.drop=[&#34;ALL&#34;]), runAsNonRoot != true (pod or container &#34;reversewords&#34; must set securityContext.runAsNonRoot=true), seccompProfile (pod or container &#34;reversewords&#34; must set securityContext.seccompProfile.type to &#34;RuntimeDefault&#34; or &#34;Localhost&#34;) deployment.apps\/go-app created (server dry run) Tip 2 - Check if workloads on a given namespace would violate a given policy You can try to label a namespace in dry-run mode and get client warnings, as an example let&rsquo;s see what would happen if we moved the namespace from the first scenario from the privileged standard to the restricted one:\nkubectl label --dry-run=server --overwrite ns non-restrictive-namespace pod-security.kubernetes.io\/enforce=restricted You will get a warning like this:\nWarning: existing pods in namespace &#34;non-restrictive-namespace&#34; violate the new PodSecurity enforce level &#34;restricted:v1.25&#34; Warning: go-app-5b954b7b74-kwkwn: allowPrivilegeEscalation != false, unrestricted capabilities, runAsNonRoot != true, seccompProfile namespace\/non-restrictive-namespace labeled Closing Thoughts Pod Security Admission is a great addition to the Kubernetes security, I hope this time its adoption increases compared to PSPs. In the next post we will talk about the new changes around Seccomp that were introduced in Kubernetes.\n","permalink":"https:\/\/linuxera.org\/working-with-pod-security-standards\/","summary":"Working with Pod Security Standards In Kubernetes v1.25 Pod Security admission has moved to stable, replacing Pod Security Policy admission. This feature has been in beta and enabled by default since Kubernetes v1.23 in this post we are going to cover what&rsquo;s new with Pod Security Admission (PSA) and how it affects the workloads being deployed in our clusters.\nNote\nFor this post I&rsquo;ll be running a Kubernetes v1.25 cluster. If you want to try this in your own environment you can use your favorite tool to get a K8s cluster up and running, I&rsquo;ll be using kcli.","title":"Working with Pod Security Standards"},{"content":"Capabilities and Seccomp Profiles on Kubernetes In a previous post we talked about Linux Capabilities and Secure Compute Profiles, in this post we are going to see how we can leverage them on Kubernetes.\nWe will need a Kubernetes cluster, I&rsquo;m going to use kcli in order to get one. Below command will deploy a Kubernetes cluster on VMs:\nNOTE: You can create a parameters file with the cluster configuration as well.\n# Create a Kubernetes 1.20 cluster with 1 master and 1 worker using calico as SDN, nginx as ingress controller, metallb for loadbalancer services and CRI-O as container runtime kcli create kube generic -P ctlplanes=1 -P workers=1 -P ctlplane_memory=4096 -P numcpus=2 -P worker_memory=4096 -P sdn=calico -P version=1.20 -P ingress=true -P ingress_method=nginx -P metallb=true -P engine=crio -P domain=linuxera.org caps-cluster After a few moments we will get the kubeconfig for accessing our cluster:\nKubernetes cluster caps-cluster deployed!!! INFO export KUBECONFIG=$HOME\/.kcli\/clusters\/caps-cluster\/auth\/kubeconfig INFO export PATH=$PWD:$PATH We can start using it right away:\nexport KUBECONFIG=$HOME\/.kcli\/clusters\/caps-cluster\/auth\/kubeconfig kubectl get nodes NAME STATUS ROLES AGE VERSION caps-cluster-master-0.linuxera.org Ready control-plane,master 8m19s v1.20.5 caps-cluster-worker-0.linuxera.org Ready worker 3m33s v1.20.5 Capabilities on Kubernetes Capabilities on Kubernetes are configured for pods or containers via the SecurityContext.\nIn the next scenarios we are going to see how we can configure different capabilities for our containers and how they behave depending on the user running our container.\nWe will be using a demo application that listens on a given port, by default the application image uses a non-root user. In a previous post we mentioned how capabilities behave differently depending on the user that runs the process, we will see how that affects when running on containers.\nContainer Runtime Default Capabilities As previously mentioned, container runtimes come with a set of enabled capabilities that will be assigned to every container if not otherwise specified. We&rsquo;re using CRI-O in our Kubernetes cluster and we can find the default capabilities in the CRI-O configuration file at \/etc\/crio\/crio.conf present in the nodes:\ndefault_capabilities = [ &#34;CHOWN&#34;, &#34;DAC_OVERRIDE&#34;, &#34;FSETID&#34;, &#34;FOWNER&#34;, &#34;SETGID&#34;, &#34;SETUID&#34;, &#34;SETPCAP&#34;, &#34;NET_BIND_SERVICE&#34;, &#34;KILL&#34;, ] The capabilities in the list above will be the ones added to containers by default.\nPod running with root UID\nCreate a namespace:\nNAMESPACE=test-capabilities kubectl create ns ${NAMESPACE} Create a pod running our test application with UID 0:\ncat &lt;&lt;EOF | kubectl -n ${NAMESPACE} create -f - apiVersion: v1 kind: Pod metadata: name: reversewords-app-captest-root spec: containers: - image: quay.io\/mavazque\/reversewords:ubi8 name: reversewords securityContext: runAsUser: 0 dnsPolicy: ClusterFirst restartPolicy: Never status: {} EOF Review the capability sets for the application process:\nkubectl -n ${NAMESPACE} exec -ti reversewords-app-captest-root -- grep Cap \/proc\/1\/status CapInh:\t00000000000005fb CapPrm:\t00000000000005fb CapEff:\t00000000000005fb CapBnd:\t00000000000005fb CapAmb:\t0000000000000000 If we decode the effective set this is what we get:\ncapsh --decode=00000000000005fb NOTE: You can see how the pod got assigned the runtime&rsquo;s default caps.\n0x00000000000005fb=cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service Pod running with non-root UID\nCreate a pod running our test application with a non-root UID:\nNAMESPACE=test-capabilities cat &lt;&lt;EOF | kubectl -n ${NAMESPACE} create -f - apiVersion: v1 kind: Pod metadata: name: reversewords-app-captest-nonroot spec: containers: - image: quay.io\/mavazque\/reversewords:ubi8 name: reversewords securityContext: runAsUser: 1024 dnsPolicy: ClusterFirst restartPolicy: Never status: {} EOF Review the capability sets for the application process:\nkubectl -n ${NAMESPACE} exec -ti reversewords-app-captest-nonroot -- grep Cap \/proc\/1\/status CapInh:\t00000000000005fb CapPrm:\t0000000000000000 CapEff:\t0000000000000000 CapBnd:\t00000000000005fb CapAmb:\t0000000000000000 You can see how the effective and permitted sets were cleared. We explained that behaviour in our previous post. That happens because we&rsquo;re doing execve to an unprivileged process so those capability sets get cleared.\nThis has some consequences when running our workloads on Kubernetes, outside Kubernetes we could use Ambient capabilities, but at the time of this writing, Ambient capabilities are not supported on Kubernetes. This means that we can only use file capabilities or capability aware programs in order to get capabilities on programs running as nonroot on Kubernetes.\nConfiguring capabilities for our workloads At this point we know what are the differences with regards to capabilities when running our workloads with a root or a nonroot UID. In the next scenarios we are going to see how we can configure our workloads so they only get the required capabilities they need in order to run.\nWorkload running with root UID\nCreate a deployment for our workload:\nNOTE: We are dropping all of the runtime&rsquo;s default capabilities, on top of that we add the NET_BIND_SERVICE capability and request the app to run with root UID. In the environment variables we configure our app to listen on port 80.\nNAMESPACE=test-capabilities cat &lt;&lt;EOF | kubectl -n ${NAMESPACE} create -f - apiVersion: apps\/v1 kind: Deployment metadata: creationTimestamp: null labels: app: reversewords-app-rootuid name: reversewords-app-rootuid spec: replicas: 1 selector: matchLabels: app: reversewords-app-rootuid strategy: {} template: metadata: creationTimestamp: null labels: app: reversewords-app-rootuid spec: containers: - image: quay.io\/mavazque\/reversewords:ubi8 name: reversewords resources: {} env: - name: APP_PORT value: &#34;80&#34; securityContext: runAsUser: 0 capabilities: drop: - CHOWN - DAC_OVERRIDE - FSETID - FOWNER - SETGID - SETUID - SETPCAP - KILL add: - NET_BIND_SERVICE status: {} EOF We can check the logs for our application and see that it&rsquo;s working fine:\nkubectl -n ${NAMESPACE} logs deployment\/reversewords-app-rootuid 2021\/04\/01 09:59:39 Starting Reverse Api v0.0.18 Release: NotSet 2021\/04\/01 09:59:39 Listening on port 80 If we look at the capability sets this is what we get:\nkubectl -n ${NAMESPACE} exec -ti deployment\/reversewords-app-rootuid -- grep Cap \/proc\/1\/status CapInh:\t0000000000000400 CapPrm:\t0000000000000400 CapEff:\t0000000000000400 CapBnd:\t0000000000000400 CapAmb:\t0000000000000000 As expected, only NET_BIND_SERVICE capability is available:\ncapsh --decode=0000000000000400 0x0000000000000400=cap_net_bind_service The workload worked as expected when running with root UID, in the next scenario we will try the same app but this time running with a non-root UID.\nWorkload running with non-root UID\nCreate a deployment for our workload:\nNOTE: We are dropping all of the runtime&rsquo;s default capabilities, on top of that we add the NET_BIND_SERVICE capability and request the app to run with non-root UID. In the environment variables we configure our app to listen on port 80.\nNAMESPACE=test-capabilities cat &lt;&lt;EOF | kubectl -n ${NAMESPACE} create -f - apiVersion: apps\/v1 kind: Deployment metadata: creationTimestamp: null labels: app: reversewords-app-nonrootuid name: reversewords-app-nonrootuid spec: replicas: 1 selector: matchLabels: app: reversewords-app-nonrootuid strategy: {} template: metadata: creationTimestamp: null labels: app: reversewords-app-nonrootuid spec: containers: - image: quay.io\/mavazque\/reversewords:ubi8 name: reversewords resources: {} env: - name: APP_PORT value: &#34;80&#34; securityContext: runAsUser: 1024 capabilities: drop: - CHOWN - DAC_OVERRIDE - FSETID - FOWNER - SETGID - SETUID - SETPCAP - KILL add: - NET_BIND_SERVICE status: {} EOF We can check the logs for our application and see if it&rsquo;s working:\nkubectl -n ${NAMESPACE} logs deployment\/reversewords-app-nonrootuid 2021\/04\/01 10:09:10 Starting Reverse Api v0.0.18 Release: NotSet 2021\/04\/01 10:09:10 Listening on port 80 2021\/04\/01 10:09:10 listen tcp :80: bind: permission denied This time the application didn&rsquo;t bind to port 80, let&rsquo;s update the app configuration so it binds to port 8080 and then we will review the capability sets:\n# Patch the app so it binds to port 8080 kubectl -n ${NAMESPACE} patch deployment reversewords-app-nonrootuid -p &#39;{&#34;spec&#34;:{&#34;template&#34;:{&#34;spec&#34;:{&#34;$setElementOrder\/containers&#34;:[{&#34;name&#34;:&#34;reversewords&#34;}],&#34;containers&#34;:[{&#34;$setElementOrder\/env&#34;:[{&#34;name&#34;:&#34;APP_PORT&#34;}],&#34;env&#34;:[{&#34;name&#34;:&#34;APP_PORT&#34;,&#34;value&#34;:&#34;8080&#34;}],&#34;name&#34;:&#34;reversewords&#34;}]}}}}&#39; # Get capability sets kubectl -n ${NAMESPACE} exec -ti deployment\/reversewords-app-nonrootuid -- grep Cap \/proc\/1\/status CapInh:\t0000000000000400 CapPrm:\t0000000000000000 CapEff:\t0000000000000000 CapBnd:\t0000000000000400 CapAmb:\t0000000000000000 We don&rsquo;t have the NET_BIND_SERVICE in the effective set, if you remember from our previous post we would need the capability in the ambient set in order for our application to work, but as we said Kubernetes still doesn&rsquo;t support ambient capabilities so our only option is make use of file capabilities.\nWe have created a new image for our application and our application binary now has the NET_BIND_SERVICE capability in the effective and permitted file capability sets. Let&rsquo;s update the deployment configuration.\nNOTE: We configured the app to bind to port 80 and changed the container image with the one that has the required changes.\nkubectl -n ${NAMESPACE} patch deployment reversewords-app-nonrootuid -p &#39;{&#34;spec&#34;:{&#34;template&#34;:{&#34;spec&#34;:{&#34;$setElementOrder\/containers&#34;:[{&#34;name&#34;:&#34;reversewords&#34;}],&#34;containers&#34;:[{&#34;$setElementOrder\/env&#34;:[{&#34;name&#34;:&#34;APP_PORT&#34;}],&#34;env&#34;:[{&#34;name&#34;:&#34;APP_PORT&#34;,&#34;value&#34;:&#34;80&#34;}],&#34;image&#34;:&#34;quay.io\/mavazque\/reversewords-captest:latest&#34;,&#34;name&#34;:&#34;reversewords&#34;}]}}}}&#39; We can check the logs for our application and see if it&rsquo;s working:\nkubectl -n ${NAMESPACE} logs deployment\/reversewords-app-nonrootuid 2021\/04\/01 10:18:42 Starting Reverse Api v0.0.21 Release: NotSet 2021\/04\/01 10:18:42 Listening on port 80 This time the application was able to bind to port 80, let&rsquo;s review the capability sets:\nkubectl -n ${NAMESPACE} exec -ti deployment\/reversewords-app-nonrootuid -- grep Cap \/proc\/1\/status NOTE: Since our application binary has the required capability in its file capability sets the process thread was able to gain that capability:\nCapInh:\t0000000000000400 CapPrm:\t0000000000000400 CapEff:\t0000000000000400 CapBnd:\t0000000000000400 CapAmb:\t0000000000000000 We can check the file capability configured in our application binary:\nkubectl -n ${NAMESPACE} exec -ti deployment\/reversewords-app-nonrootuid -- getcap \/usr\/bin\/reverse-words \/usr\/bin\/reverse-words = cap_net_bind_service+eip Seccomp Profiles on Kubernetes In this scenario we&rsquo;re going to reuse the Secure Compute profile we created in the previous post.\nConfiguring Seccomp Profiles on the cluster nodes By default Kubelet will try to find the seccomp profiles in the \/var\/lib\/kubelet\/seccomp\/ path. This path can be configured in the kubelet config.\nWe are going to create the two seccomp profiles that we will be using in the nodes.\nCreate below file on every node that can run workloads as \/var\/lib\/kubelet\/seccomp\/centos8-ls.json:\nNOTE: This is the seccomp profile that allows us to run a centos8 image that runs ls \/ as we saw in the previous post.\n{ &#34;defaultAction&#34;: &#34;SCMP_ACT_ERRNO&#34;, &#34;architectures&#34;: [ &#34;SCMP_ARCH_X86_64&#34; ], &#34;syscalls&#34;: [ { &#34;names&#34;: [ &#34;access&#34;, &#34;arch_prctl&#34;, &#34;brk&#34;, &#34;capget&#34;, &#34;capset&#34;, &#34;chdir&#34;, &#34;close&#34;, &#34;epoll_ctl&#34;, &#34;epoll_pwait&#34;, &#34;execve&#34;, &#34;exit_group&#34;, &#34;fchown&#34;, &#34;fcntl&#34;, &#34;fstat&#34;, &#34;fstatfs&#34;, &#34;futex&#34;, &#34;getdents64&#34;, &#34;getpid&#34;, &#34;getppid&#34;, &#34;ioctl&#34;, &#34;mmap&#34;, &#34;mprotect&#34;, &#34;munmap&#34;, &#34;nanosleep&#34;, &#34;newfstatat&#34;, &#34;openat&#34;, &#34;prctl&#34;, &#34;pread64&#34;, &#34;prlimit64&#34;, &#34;read&#34;, &#34;rt_sigaction&#34;, &#34;rt_sigprocmask&#34;, &#34;rt_sigreturn&#34;, &#34;sched_yield&#34;, &#34;seccomp&#34;, &#34;set_robust_list&#34;, &#34;set_tid_address&#34;, &#34;setgid&#34;, &#34;setgroups&#34;, &#34;setuid&#34;, &#34;stat&#34;, &#34;statfs&#34;, &#34;tgkill&#34;, &#34;write&#34; ], &#34;action&#34;: &#34;SCMP_ACT_ALLOW&#34;, &#34;args&#34;: [], &#34;comment&#34;: &#34;&#34;, &#34;includes&#34;: {}, &#34;excludes&#34;: {} } ] } Configuring seccomp profiles for our workloads Create a namespace:\nNAMESPACE=test-seccomp kubectl create ns ${NAMESPACE} Seccomp profiles can be configured at pod or container level, this time we&rsquo;re going to configure it at pod level:\nNOTE: We configured the seccompProfile centos8-ls.json.\ncat &lt;&lt;EOF | kubectl -n ${NAMESPACE} create -f - apiVersion: v1 kind: Pod metadata: name: seccomp-ls-test spec: securityContext: seccompProfile: type: Localhost localhostProfile: centos8-ls.json containers: - image: registry.centos.org\/centos:8 name: seccomp-ls-test command: [&#34;ls&#34;, &#34;\/&#34;] dnsPolicy: ClusterFirst restartPolicy: Never status: {} EOF The pod was executed with no issues:\nkubectl -n ${NAMESPACE} logs seccomp-ls-test bin dev ... Let&rsquo;s try to create a new pod that runs ls -l instead. On top of that we will configure the seccomp profile at the container level.\ncat &lt;&lt;EOF | kubectl -n ${NAMESPACE} create -f - apiVersion: v1 kind: Pod metadata: name: seccomp-lsl-test spec: containers: - image: registry.centos.org\/centos:8 name: seccomp-lsl-test command: [&#34;ls&#34;, &#34;-l&#34;, &#34;\/&#34;] securityContext: seccompProfile: type: Localhost localhostProfile: centos8-ls.json dnsPolicy: ClusterFirst restartPolicy: Never status: {} EOF As expected, the pod failed since the seccomp profile doesn&rsquo;t have all the required syscalls required for the command to run permitted:\nkubectl -n ${NAMESPACE} logs seccomp-lsl-test ls: cannot access &#39;\/&#39;: Operation not permitted Closing Thoughts At this point you should&rsquo;ve a clear understanding of when your workloads will benefit from using capabilities or seccomp profiles.\nWe&rsquo;ve not been through how we can control which capabilities \/ seccomp a specific user can use, PodSecurityPolicies can be used to control such things on Kubernetes. In OpenShift you can use SecurityContextConstraints.\nIf you want to learn more around these topics feel free to take a look at the following SCCs lab: https:\/\/github.com\/mvazquezc\/scc-fun\/blob\/main\/README.md\n","permalink":"https:\/\/linuxera.org\/capabilities-seccomp-kubernetes\/","summary":"Capabilities and Seccomp Profiles on Kubernetes In a previous post we talked about Linux Capabilities and Secure Compute Profiles, in this post we are going to see how we can leverage them on Kubernetes.\nWe will need a Kubernetes cluster, I&rsquo;m going to use kcli in order to get one. Below command will deploy a Kubernetes cluster on VMs:\nNOTE: You can create a parameters file with the cluster configuration as well.","title":"Capabilities and Seccomp Profiles on Kubernetes"},{"content":"Container Security - Linux Capabilities and Secure Compute Profiles In this post we are going to see two security mechanisms used in Linux Containers in order to provide a security layer for our workloads.\nWe will see how Linux Capabilities and Secure Compute Profiles can be used for limiting the attack surface for our containers.\nThe first part of the blog post will be an introduction to Linux Capabilities and Secure Compute Profiles, second part will show how these technologies work through the use of demos.\nLinux Capabilities For the purpose of permission checks, traditional UNIX implementations distinguish two categories of processes:\nPrivileged Processes: Whose effective user ID is 0, referred to as superuser or root. Unprivileged Processes: Whose effective UID is nonzero. Privileged processes bypass all kernel permissions checks, on the other hand, unprivileged processes are subject to full permissions checking based on the processes credentials. Usually effective UID, effective GID and supplementary group list.\nStarting with kernel 2.2, Linux divides the privileges traditionally associated with superuser into distinct units, known as capabilities, which can be independently enabled and disabled.\nYou need to keep in mind that capabilities are a per-thread attribute.\nThe first square represents root without capabilities before Linux kernel 2.2. The second square represents root with full capabilities. The third square represents root with only a few capabilities enabled. We can say that the power of root comes from the capabilities it can use rather than from being root itself. This will be important to understand that even if a container is running as root UID it doesn&rsquo;t mean that it has full root privileges.\nAt the moment of this writing there are a total of 41 capabilities, you can find the list here. We are going to see some of the most common ones:\nCapability Allows NET_RAW Use RAW and PACKET sockets SETUID Make arbitrary manipulations of process UIDs CHOWN Marke arbitrary changes to file UIDs and GIDs SYS_PTRACE Trace arbitrary processes using ptrace SYS_TIME Set system clock Container runtimes have some of these capabilities enabled by default, for example, you can check the default capabilities enabled by the CRI-O runtime on its version v1.21 here.\nOne potential question you might have could be &ldquo;What capabilities are required for my application?&rdquo; - Well, knowing which capabilities are required by your applications requires a very good knowledge of the application by the developer. There is no magic tool that will tell you which capabilities are actually required.\nSecure Compute Profiles (Seccomp) Containers typically run a single application with a set of well-defined tasks, these applications usually require a small subset of the underlying operating system kernel APIs. For example, an httpd server does not require the mount syscall at all, why should the app have access to this syscall?\nIn order to limit the attack vector of a subverted process running in a container, the seccomp Linux kernel feature can be used to limit which syscalls a process has access to. We can think of seccomp like a firewall for syscalls.\nCreating your own seccomp profiles can be tedious and often requires deep knowledge of the application. For example, a developer must be aware that a framework that sets up a network server to accept connections would translate into calling socket, bind and listen system calls. This time, there is some tooling that can help us getting the list of syscalls used by our applications:\noci-seccomp-bpf-hook\nKeep in mind when using the oci hook for creating seccomp profiles for runtimes such as CRI-O that you need to run the hook with the proper container runtime, e.g: crun vs runc. strace\netc\nSecure Compute Profiles can be defined using JSON, below we will see an example:\n{ &#34;defaultAction&#34;: &#34;SCMP_ACT_ERRNO&#34;, &#34;architectures&#34;: [ &#34;SCMP_ARCH_X86_64&#34;, &#34;SCMP_ARCH_X86&#34;, &#34;SCMP_ARCH_X32&#34; ], &#34;syscalls&#34;: [ { &#34;names&#34;: [ &#34;accept4&#34;, &#34;epoll_wait&#34;, &#34;pselect6&#34;, &#34;futex&#34; ], &#34;action&#34;: &#34;SCMP_ACT_ALLOW&#34; } ] } Profiles can have multiple actions configured:\nAction Result SCMP_ACT_ALLOW Allows the use of the specified syscalls SCMP_ACT_ERRNO Denies the use of the specified syscalls SCMP_ACT_LOG Allows the use of any syscalls, but logs in the audit log the ones that are not explicitly permitted Above policy can be interpreted as:\nThe default action for syscalls not defined in the seccomp is deny, that means that we will only allow running syscalls explicitly permitted in our policy. The policy applies to the system architectures defined in architectures. We have a group of 4 syscalls that are permitted: accept4, epoll_wait, pselect6 and futex. Linux Capabilities in Action In the previous section on capabilities we said that capabilities are a per-thread attribute, and as such every thread has the following capability sets containing zero or more capabilities:\nPermitted Set Capabilities that the thread may assume. It also limits the capabilities that may be added to the inheritable set by a thread that has the SETPCAP capability in its effective set. If a thread drops a capability from its permitted set, it can never reacquire that capability unless it execve either a SETUID program or a program with that capability set as a permitted file capability. Inheritable Set Capabilities preserved across an execve. Inheritable capabilities remain inheritable when executing any program, and they will be added to the permitted set when executing a program that has that capability set as inheritable file capability. Keep in mind that inheritable capabilities are not generally preserved across execve when running as a non-root user, for such uses cases consider using ambient capabilities. Effective Set Capabilities used by the kernel to perform permission checks for the thread. Bounding Set Used to limit which capabilities can be gained during execve. Ambient Set Capabilities that are preserved across an execve of a program that is not privileged. No capability can ever be ambient if it&rsquo;s not both permitted and inheritable. Executing a program that changes UID or GID due to SETUID or SETGID bits or executing a program that has file capabilities set will clear the ambient set. Ambient capabilities are added to the permitted set and assigned to the effective set when execve is called. On top of thread capabilities we have file capabilities, which are capabilities assigned to an executable file and that upon execution will be granted to the thread. These file capabilities are stored using one bit, but they act as different file capability sets:\nPermitted Set Capabilities that are automatically permitted to the thread, regardless of the thread&rsquo;s inheritable capabilities. Inheritable Capabilities that are ANDed with the thread&rsquo;s inheritable set to determine which inheritable capabilities are enabled in the permitted set of the thread after the execve. Effective This is not a capability set, but rather just a single bit. If set, during an execve all of the thread&rsquo;s permitted capabilities are also raised in the effective set. If not set, after an execve, none of the thread&rsquo;s permitted capabilities are raised in the effective set. Enabling a capability in the file effective set implies that the thread will acquire that capability in its permitted set. Capabilities and containers Before we get started with hands-on scenarios we need to know how capabilities behave in containers, specially what&rsquo;s the different behaviours we get when running a container as root or as a non-root user.\nContainers running with UID 0\nWhen we run a container with UID 0, default capabilities configured by the runtime will be configured in the effective set for the container thread.\nPodman default runtime capabilities can be found here. You can also modify the defaults using the Podman&rsquo;s configuration file.\nContainer running with nonroot UIDs\nWhen we run a container with a nonroot UID, default capabilities configured by the runtime are dropped, they will be in the inherited set and we can use file capabilities for such cases. We can also explicitly request a list of capabilities to the container runtime so those will be added to the container thread effective set.\nIn the next scenarios we will show the differences.\nGet capabilities assigned to a process During the following scenarios we will get capabilities assigned to processes, there are different ways of getting this information, let&rsquo;s see some.\nLet&rsquo;s run a test container, this container has an application that listens on a given port, but that&rsquo;s not important for now:\npodman run -d --rm --name reversewords-test quay.io\/mavazque\/reversewords:latest We can always get capabilities for a process by querying the \/proc filesystem:\n# Get container&#39;s PID CONTAINER_PID=$(podman inspect reversewords-test --format \\{\\{.State.Pid\\}\\}) # Get caps for a given PID grep Cap \/proc\/${CONTAINER_PID}\/status NOTE: The command returns the different capability sets in hex format, we will use a tool to decode that information.\nCapInh:\t00000000800405fb CapPrm:\t00000000800405fb CapEff:\t00000000800405fb CapBnd:\t00000000800405fb CapAmb:\t0000000000000000 We can see that the inherited, permitted, effective and bounding sets share the same capabilities, let&rsquo;s decode them:\ncapsh --decode=00000000800405fb NOTE: As you can see below capabilities were assigned since those are the runtime&rsquo;s defaults and our container is running with UID 0 so no capabilities were dropped.\n0x00000000800405fb=cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_sys_chroot,cap_setfcap We can use podman inspect as well:\npodman inspect reversewords-test --format \\{\\{.EffectiveCaps\\}\\} [CAP_CHOWN CAP_DAC_OVERRIDE CAP_FOWNER CAP_FSETID CAP_KILL CAP_NET_BIND_SERVICE CAP_SETFCAP CAP_SETGID CAP_SETPCAP CAP_SETUID CAP_SYS_CHROOT] We can stop the test container now:\npodman stop reversewords-test Container running with UID 0 vs container running with nonroot UID We explained the different behaviour between a container running with root&rsquo;s UID and with nonroot UID, now let&rsquo;s see it in action.\nRun our test container with a root uid and get it&rsquo;s capabilities:\n# Run the container podman run --rm -it --user 0 --entrypoint \/bin\/bash --name reversewords-test quay.io\/mavazque\/reversewords:ubi8 # Now we&#39;re inside the container, let&#39;s get caps grep Cap \/proc\/1\/status CapInh:\t00000000800405fb CapPrm:\t00000000800405fb CapEff:\t00000000800405fb CapBnd:\t00000000800405fb CapAmb:\t0000000000000000 We can decode the capabilities in the effective set:\ncapsh --decode=00000000800405fb 0x00000000800405fb=cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_sys_chroot,cap_setfcap We can exit our container now:\nexit Now it&rsquo;s time to run our test container with a nonroot uid:\n# Run the container podman run --rm -it --user 1024 --entrypoint \/bin\/bash --name reversewords-test quay.io\/mavazque\/reversewords:ubi8 # Now we&#39;re inside the container, let&#39;s get caps grep Cap \/proc\/1\/status NOTE: As you can see since we&rsquo;re running with a nonroot UID our permitted and effective set were cleared. We could still use file capabilities.\nCapInh:\t00000000800405fb CapPrm:\t0000000000000000 CapEff:\t0000000000000000 CapBnd:\t00000000800405fb CapAmb:\t0000000000000000 We can exit our container now:\nexit On top of file capabilities, we can request specific capabilities to the runtime and they will be assigned to the corresponding sets even if we are running with a nonroot uid:\n# Run the container and request the NET_BIND_SERVICE capability podman run --rm -it --user 1024 --cap-add=cap_net_bind_service --entrypoint \/bin\/bash --name reversewords-test quay.io\/mavazque\/reversewords:ubi8 # Now we&#39;re inside the container, let&#39;s get caps grep Cap \/proc\/1\/status NOTE: You can see that we got some capability in the permitted and effective set, let&rsquo;s decode it.\nCapInh:\t00000000800405fb CapPrm:\t0000000000000400 CapEff:\t0000000000000400 CapBnd:\t00000000800405fb CapAmb:\t0000000000000400 Decode the capability:\ncapsh --decode=0000000000000400 NOTE: As expected, the NET_BIND_SERVICE capability was added to the containers permitted and effective set.\n0x0000000000000400=cap_net_bind_service We can exit our container now:\nexit Real world scenario We said that the power of root comes from its capabilities and not from just being root, in the next scenario we are going to show how we can use capabilities in order to run root-like actions with nonroot users.\nWe have our test application, it runs a small web-service on a given port. We want to bind to port 80, but as you might know, binding to ports under 1024 is a privileged action. Let&rsquo;s see how capabilities can help us here.\nUsing thread capabilities\nWe can control in which port our application listens by using the APP_PORT environment variable. Let&rsquo;s try to run our application in a non-privileged port with a non-privileged user:\npodman run --rm --user 1024 -e APP_PORT=8080 --name reversewords-test quay.io\/mavazque\/reversewords:ubi8 NOTE: As you can see the application is running properly.\n2021\/03\/27 17:12:49 Starting Reverse Api v0.0.18 Release: NotSet 2021\/03\/27 17:12:49 Listening on port 8080 You can stop the container by pressing Ctrl+C\nNow, let&rsquo;s try to bind to port 80\npodman run --rm --user 1024 -e APP_PORT=80 --name reversewords-test quay.io\/mavazque\/reversewords:ubi8 NOTE: We got a permission denied, if you remember since we&rsquo;re running with a nonroot UID the capability sets were cleared.\n2021\/03\/27 17:15:56 Starting Reverse Api v0.0.18 Release: NotSet 2021\/03\/27 17:15:56 Listening on port 80 2021\/03\/27 17:15:56 listen tcp :80: bind: permission denied We know that the capability NET_BIND_SERVICE allows unprivileged processes to bind to ports under 1024, let&rsquo;s assign this capability to the container and see what happens:\npodman run --rm --user 1024 -e APP_PORT=80 --cap-add=cap_net_bind_service --name reversewords-test quay.io\/mavazque\/reversewords:ubi8 NOTE: Now the application was able to bind to port 80 even if it&rsquo;s running with a nonroot user because the capability NET_BIND_SERVICE was added to the thread&rsquo;s effective set.\n2021\/03\/27 17:18:07 Starting Reverse Api v0.0.18 Release: NotSet 2021\/03\/27 17:18:07 Listening on port 80 You can stop the container by pressing Ctrl+C\nUsing file capabilities\nFor this example we&rsquo;re using the same application, but this time we set file capabilities to our application binary using the setcap command:\nNOTE: We added the NET_BIND_SERVICE in the effective and permitted file capability set.\nsetcap &#39;cap_net_bind_service+ep&#39; \/usr\/bin\/reverse-words Let&rsquo;s see what happens when we run this new image:\npodman run --rm -it --entrypoint \/bin\/bash --user 1024 -e APP_PORT=80 --name reversewords-test quay.io\/mavazque\/reversewords-captest:latest Instead of running the application directly, we opened a shell. Let&rsquo;s review the file capabilities assigned to our binary:\ngetcap \/usr\/bin\/reverse-words NOTE: As previously mentioned, NET_BIND_SERVICE capability was added.\n\/usr\/bin\/reverse-words = cap_net_bind_service+ep Let&rsquo;s see the container thread capabilities:\ngrep Cap \/proc\/1\/status NOTE: We don&rsquo;t have the NET_BIND_SERVICE capability in the effective set, which means that we won&rsquo;t be able to bind to port 80 under normal circumstances. If we decode the inherited set we will see that the NET_BIND_SERVICE capability is present, that means that we should be able to use file capabilities to get that capability in the effective and permitted set.\nCapInh:\t00000000800405fb CapPrm:\t0000000000000000 CapEff:\t0000000000000000 CapBnd:\t00000000800405fb CapAmb:\t0000000000000000 Let&rsquo;s try to run our application:\n\/usr\/bin\/reverse-words NOTE: We were able to bind to port 80 since the file capability granted access to NET_BIND_SERVICE to our application thread.\n2021\/03\/27 17:26:51 Starting Reverse Api v0.0.18 Release: NotSet 2021\/03\/27 17:26:51 Listening on port 80 We can exit our container now:\nexit You might be thinking that file capabilities can be used to bypass the thread&rsquo;s capabilities, but that&rsquo;s not the case. Let&rsquo;s see what happens when we try to get a capability via file capabilities when the capability we want to get is not in the thread&rsquo;s inherited set:\n# We explicitly request to drop all capabilities podman run --rm -it --entrypoint \/bin\/bash --user 1024 --cap-drop=all -e APP_PORT=80 --name reversewords-test quay.io\/mavazque\/reversewords-captest:latest Let&rsquo;s see the container thread capabilities:\ngrep Cap \/proc\/1\/status NOTE: We don&rsquo;t have any capability in any capability set for the thread.\nCapInh:\t0000000000000000 CapPrm:\t0000000000000000 CapEff:\t0000000000000000 CapBnd:\t0000000000000000 CapAmb:\t0000000000000000 If we try to run our application:\nNOTE: The kernel stopped us from getting the NET_BIND_SERVICE and thus executing our app.\nbash: \/usr\/bin\/reverse-words: Operation not permitted We can exit our container now:\nexit Capability aware programs Very similar to file capabilities there are programs that are capability aware, that happens when they use specific libraries that are used for managing capabilities at a thread level.\nIn the previous example, our application raised the NET_BIND_SERVICE capability in the effective set for the whole execution time. Capability aware programs are much smarter and they only raise capabilities when they&rsquo;re required and they drop those capabilities when they&rsquo;re no longer required.\nIf our application was that smarter it would&rsquo;ve raised the NET_BIND_SERVICE before binding to port 80, and once binded it would&rsquo;ve dropped the capability since it was not required anymore.\nFor example, we can build capability aware programs in go by using a library like this.\nSecure Compute Profiles in Action In this scenario we will generate a seccomp profile for our container, in order to do that we will use the OCI Hook project.\nNOTE: The OCI Hook requires us to run containers with a privileged user, that&rsquo;s why we will be using sudo in the next commands.\nRun a container that runs ls \/ command and tell the hook to save the seccomp profile at \/tmp\/ls.json:\nsudo podman run --rm --annotation io.containers.trace-syscall=&#34;of:\/tmp\/ls.json&#34; fedora:32 ls \/ &gt; \/dev\/null The hook generated the seccomp profile at \/tmp\/ls.json, let&rsquo;s review it:\ncat \/tmp\/ls.json | jq NOTE: We can see the syscalls that were made by our container in order to run the ls \/ command.\n{ &#34;defaultAction&#34;: &#34;SCMP_ACT_ERRNO&#34;, &#34;architectures&#34;: [ &#34;SCMP_ARCH_X86_64&#34; ], &#34;syscalls&#34;: [ { &#34;names&#34;: [ &#34;access&#34;, &#34;arch_prctl&#34;, &#34;brk&#34;, &#34;capset&#34;, &#34;close&#34;, &#34;execve&#34;, &#34;exit_group&#34;, &#34;fstat&#34;, &#34;getdents64&#34;, &#34;ioctl&#34;, &#34;mmap&#34;, &#34;mprotect&#34;, &#34;munmap&#34;, &#34;openat&#34;, &#34;prctl&#34;, &#34;pread64&#34;, &#34;prlimit64&#34;, &#34;read&#34;, &#34;rt_sigaction&#34;, &#34;rt_sigprocmask&#34;, &#34;select&#34;, &#34;set_robust_list&#34;, &#34;set_tid_address&#34;, &#34;setresgid&#34;, &#34;setresuid&#34;, &#34;stat&#34;, &#34;statfs&#34;, &#34;write&#34; ], &#34;action&#34;: &#34;SCMP_ACT_ALLOW&#34;, &#34;args&#34;: [], &#34;comment&#34;: &#34;&#34;, &#34;includes&#34;: {}, &#34;excludes&#34;: {} } ] } Now that we have a seccomp profile that only has the required syscalls for our application to work, we can run the container with this profile:\npodman run --rm --security-opt seccomp=\/tmp\/ls.json fedora:32 ls \/ &gt; \/dev\/null It worked!, let&rsquo;s see what happens if we change the ls command a bit:\npodman run --rm --security-opt seccomp=\/tmp\/ls.json fedora:32 ls -l \/ &gt; \/dev\/null NOTE: The ls -l command failed because it requires additional syscalls that are not permitted by our seccomp profile.\nls: cannot access &#39;\/&#39;: Operation not permitted The hook allow us to pass an input file that will be used as baseline, then we will log the required additional syscalls into a new output file:\nsudo podman run --rm --annotation io.containers.trace-syscall=&#34;if:\/tmp\/ls.json;of:\/tmp\/lsl.json&#34; fedora:32 ls -l \/ &gt; \/dev\/null An updated seccomp profile has been generated at \/tmp\/lsl.json, let&rsquo;s compare both profiles:\ndiff &lt;(jq -S . \/tmp\/ls.json) &lt;(jq -S . \/tmp\/lsl.json) NOTE: We can see the additional syscalls required by the ls -l command below.\n42a43,61 &gt; }, &gt; { &gt; &#34;action&#34;: &#34;SCMP_ACT_ALLOW&#34;, &gt; &#34;args&#34;: [], &gt; &#34;comment&#34;: &#34;&#34;, &gt; &#34;excludes&#34;: {}, &gt; &#34;includes&#34;: {}, &gt; &#34;names&#34;: [ &gt; &#34;connect&#34;, &gt; &#34;fcntl&#34;, &gt; &#34;futex&#34;, &gt; &#34;getpid&#34;, &gt; &#34;getxattr&#34;, &gt; &#34;lgetxattr&#34;, &gt; &#34;lseek&#34;, &gt; &#34;lstat&#34;, &gt; &#34;readlink&#34;, &gt; &#34;socket&#34; &gt; ] If we try to use the new seccomp profile we will be able to run the ls -l command this time:\npodman run --rm --security-opt seccomp=\/tmp\/lsl.json fedora:32 ls -l \/ &gt; \/dev\/null Closing Thoughts In this blog post we introduced two security technologies in containers that can be used to limit the attack surface in our applications running in containers. In a future blog post we will see how these technologies can be leveraged in Kubernetes.\nSources Linux Capabilities in OpenShift Linux Man Pages ","permalink":"https:\/\/linuxera.org\/container-security-capabilities-seccomp\/","summary":"Container Security - Linux Capabilities and Secure Compute Profiles In this post we are going to see two security mechanisms used in Linux Containers in order to provide a security layer for our workloads.\nWe will see how Linux Capabilities and Secure Compute Profiles can be used for limiting the attack surface for our containers.\nThe first part of the blog post will be an introduction to Linux Capabilities and Secure Compute Profiles, second part will show how these technologies work through the use of demos.","title":"Container Security - Linux Capabilities and Secure Compute Profiles"},{"content":"Containers are Linux You probably already heard this expression, in today&rsquo;s post we are going to desmitify container technologies by decomposing them part by part and describing which Linux technologies make containers possible.\nWe can describe a container as an isolated process running on a host. In order to isolate the process the container runtimes leverage Linux kernel technologies such as: namespaces, chroots, cgroups, etc. plus security layers like SELinux.\nWe will see how we can leverage these technologies on Linux in order to build and run our own containers.\nContainer File Systems (a.k.a rootfs) Whenever you pull an image container from a container registry, you&rsquo;re downloading just a tarball. We can say container images are just tarballs.\nThere are multiple ways to get a rootfs that we can use in order to run our containers, for this blogpost we&rsquo;re going to download an already built rootfs for Alpine Linux.\nThere are tools such as buildroot that make it really easy to create our own rootfs. We will see how to create our own rootfs using buildroot on a future post.\nAs earlier mentioned, let&rsquo;s download the x86_64 rootfs for Alpine Linux:\nmkdir \/var\/tmp\/alpine-rootfs\/ &amp;&amp; cd $_ curl https:\/\/dl-cdn.alpinelinux.org\/alpine\/v3.12\/releases\/x86_64\/alpine-minirootfs-3.12.3-x86_64.tar.gz -o rootfs.tar.gz We can extract the rootfs on the temporary folder we just created:\ntar xfz rootfs.tar.gz &amp;&amp; rm -f rootfs.tar.gz If we take a look at the extracted files:\ntree -L 1 As you can see, the result looks like a Linux system. We have some well known directories in the Linux Filesystem Hierarchy Standard such as: bin, tmp, dev, opt, etc.\n. \u251c\u2500\u2500 bin \u251c\u2500\u2500 dev \u251c\u2500\u2500 etc \u251c\u2500\u2500 home \u251c\u2500\u2500 lib \u251c\u2500\u2500 media \u251c\u2500\u2500 mnt \u251c\u2500\u2500 opt \u251c\u2500\u2500 proc \u251c\u2500\u2500 root \u251c\u2500\u2500 run \u251c\u2500\u2500 sbin \u251c\u2500\u2500 srv \u251c\u2500\u2500 sys \u251c\u2500\u2500 tmp \u251c\u2500\u2500 usr \u2514\u2500\u2500 var chroot Chroot is an operation that changes the root directory for the current running process and their children. A process that runs inside a chroot cannot access files and commands outside the chrooted directory tree.\nThat being said, we can now chroot into the rootfs environment we extracted in the previous step and run a shell to poke around:\nCreate the chroot jail\nsudo chroot \/var\/tmp\/alpine-rootfs\/ \/bin\/sh Check the os-release\ncat \/etc\/os-release NAME=&#34;Alpine Linux&#34; ID=alpine VERSION_ID=3.12.3 PRETTY_NAME=&#34;Alpine Linux v3.12&#34; HOME_URL=&#34;https:\/\/alpinelinux.org\/&#34; BUG_REPORT_URL=&#34;https:\/\/bugs.alpinelinux.org\/&#34; Try to list \/tmp\/alpine-rootfs folder\nls \/var\/tmp\/alpine-rootfs ls: \/var\/tmp\/alpine-rootfs: No such file or directory As you can see we only have visibility of the contents of the rootfs we&rsquo;ve chroot into.\nWe can now install python and run a simple http server for example:\nInstall python3\napk add python3 Run a simple http server\nNOTE: When we execute the Python interpreter we&rsquo;re actually running it from \/var\/tmp\/alpine-rootfs\/usr\/bin\/python3\npython3 -m http.server If you open a new shell on your system (even if it&rsquo;s outside of the chroot) you will be able to reach the http server we just created:\ncurl http:\/\/127.0.0.1:8000 namespaces At this point we were able to work with a tarball like if it was a different system, but we&rsquo;re not isolating the processed from the host system like containers do.\nLet&rsquo;s check the level of isolation:\nIn a shell outside the chroot run a ping command:\nping 127.0.0.1 Mount the proc filesystem inside the chrooted shell\nNOTE: If you&rsquo;re still running the python http server you can kill the process\nmount -t proc proc \/proc Run a ps command inside the chroot and try to find the ping command:\nps -ef | grep &#34;ping 127.0.0.1&#34; 387870 1000 0:00 ping 127.0.0.1 388204 root 0:00 grep ping 127.0.0.1 We have visibility over the host system processes, that&rsquo;s not great. On top of that, our chroot is running as root so we can even kill the process:\npkill -f &#34;ping 127.0.0.1&#34; Now is when we introduce namespaces.\nLinux namespaces are a feature of the Linux kernel that partitions kernel resources so one process will only see a set of resources while a different process can see a different set of resources.\nThese resources may exist in multiple spaces. The list of existing namespaces are:\nNamespace Isolates Cgroup Cgroup root directory IPC System V IPC, POSIX message queues Network Network devices, stacks, prots, etc. Mount Mount points PID Process IDs Time Boot and monotonic clocks User User and Group IDs UTS Hostname and NIS domain name Creating namespaces with unshare Creating namespaces is just a single syscall (unshare). There is also a unshare command line tool that provides a nice wrapper around the syscall.\nWe are going to use the unshare command line to create namespaces manually. Below example will create a PID namespace for the chrooted shell:\nExit the chroot we have already running\nNOTE: Run below command on the chrooted shell\nexit Create the PID namespace and run the chrooted shell inside the namespace\nsudo unshare -p -f --mount-proc=\/var\/tmp\/alpine-rootfs\/proc chroot \/var\/tmp\/alpine-rootfs\/ \/bin\/sh Now that we have created our new process namespace, we will see that our shell thinks its PID is 1:\nps -ef NOTE: As you can see, we no longer see the host system processes\nPID USER TIME COMMAND 1 root 0:00 \/bin\/sh 2 root 0:00 ps -ef Since we didn&rsquo;t create a namespace for the network we can still see the whole network stack from the host system:\nip -o a NOTE: Below output might vary on your system\n1: lo inet 127.0.0.1\/8 scope host lo\\ valid_lft forever preferred_lft forever 1: lo inet6 ::1\/128 scope host \\ valid_lft forever preferred_lft forever 4: wlp82s0 inet 192.168.0.160\/24 brd 192.168.0.255 scope global dynamic wlp82s0\\ valid_lft 6555sec preferred_lft 6555sec 4: wlp82s0 inet6 fe80::4e03:6176:40f0:b862\/64 scope link \\ valid_lft forever preferred_lft forever Entering namespaces with nsenter One powerful thing about namespaces is that they&rsquo;re pretty flexible, for example you can have processes with some separated namespaces and some shared namespaces. One example in the Kubernetes world will be containers running in pods: Containers will have different PID namespaces but they will share the Network namespace.\nThere is a syscall (setns) that can be used to reassociate a thread with a namespace. The nsenter command line tool will help with that.\nWe can check the namespaces for a given process by querying the \/proc filesystem:\nFrom a shell outside the chroot get the PID for the chrooted shell\nUNSHARE_PPID=$(ps -ef | grep &#34;sudo unshare&#34; | grep chroot | awk &#39;{print $2}&#39;) UNSHARE_PID=$(ps -ef | grep ${UNSHARE_PPID} | grep chroot | grep -v sudo | awk &#39;{print $2}&#39;) SHELL_PID=$(ps -ef | grep ${UNSHARE_PID} | grep -v chroot | grep \/bin\/sh | awk &#39;{print $2}&#39;) ps -ef | grep ${UNSHARE_PID} | grep -v chroot | grep \/bin\/sh root 390072 390071 0 12:32 pts\/1 00:00:00 \/bin\/sh From a shell outside the chroot get the namespaces for the shell process:\nsudo ls -l \/proc\/${SHELL_PID}\/ns total 0 lrwxrwxrwx. 1 root root 0 mar 25 12:54 cgroup -&gt; &#39;cgroup:[4026531835]&#39; lrwxrwxrwx. 1 root root 0 mar 25 12:54 ipc -&gt; &#39;ipc:[4026531839]&#39; lrwxrwxrwx. 1 root root 0 mar 25 12:54 mnt -&gt; &#39;mnt:[4026532266]&#39; lrwxrwxrwx. 1 root root 0 mar 25 12:54 net -&gt; &#39;net:[4026532008]&#39; lrwxrwxrwx. 1 root root 0 mar 25 12:54 pid -&gt; &#39;pid:[4026532489]&#39; lrwxrwxrwx. 1 root root 0 mar 25 12:54 pid_for_children -&gt; &#39;pid:[4026532489]&#39; lrwxrwxrwx. 1 root root 0 mar 25 12:54 time -&gt; &#39;time:[4026531834]&#39; lrwxrwxrwx. 1 root root 0 mar 25 12:54 time_for_children -&gt; &#39;time:[4026531834]&#39; lrwxrwxrwx. 1 root root 0 mar 25 12:54 user -&gt; &#39;user:[4026531837]&#39; lrwxrwxrwx. 1 root root 0 mar 25 12:54 uts -&gt; &#39;uts:[4026531838]&#39; Earlier we saw how we were just setting a different PID namespace, let&rsquo;s see the difference between the PID namespace configured for our chroot shell and for the regular shell:\nNOTE: Below commands must be run from a shell outside the chroot:\nGet PID namespace for the chrooted shell:\nsudo ls -l \/proc\/${SHELL_PID}\/ns\/pid lrwxrwxrwx. 1 root root 0 mar 25 12:54 pid -&gt; pid:[4026532489] Get PID namespace for the regular shell:\nsudo ls -l \/proc\/$$\/ns\/pid lrwxrwxrwx. 1 mario mario 0 mar 25 12:55 pid -&gt; pid:[4026531836] As you can see, both processes are using a different PID namespace. We saw that network stack was still visible, let&rsquo;s see if there is any difference in the Network namespace for both processes. Let&rsquo;s start with the chrooted shell:\nsudo ls -l \/proc\/${SHELL_PID}\/ns\/net lrwxrwxrwx. 1 root root 0 mar 25 12:54 net -&gt; net:[4026532008] Now, time to get the one for the regular shell:\nsudo ls -l \/proc\/$$\/ns\/net lrwxrwxrwx. 1 mario mario 0 mar 25 12:55 net -&gt; net:[4026532008] As you can see from above outputs, both processes are using the same Network namespace.\nIf we want to join a process to an existing namespace we can do that using nsenter as we said before, let&rsquo;s do that.\nOpen a new shell outside the chroot\nWe want run a new chrooted shell and join the already existing PID namespace we created earlier:\n# Get the previous unshare PPID UNSHARE_PPID=$(ps -ef | grep &#34;sudo unshare&#34; | grep chroot | awk &#39;{print $2}&#39;) # Get the previous unshare PID UNSHARE_PID=$(ps -ef | grep ${UNSHARE_PPID} | grep chroot | grep -v sudo | awk &#39;{print $2}&#39;) # Get the previous chrooted shell PID SHELL_PID=$(ps -ef | grep ${UNSHARE_PID} | grep -v chroot | grep \/bin\/sh | awk &#39;{print $2}&#39;) # We will enter the previous PID namespace, remount the \/proc filesystem and run a new chrooted shell sudo nsenter --pid=\/proc\/${SHELL_PID}\/ns\/pid unshare -f --mount-proc=\/tmp\/alpine-rootfs\/proc chroot \/tmp\/alpine-rootfs\/ \/bin\/sh From the new chrooted shell we can run a ps command and we should see the existing processes from the previous chrooted shell:\nps -ef PID USER TIME COMMAND 1 root 0:00 \/bin\/sh 4 root 0:00 unshare -f --mount-proc=\/tmp\/alpine-rootfs\/proc chroot \/tmp\/alpine-rootfs\/ \/bin\/sh 5 root 0:00 \/bin\/sh 6 root 0:00 ps -ef We have entered the already existing PID namespace used by our previous chrooted shell and we can see that running a ps command from the new shell (PID 5) we can see the first shell (PID 1).\nInjecting files or directories into the chroot Containers are usually inmutables, that means that we cannot create or edit directories or files into the chroot. Sometimes we will need to inject files or directories either for storage or configuration. We are going to show how we can create some files on the host system and expose them as read-only to the chrooted shell using mount.\nCreate a folder in the host system to host some read-only config files:\nsudo mkdir -p \/var\/tmp\/alpine-container-configs\/ echo &#34;Test&#34; | sudo tee -a \/var\/tmp\/alpine-container-configs\/app-config echo &#34;Test2&#34; | sudo tee -a \/var\/tmp\/alpine-container-configs\/srv-config Create a folder in the rootfs directory to use it as mount point:\nsudo mkdir -p \/var\/tmp\/alpine-rootfs\/etc\/myconfigs Run a bind mount:\nsudo mount --bind -o ro \/var\/tmp\/alpine-container-configs \/var\/tmp\/alpine-rootfs\/etc\/myconfigs Run a chrooted shell and check the mounted files:\nNOTE: You can exit from the already existing chrooted shells before creating this one\nsudo unshare -p -f --mount-proc=\/var\/tmp\/alpine-rootfs\/proc chroot \/var\/tmp\/alpine-rootfs\/ \/bin\/sh ls -l \/etc\/myconfigs\/ total 8 -rw-r--r-- 1 root root 5 Mar 25 13:28 app-config -rw-r--r-- 1 root root 6 Mar 25 13:28 srv-config If we try to edit the files from the chrooted shell, this is what happens:\necho &#34;test3&#34; &gt;&gt; \/etc\/myconfigs\/app-config NOTE: We cannot edit\/create files since the mount is read-only\n\/bin\/sh: can&#39;t create \/etc\/myconfigs\/app-config: Read-only file system If we want to unmount the files we can run the command below from the host system:\nsudo umount \/var\/tmp\/alpine-rootfs\/etc\/myconfigs CGroups Control groups allow the kernel to restrict resources like memory and CPU for specific processes. In this case we are going to create a new CGroup for our chrooted shell so it cannot use more than 200MB of RAM.\nKernel exposes cgroups at the \/sys\/fs\/cgroup directory:\nls \/sys\/fs\/cgroup\/ cgroup.controllers cgroup.stat cpuset.cpus.effective io.cost.model machine.slice system.slice cgroup.max.depth cgroup.subtree_control cpuset.mems.effective io.cost.qos memory.numa_stat user.slice cgroup.max.descendants cgroup.threads cpu.stat io.pressure memory.pressure cgroup.procs cpu.pressure init.scope io.stat memory.stat Let&rsquo;s create a new cgroup, we just need to create a folder for that to happen:\nsudo mkdir \/sys\/fs\/cgroup\/alpinecgroup ls \/sys\/fs\/cgroup\/alpinecgroup\/ NOTE: The kernel automatically populated the folder\ncgroup.controllers cgroup.stat io.pressure memory.max memory.swap.current pids.max cgroup.events cgroup.subtree_control memory.current memory.min memory.swap.events cgroup.freeze cgroup.threads memory.events memory.numa_stat memory.swap.high cgroup.max.depth cgroup.type memory.events.local memory.oom.group memory.swap.max cgroup.max.descendants cpu.pressure memory.high memory.pressure pids.current cgroup.procs cpu.stat memory.low memory.stat pids.events Now, we just need to adjust the memory value by modifying the required files:\n# Set a limit of 200MB of RAM echo &#34;200000000&#34; | sudo tee -a \/sys\/fs\/cgroup\/alpinecgroup\/memory.max # Disable swap echo &#34;0&#34; | sudo tee -a \/sys\/fs\/cgroup\/alpinecgroup\/memory.swap.max Finally, we need to assign this CGroup to our chrooted shell:\n# Get the previous unshare PPID UNSHARE_PPID=$(ps -ef | grep &#34;sudo unshare&#34; | grep chroot | awk &#39;{print $2}&#39;) # Get the previous unshare PID UNSHARE_PID=$(ps -ef | grep ${UNSHARE_PPID} | grep chroot | grep -v sudo | awk &#39;{print $2}&#39;) # Get the previous chrooted shell PID SHELL_PID=$(ps -ef | grep ${UNSHARE_PID} | grep -v chroot | grep \/bin\/sh | awk &#39;{print $2}&#39;) # Assign the shell process to the cgroup echo ${SHELL_PID} | sudo tee -a \/sys\/fs\/cgroup\/alpinecgroup\/cgroup.procs In order to test the cgroup we will create a dumb python script in the chrooted shell:\n# Mount the \/dev fs since we need to read data from urandom mount -t devtmpfs dev \/dev # Create the python script cat &lt;&lt;EOF &gt; \/opt\/dumb.py f = open(&#34;\/dev\/urandom&#34;, &#34;r&#34;, encoding = &#34;ISO-8859-1&#34;) data = &#34;&#34; i=0 while i &lt; 20: data += f.read(10000000) # 10mb i += 1 print(&#34;Used %d MB&#34; % (i * 10)) EOF Run the script:\npython3 \/opt\/dumb.py NOTE: The process was killed before it reached the memory limit.\npython3 \/opt\/dumb.py Used 10 MB Used 20 MB Used 30 MB Used 40 MB Used 50 MB Used 60 MB Used 70 MB Used 80 MB Used 90 MB Used 100 MB Used 110 MB Used 120 MB Used 130 MB Used 140 MB Used 150 MB Used 160 MB Used 170 MB Killed We can now close the chrooted shell and remove the cgroup\nExit the chrooted shell:\nexit NOTE: A CGroup cannot be removed until all the attached processes are finished.\nRemove the cgroup:\nsudo rmdir \/sys\/fs\/cgroup\/alpinecgroup\/ Container security and capabilities As you know, Linux containers run directly on top of the host system and share multiple resources like the Kernel, filesystems, network stack, etc. If an attacker breaks out of the container confinement security risks will arise.\nIn order to limit the attack surface there are many technologies involved in limiting the power of processes running in the container such as SELinux, Security Compute Profiles and Linux Capabilities.\nYou can learn more in this blogpost.\nClosing Thoughts Containers are not new, they use technologies that have been present in the Linux kernel for a long time. Tools like Podman or Docker make running containers easy for everyone by abstracting the different Linux technologies used under the hood from the user.\nI hope that now you have a better understanding of what technologies are used when you run containers on your systems.\nSources Containers from from Scratch Creating CGroupsv2 ","permalink":"https:\/\/linuxera.org\/containers-under-the-hood\/","summary":"Containers are Linux You probably already heard this expression, in today&rsquo;s post we are going to desmitify container technologies by decomposing them part by part and describing which Linux technologies make containers possible.\nWe can describe a container as an isolated process running on a host. In order to isolate the process the container runtimes leverage Linux kernel technologies such as: namespaces, chroots, cgroups, etc. plus security layers like SELinux.","title":"Containers under the Hood"},{"content":"Introduction This post is a continuation of our previous blog Writing Operators using the Operator Framework SDK.\nWe will continue working on the operator created on the previous blog, if you want to be able to follow this blog, you will need to run the steps from the previous blog.\nOperator Lifecycle Manager The Operator Lifecycle Manager is an open source toolkit to manage Operators in an effective, automated and scalable way. You can learn more here.\nDuring this post we will integrate our Reverse Words Operator into OLM, that way we will be able to use OLM to manager our Operator lifecycle.\nIntegrating Reverse Words Operator into OLM Deploy OLM Some Kubernetes distributions, like OpenShift come with OLM pre-installed, if you&rsquo;re using a distribution with doesn&rsquo;t come with OLM or you don&rsquo;t know if your Kubernetes cluster is running OLM already you can use the operator-sdk command to find out.\noperator-sdk olm status If your cluster is not running olm and you want to deploy it, you can run the following command:\noperator-sdk olm install Once we know OLM is present in our cluster we can continue and start the creation of our Operator Bundle.\nOperator Bundle An Operator Bundle consists of different manifests (CSVs and CRDs) and some metadata that defines the Operator at a specific version.\nYou can read more about Bundles here.\nRequirements At the moment of this writing the following versions were used:\ngolang-1.19.5 Operator Framework SDK v1.26.1 Kubernetes 1.24 opm v1.26.3 Creating the Operator Bundle We need to change to the Reverse Words Operator folder and run the make bundle command. We will be asked for some information.\ncd ~\/operators-projects\/reverse-words-operator\/ QUAY_USERNAME=&lt;username&gt; make bundle VERSION=0.0.1 CHANNELS=alpha DEFAULT_CHANNEL=alpha IMG=quay.io\/$QUAY_USERNAME\/reversewords-operator:v0.0.1 NOTE: Example output\nDisplay name for the operator (required): &gt; Reverse Words Operator Description for the operator (required): &gt; Deploys and Manages instances of the Reverse Words Application Provider&#39;s name for the operator (required): &gt; Linuxera Any relevant URL for the provider name (optional): &gt; linuxera.org Comma-separated list of keywords for your operator (required): &gt; reverse,reversewords,linuxera Comma-separated list of maintainers and their emails (e.g. &#39;name1:email1, name2:email2&#39;) (required): &gt; mario@linuxera.org &lt;omitted_output&gt; Above command has generated some files:\nbundle \u251c\u2500\u2500 manifests \u2502\u00a0\u251c\u2500\u2500 apps.linuxera.org_reversewordsapps.yaml \u2502\u00a0\u251c\u2500\u2500 reverse-words-operator.clusterserviceversion.yaml \u2502\u00a0\u251c\u2500\u2500 reverse-words-operator-controller-manager-metrics-service_v1_service.yaml \u2502\u00a0\u251c\u2500\u2500 reverse-words-operator-manager-config_v1_configmap.yaml \u2502\u00a0\u2514\u2500\u2500 reverse-words-operator-metrics-reader_rbac.authorization.k8s.io_v1beta1_clusterrole.yaml \u251c\u2500\u2500 metadata \u2502\u00a0\u2514\u2500\u2500 annotations.yaml \u2514\u2500\u2500 tests \u2514\u2500\u2500 scorecard \u2514\u2500\u2500 config.yaml We need to tweak the ClusterServiceVersion a bit:\nConfigure proper installModes Add WATCH_NAMESPACE env var to the operator deployment Add an Icon to our Operator You can download the modified CSV here:\ncurl -Ls https:\/\/linuxera.org\/integrating-operators-olm\/reverse-words-operator.clusterserviceversion_v0.0.1.yaml -o ~\/operators-projects\/reverse-words-operator\/bundle\/manifests\/reverse-words-operator.clusterserviceversion.yaml sed -i &#34;s\/QUAY_USER\/$QUAY_USERNAME\/g&#34; ~\/operators-projects\/reverse-words-operator\/bundle\/manifests\/reverse-words-operator.clusterserviceversion.yaml Now that we have the Operator Bundle ready we can build it and push it to Quay. After that we will build the catalog image and once the catalog image is ready, we will use it to deploy our operator.\nNOTE: If you use podman instead of docker you can edit the Makefile and change docker commands by podman commands\nBuild and Push the bundle\nmake bundle-build bundle-push BUNDLE_IMG=quay.io\/$QUAY_USERNAME\/reversewords-operator-bundle:v0.0.1 Validate the bundle\noperator-sdk bundle validate quay.io\/$QUAY_USERNAME\/reversewords-operator-bundle:v0.0.1 -b podman Create the Catalog Image\nNote\nWith this new file-based approach, it&rsquo;s highly recommended to keep control of your catalog in Git. The operator framework team created an example repo you can fork here.\n# Download opm tool sudo curl -sL https:\/\/github.com\/operator-framework\/operator-registry\/releases\/download\/v1.26.3\/linux-amd64-opm -o \/usr\/local\/bin\/opm &amp;&amp; sudo chmod +x \/usr\/local\/bin\/opm # Create the catalog image mkdir reversewords-catalog opm generate dockerfile reversewords-catalog opm init reverse-words-operator --default-channel=alpha --output yaml &gt; reversewords-catalog\/operator.yaml # Add bundle opm render quay.io\/$QUAY_USERNAME\/reversewords-operator-bundle:v0.0.1 --output yaml &gt;&gt; reversewords-catalog\/operator.yaml # Initialize the alpha channel cat &lt;&lt; EOF &gt;&gt; reversewords-catalog\/operator.yaml --- schema: olm.channel package: reverse-words-operator name: alpha entries: - name: reverse-words-operator.v0.0.1 EOF # Validate the catalog opm validate reversewords-catalog &amp;&amp; echo &#34;OK&#34; Building and pushing the catalog image\npodman build . -f reversewords-catalog.Dockerfile -t quay.io\/$QUAY_USERNAME\/reversewords-catalog:latest podman push quay.io\/$QUAY_USERNAME\/reversewords-catalog:latest Deploy the Operator using OLM At this point we have our bundle and catalog images ready, we just need to create the required CatalogSource into the cluster so we get access to our Operator bundle.\nOLM_NAMESPACE=$(kubectl get pods -A | grep catalog-operator | awk &#39;{print $1}&#39;) cat &lt;&lt;EOF | kubectl create -f - apiVersion: operators.coreos.com\/v1alpha1 kind: CatalogSource metadata: name: reversewords-catalog namespace: $OLM_NAMESPACE spec: sourceType: grpc displayName: &#34;ReverseWords Catalog&#34; publisher: Linuxera image: quay.io\/$QUAY_USERNAME\/reversewords-catalog:latest updateStrategy: registryPoll: interval: 1m0s EOF A pod will be created on the OLM namespace:\nkubectl -n $OLM_NAMESPACE get pod -l olm.catalogSource=reversewords-catalog NAME READY STATUS RESTARTS AGE reversewords-catalog-d8qbw 1\/1 Running 0 12s OLM will read the CSVs from our Operator Bundle and will load the Package Manifest into the cluster:\nkubectl get packagemanifest -l catalog=reversewords-catalog NAME CATALOG AGE reverse-words-operator ReverseWords Catalog 30s At this point we can create a Subscription to our operator:\nCreate a new namespace\nNAMESPACE=test-operator-subscription kubectl create ns $NAMESPACE Create the subscription in the namespace we just created\ncat &lt;&lt;EOF | kubectl -n $NAMESPACE create -f - apiVersion: operators.coreos.com\/v1alpha1 kind: Subscription metadata: name: reversewords-subscription spec: channel: alpha name: reverse-words-operator installPlanApproval: Automatic source: reversewords-catalog sourceNamespace: $OLM_NAMESPACE --- apiVersion: operators.coreos.com\/v1 kind: OperatorGroup metadata: name: reverse-words-operatorgroup spec: targetNamespaces: - $NAMESPACE EOF The operator will be deployed in the namespace\nkubectl -n $NAMESPACE get pods NAME READY STATUS RESTARTS AGE reverse-words-operator-controller-manager-844d897db4-hsnmw 2\/2 Running 0 12s Publish an upgrade for our Operator We have seen how to create a bundle for our operator, now we are going to see how we can add new versions to the bundle and link them so we can publish updates for the operators.\nIn the previous steps we create the version v0.0.1 for our Operator, we are going to create and publish a v0.0.2 version:\nFirst we create a new CSV version in the same channel we used for v0.0.1:\nmake bundle VERSION=0.0.2 CHANNELS=alpha DEFAULT_CHANNEL=alpha IMG=quay.io\/$QUAY_USERNAME\/reversewords-operator:v0.0.2 We need to tweak the ClusterServiceVersion a bit:\nConfigure proper installModes Add WATCH_NAMESPACE env var to the operator deployment Add an Icon to our Operator You can download the modified CSV here:\ncurl -Ls https:\/\/linuxera.org\/integrating-operators-olm\/reverse-words-operator.clusterserviceversion_v0.0.2.yaml -o ~\/operators-projects\/reverse-words-operator\/bundle\/manifests\/reverse-words-operator.clusterserviceversion.yaml sed -i &#34;s\/QUAY_USER\/$QUAY_USERNAME\/g&#34; ~\/operators-projects\/reverse-words-operator\/bundle\/manifests\/reverse-words-operator.clusterserviceversion.yaml Now that we have the new Operator Bundle ready we can build it and push it to Quay. After that we will update and build the catalog image.\nBuild and push the new bundle\nmake bundle-build bundle-push BUNDLE_IMG=quay.io\/$QUAY_USERNAME\/reversewords-operator-bundle:v0.0.2 Validate the new bundle\noperator-sdk bundle validate quay.io\/$QUAY_USERNAME\/reversewords-operator-bundle:v0.0.2 -b podman Update the Catalog Image\n# Add bundle opm render quay.io\/$QUAY_USERNAME\/reversewords-operator-bundle:v0.0.2 --output yaml &gt;&gt; reversewords-catalog\/operator.yaml # Update the alpha channel: Edit file reversewords-catalog\/operator.yaml and change entries: - name: reverse-words-operator.v0.0.1 - name: reverse-words-operator.v0.0.2 replaces: reverse-words-operator.v0.0.1 # Validate the catalog opm validate reversewords-catalog &amp;&amp; echo &#34;OK&#34; Build and push the catalog image\npodman build . -f reversewords-catalog.Dockerfile -t quay.io\/$QUAY_USERNAME\/reversewords-catalog:latest podman push quay.io\/$QUAY_USERNAME\/reversewords-catalog:latest OLM is continuously checking for new bundles in the Catalog Images based on the updateStrategy we configured in our CatalogSource. After a few moments, the new CSV v0.0.2 should be available.\nUpdating to a new Operator version Depending on the installPlanApproval you selected when you created the subscription the operator will be updated automatically when a new version is published or you may need to approve the installPlan so the operator gets updated.\nSources OLM Generation Docs Operator Registry Docs Operator SDK OLM Integration Bundle Quickstart Operator SDK Generating Manifests and Metadata ","permalink":"https:\/\/linuxera.org\/integrating-operators-olm\/","summary":"Introduction This post is a continuation of our previous blog Writing Operators using the Operator Framework SDK.\nWe will continue working on the operator created on the previous blog, if you want to be able to follow this blog, you will need to run the steps from the previous blog.\nOperator Lifecycle Manager The Operator Lifecycle Manager is an open source toolkit to manage Operators in an effective, automated and scalable way.","title":"Integrating our Operators with OLM"},{"content":"Instrumenting your Applications We usually see systems being monitored by Ops teams, in fact, there are lots of valuable metrics that help Ops teams understand how the infrastructure they are managing is doing, but when it comes to applications monitoring, we don&rsquo;t see those being monitored that carefully most of the time. Sometimes that ends up in application crashes that might be prevented with a proper monitoring strategy.\nIn this blog post we are going to see how we can instrument our applications using Prometheus metrics libraries. Prometheus metrics libraries are widely adopted, the Prometheus metrics format has become an independent project, OpenMetrics. OpenMetrics is trying to take Prometheus Metrics Format to the next level making it an industry standard.\nCustom Metrics Example In this example we are going to use our Simple Go Application as a reference.\nOur example application is capable of:\nReverses a word sent via POST on \/ endpoint Returns a release version set via an env var on \/ endpoint Returns the hostname of the machine where it&rsquo;s running on \/hostname endpoint Returns the app status on \/health endpoint We are going to add the following metrics to our application:\nTotal number of words that have been reversed by our application Total number of times that a given endpoint has been accessed NOTE: This is an example application with example metrics, you should think carefully of which metrics do you want to include in your production applications.\nPrometheus Client The Prometheus Client is available for multiple programming languages, for today&rsquo;s blog post we will be using the Go Client.\nThe Prometheus Client provides some metrics enabled by default, among those metrics we can find metrics related to memory consumption, cpu consumption, etc.\nEnable Prometheus Metrics Endpoint NOTE: Make sure you&rsquo;re following metrics name best practices when defining your metrics.\nFirst, we need to import some required modules:\n&#34;github.com\/prometheus\/client_golang\/prometheus&#34; &#34;github.com\/prometheus\/client_golang\/prometheus\/promhttp&#34; Define reversewords_reversed_words_total metric. This metric is a simple counter metric.\nvar ( totalWordsReversed = prometheus.NewCounter( prometheus.CounterOpts{ Name: &#34;reversewords_reversed_words_total&#34;, Help: &#34;Total number of reversed words&#34;, }, ) ) Define reversewords_endpoints_accessed_total metric. This metric is a vector counter metric.\nvar ( endpointsAccessed = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: &#34;reversewords_endpoints_accessed_total&#34;, Help: &#34;Total number of accessed to a given endpoint&#34;, }, []string{&#34;accessed_endpoint&#34;}, ) ) Our application has 4 different endpoints as we already seen before, these are the endpoints:\nrouter.HandleFunc(&#34;\/&#34;, ReverseWord).Methods(&#34;POST&#34;) router.HandleFunc(&#34;\/&#34;, ReturnRelease).Methods(&#34;GET&#34;) router.HandleFunc(&#34;\/hostname&#34;, ReturnHostname).Methods(&#34;GET&#34;) router.HandleFunc(&#34;\/health&#34;, ReturnHealth).Methods(&#34;GET&#34;) The reversewords_reversed_words_total metric will be increased every time the function ReverseWord is called:\nfunc ReverseWord(w http.ResponseWriter, r *http.Request) { &lt;OUTPUT_OMITTED&gt; totalWordsReversed.Inc() &lt;OUTPUT_OMITTED&gt; } The reversewords_endpoints_accessed_total metric will be increased every time the functions ReverseWord, ReturnRelease, ReturnHostname or ReturnHealth are called:\nfunc ReturnRelease(w http.ResponseWriter, r *http.Request) { &lt;OUTPUT_OMITTED&gt; endpointsAccessed.WithLabelValues(&#34;release&#34;).Inc() } func ReturnHostname(w http.ResponseWriter, r *http.Request) { &lt;OUTPUT_OMITTED&gt; endpointsAccessed.WithLabelValues(&#34;hostname&#34;).Inc() } func ReturnHealth(w http.ResponseWriter, r *http.Request) { &lt;OUTPUT_OMITTED&gt; endpointsAccessed.WithLabelValues(&#34;health&#34;).Inc() } func ReverseWord(w http.ResponseWriter, r *http.Request) { &lt;OUTPUT_OMITTED&gt; endpointsAccessed.WithLabelValues(&#34;reverseword&#34;).Inc() } Finally, we need to add the \/metrics endpoint to our application:\nrouter.Handle(&#34;\/metrics&#34;, promhttp.Handler()).Methods(&#34;GET&#34;) Gathering Metrics With our application running we can send a GET request to the \/metrics endpoints to get the metrics:\n$ curl http:\/\/127.0.0.1:8080\/metrics # HELP go_gc_duration_seconds A summary of the GC invocation durations. # TYPE go_gc_duration_seconds summary go_gc_duration_seconds{quantile=&#34;0&#34;} 0 go_gc_duration_seconds{quantile=&#34;0.25&#34;} 0 go_gc_duration_seconds{quantile=&#34;0.5&#34;} 0 go_gc_duration_seconds{quantile=&#34;0.75&#34;} 0 go_gc_duration_seconds{quantile=&#34;1&#34;} 0 go_gc_duration_seconds_sum 0 go_gc_duration_seconds_count 0 # HELP go_goroutines Number of goroutines that currently exist. # TYPE go_goroutines gauge go_goroutines 8 # HELP go_info Information about the Go environment. # TYPE go_info gauge go_info{version=&#34;go1.12.6&#34;} 1 # HELP go_memstats_alloc_bytes Number of bytes allocated and still in use. # TYPE go_memstats_alloc_bytes gauge go_memstats_alloc_bytes 457776 # HELP go_memstats_alloc_bytes_total Total number of bytes allocated, even if freed. # TYPE go_memstats_alloc_bytes_total counter go_memstats_alloc_bytes_total 457776 # HELP go_memstats_buck_hash_sys_bytes Number of bytes used by the profiling bucket hash table. # TYPE go_memstats_buck_hash_sys_bytes gauge go_memstats_buck_hash_sys_bytes 2684 # HELP go_memstats_frees_total Total number of frees. # TYPE go_memstats_frees_total counter go_memstats_frees_total 172 # HELP go_memstats_gc_cpu_fraction The fraction of this program&#39;s available CPU time used by the GC since the program started. # TYPE go_memstats_gc_cpu_fraction gauge go_memstats_gc_cpu_fraction 0 # HELP go_memstats_gc_sys_bytes Number of bytes used for garbage collection system metadata. # TYPE go_memstats_gc_sys_bytes gauge go_memstats_gc_sys_bytes 2.240512e+06 # HELP go_memstats_heap_alloc_bytes Number of heap bytes allocated and still in use. # TYPE go_memstats_heap_alloc_bytes gauge go_memstats_heap_alloc_bytes 457776 # HELP go_memstats_heap_idle_bytes Number of heap bytes waiting to be used. # TYPE go_memstats_heap_idle_bytes gauge go_memstats_heap_idle_bytes 6.5347584e+07 # HELP go_memstats_heap_inuse_bytes Number of heap bytes that are in use. # TYPE go_memstats_heap_inuse_bytes gauge go_memstats_heap_inuse_bytes 1.368064e+06 # HELP go_memstats_heap_objects Number of allocated objects. # TYPE go_memstats_heap_objects gauge go_memstats_heap_objects 2079 # HELP go_memstats_heap_released_bytes Number of heap bytes released to OS. # TYPE go_memstats_heap_released_bytes gauge go_memstats_heap_released_bytes 0 # HELP go_memstats_heap_sys_bytes Number of heap bytes obtained from system. # TYPE go_memstats_heap_sys_bytes gauge go_memstats_heap_sys_bytes 6.6715648e+07 # HELP go_memstats_last_gc_time_seconds Number of seconds since 1970 of last garbage collection. # TYPE go_memstats_last_gc_time_seconds gauge go_memstats_last_gc_time_seconds 0 # HELP go_memstats_lookups_total Total number of pointer lookups. # TYPE go_memstats_lookups_total counter go_memstats_lookups_total 0 # HELP go_memstats_mallocs_total Total number of mallocs. # TYPE go_memstats_mallocs_total counter go_memstats_mallocs_total 2251 # HELP go_memstats_mcache_inuse_bytes Number of bytes in use by mcache structures. # TYPE go_memstats_mcache_inuse_bytes gauge go_memstats_mcache_inuse_bytes 6944 # HELP go_memstats_mcache_sys_bytes Number of bytes used for mcache structures obtained from system. # TYPE go_memstats_mcache_sys_bytes gauge go_memstats_mcache_sys_bytes 16384 # HELP go_memstats_mspan_inuse_bytes Number of bytes in use by mspan structures. # TYPE go_memstats_mspan_inuse_bytes gauge go_memstats_mspan_inuse_bytes 19440 # HELP go_memstats_mspan_sys_bytes Number of bytes used for mspan structures obtained from system. # TYPE go_memstats_mspan_sys_bytes gauge go_memstats_mspan_sys_bytes 32768 # HELP go_memstats_next_gc_bytes Number of heap bytes when next garbage collection will take place. # TYPE go_memstats_next_gc_bytes gauge go_memstats_next_gc_bytes 4.473924e+06 # HELP go_memstats_other_sys_bytes Number of bytes used for other system allocations. # TYPE go_memstats_other_sys_bytes gauge go_memstats_other_sys_bytes 527748 # HELP go_memstats_stack_inuse_bytes Number of bytes in use by the stack allocator. # TYPE go_memstats_stack_inuse_bytes gauge go_memstats_stack_inuse_bytes 393216 # HELP go_memstats_stack_sys_bytes Number of bytes obtained from system for stack allocator. # TYPE go_memstats_stack_sys_bytes gauge go_memstats_stack_sys_bytes 393216 # HELP go_memstats_sys_bytes Number of bytes obtained from system. # TYPE go_memstats_sys_bytes gauge go_memstats_sys_bytes 6.992896e+07 # HELP go_threads Number of OS threads created. # TYPE go_threads gauge go_threads 8 # HELP process_cpu_seconds_total Total user and system CPU time spent in seconds. # TYPE process_cpu_seconds_total counter process_cpu_seconds_total 0 # HELP process_max_fds Maximum number of open file descriptors. # TYPE process_max_fds gauge process_max_fds 1024 # HELP process_open_fds Number of open file descriptors. # TYPE process_open_fds gauge process_open_fds 7 # HELP process_resident_memory_bytes Resident memory size in bytes. # TYPE process_resident_memory_bytes gauge process_resident_memory_bytes 7.548928e+06 # HELP process_start_time_seconds Start time of the process since unix epoch in seconds. # TYPE process_start_time_seconds gauge process_start_time_seconds 1.56553026534e+09 # HELP process_virtual_memory_bytes Virtual memory size in bytes. # TYPE process_virtual_memory_bytes gauge process_virtual_memory_bytes 5.00559872e+08 # HELP process_virtual_memory_max_bytes Maximum amount of virtual memory available in bytes. # TYPE process_virtual_memory_max_bytes gauge process_virtual_memory_max_bytes -1 # HELP promhttp_metric_handler_requests_in_flight Current number of scrapes being served. # TYPE promhttp_metric_handler_requests_in_flight gauge promhttp_metric_handler_requests_in_flight 1 # HELP promhttp_metric_handler_requests_total Total number of scrapes by HTTP status code. # TYPE promhttp_metric_handler_requests_total counter promhttp_metric_handler_requests_total{code=&#34;200&#34;} 0 promhttp_metric_handler_requests_total{code=&#34;500&#34;} 0 promhttp_metric_handler_requests_total{code=&#34;503&#34;} 0 # HELP reversewords_reversed_words_total Total number of reversed words # TYPE reversewords_reversed_words_total counter reversewords_reversed_words_total 0 Now, let&rsquo;s see how our metrics increase as we use our application:\n$ curl -s http:\/\/127.0.0.1:8080\/ -X POST -d &#39;{&#34;word&#34;:&#34;PALC&#34;}&#39; {&#34;reverse_word&#34;:&#34;CLAP&#34;} $ curl -s http:\/\/127.0.0.1:8080\/health Healthy $ curl -s http:\/\/127.0.0.1:8080\/hostname Hostname: reverse-words-22j33j $ curl -s http:\/\/127.0.0.1:8080\/metrics | grep &#34;reversewords_&#34; # HELP reversewords_endpoints_accessed_total Total number of accessed to a given endpoint # TYPE reversewords_endpoints_accessed_total counter reversewords_endpoints_accessed_total{accessed_endpoint=&#34;health&#34;} 1 reversewords_endpoints_accessed_total{accessed_endpoint=&#34;hostname&#34;} 1 reversewords_endpoints_accessed_total{accessed_endpoint=&#34;reverseword&#34;} 1 # HELP reversewords_reversed_words_total Total number of reversed words # TYPE reversewords_reversed_words_total counter reversewords_reversed_words_total 1 As you can see the reversewords_reversed_words_total has increased by 1 and the reversewords_endpoints_accessed_total metrics now show the total number of times a given endpoint has been accessed.\nNext Steps In a future blog post we are going to show how we can configure Prometheus to scrape our metrics endpoint and how Grafana can help us to create graphs that can be consumed by monitoring teams.\nUseful Resources If you want to learn more, feel free to take a look at the resources below.\nhttps:\/\/sysdig.com\/blog\/prometheus-metrics\/ https:\/\/prometheus.io\/docs\/guides\/go-application\/ ","permalink":"https:\/\/linuxera.org\/prometheus-metrics-on-your-applications\/","summary":"Instrumenting your Applications We usually see systems being monitored by Ops teams, in fact, there are lots of valuable metrics that help Ops teams understand how the infrastructure they are managing is doing, but when it comes to applications monitoring, we don&rsquo;t see those being monitored that carefully most of the time. Sometimes that ends up in application crashes that might be prevented with a proper monitoring strategy.\nIn this blog post we are going to see how we can instrument our applications using Prometheus metrics libraries.","title":"Enabling Prometheus Metrics on your Applications"},{"content":"What is OAuth Proxy A reverse proxy and static file server that provides authentication and authorization to an OpenShift OAuth server or Kubernetes master supporting the 1.6+ remote authorization endpoints to validate access to content. It is intended for use withing OpenShift clusters to make it easy to run both end-user and infrastructure services that do not provider their own authentication.\n[Source]\nSecuring an Application with OAuth Proxy In this blog post we are going to deploy OAuth Proxy in front of a simple application.\nWe will go through the following scenarios:\nApplication deployed without OAuth Proxy Application + OAuth Proxy limiting access to authenticated users Application + OAuth Proxy limiting access to specific users Application + OAuth Proxy limiting access to specific service accounts TLS application + OAuth Proxy limiting access to authenticated users After following these three scenarios you will be able to secure applications on OpenShift and Kubernetes using the OAuth Proxy.\nScenario 1 - Deploying the Application without OAuth Proxy Not a big deal, just a regular deployment.\nRequired files deployment.yaml\napiVersion: apps\/v1 kind: Deployment metadata: name: reverse-words labels: name: reverse-words spec: replicas: 1 selector: matchLabels: name: reverse-words template: metadata: labels: name: reverse-words spec: containers: - name: reverse-words image: quay.io\/mavazque\/reversewords:latest imagePullPolicy: Always ports: - name: reverse-words containerPort: 8080 protocol: TCP service.yaml\napiVersion: v1 kind: Service metadata: labels: name: reverse-words name: reverse-words spec: ports: - name: app port: 8080 protocol: TCP targetPort: reverse-words selector: name: reverse-words sessionAffinity: None type: ClusterIP Deploy oc create namespace reverse-words oc -n reverse-words create -f deployment.yaml oc -n reverse-words create -f service.yaml oc -n reverse-words create route edge reverse-words --service=reverse-words --port=app --insecure-policy=Redirect Now we should be able to reach our application without providing any authentication details.\ncurl -k https:\/\/$(oc -n reverse-words get route reverse-words -o jsonpath=&#39;{.status.ingress[*].host}&#39;) -X POST -d &#39;{&#34;word&#34;: &#34;PALC&#34;}&#39; {&#34;reverse_word&#34;:&#34;CLAP&#34;} Let&rsquo;s go ahead and secure our application to be accessible only to authenticated users.\nScenario 2 - Limiting Access to Authenticated Users In order to use OAuth Proxy we need a couple of things:\nCreate a session Secret used by OAuth Proxy to encrypt the login cookie A ServiceAccount used by our application and annotated to redirect traffic to a given route to the OAuth Proxy TLS Certificates for be used by the proxy (We will leverage OpenShift TLS service serving certificate) Modify our Deployment to include OAuth Proxy container Modify our Service to include OAuth Proxy port and annotation for certificate creation Prerequisites Create the Secret\noc -n reverse-words create secret generic reversewords-proxy --from-literal=session_secret=$(head \/dev\/urandom | tr -dc A-Za-z0-9 | head -c43) Create and annotate the ServiceAccount\noc -n reverse-words create serviceaccount reversewords oc -n reverse-words annotate serviceaccount reversewords serviceaccounts.openshift.io\/oauth-redirectreference.reversewords=&#39;{&#34;kind&#34;:&#34;OAuthRedirectReference&#34;,&#34;apiVersion&#34;:&#34;v1&#34;,&#34;reference&#34;:{&#34;kind&#34;:&#34;Route&#34;,&#34;name&#34;:&#34;reverse-words-authenticated&#34;}}&#39; Modify the deployment\nNOTE: Below deployment points to the quay.io\/openshift\/origin-oauth-proxy:4.17 image, make sure to use the one matching your cluster version. You can find the available tags here.\ndeployment.yaml\napiVersion: apps\/v1 kind: Deployment metadata: name: reverse-words labels: name: reverse-words spec: replicas: 1 selector: matchLabels: name: reverse-words template: metadata: labels: name: reverse-words spec: containers: - name: reverse-words image: quay.io\/mavazque\/reversewords:latest imagePullPolicy: Always ports: - name: reverse-words containerPort: 8080 protocol: TCP - name: oauth-proxy args: - -provider=openshift - -https-address=:8888 - -http-address= - -email-domain=* - -upstream=http:\/\/localhost:8080 - -tls-cert=\/etc\/tls\/private\/tls.crt - -tls-key=\/etc\/tls\/private\/tls.key - -cookie-secret-file=\/etc\/proxy\/secrets\/session_secret - -openshift-service-account=reversewords - -openshift-ca=\/var\/run\/secrets\/kubernetes.io\/serviceaccount\/ca.crt - -skip-auth-regex=^\/metrics image: quay.io\/openshift\/origin-oauth-proxy:4.17 imagePullPolicy: IfNotPresent ports: - name: oauth-proxy containerPort: 8888 protocol: TCP volumeMounts: - mountPath: \/etc\/tls\/private name: secret-reversewords-tls - mountPath: \/etc\/proxy\/secrets name: secret-reversewords-proxy serviceAccountName: reversewords volumes: - name: secret-reversewords-tls secret: defaultMode: 420 secretName: reversewords-tls - name: secret-reversewords-proxy secret: defaultMode: 420 secretName: reversewords-proxy Modify the service\nservice.yaml\napiVersion: v1 kind: Service metadata: annotations: service.alpha.openshift.io\/serving-cert-secret-name: reversewords-tls labels: name: reverse-words name: reverse-words spec: ports: - name: proxy port: 8888 protocol: TCP targetPort: oauth-proxy - name: app port: 8080 protocol: TCP targetPort: reverse-words selector: name: reverse-words sessionAffinity: None type: ClusterIP Deploy oc -n reverse-words apply -f service.yaml oc -n reverse-words apply -f deployment.yaml oc -n reverse-words create route reencrypt reverse-words-authenticated --service=reverse-words --port=proxy --insecure-policy=Redirect Now we should be able to reach our application, let&rsquo;s see what happens when we try to access without providing any authentication details.\ncurl -k -I https:\/\/$(oc -n reverse-words get route reverse-words-authenticated -o jsonpath=&#39;{.status.ingress[*].host}&#39;) HTTP\/1.1 403 Forbidden Set-Cookie: _oauth_proxy=; Path=\/; Domain=reverse-words-authenticated-reverse-words.apps.okd.linuxlabs.org; Expires=Tue, 30 Jul 2019 15:08:22 GMT; HttpOnly; Secure Date: Tue, 30 Jul 2019 16:08:22 GMT Content-Type: text\/html; charset=utf-8 Set-Cookie: 24c429aac95893475d1e8c1316adf60f=255a07dc5b1af1d2d01721678f463c09; path=\/; HttpOnly; Secure Now we are going to access to our application using our browser and authenticating with a valid user:\nScenario 3 - Limiting Access to Specific Authenticated Users In this scenario we are going to modify the OAuth Proxy configuration so only users with access to the reverse-words Namespace can access the application.\nPrerequisites Modify the deployment. Add the line below to the oauth-proxy container arguments\noc -n reverse-words edit deployment reverse-words Attention\nIf you plan to use a resource for openshift-sar that is not part of the core API Group, you need to add the group. i.e: {&quot;group&quot;:&quot;my.resource.group&quot;,&quot;resource&quot;:&quot;myresource&quot;,&quot;namespace&quot;:&quot;mynamespace&quot;,&quot;verb&quot;:&quot;get&quot;}}\n&lt;OMITTED OUTPUT&gt; - -openshift-service-account=reversewords - -openshift-sar={&#34;resource&#34;:&#34;namespaces&#34;,&#34;resourceName&#34;:&#34;reverse-words&#34;,&#34;namespace&#34;:&#34;reverse-words&#34;,&#34;verb&#34;:&#34;get&#34;} &lt;OMITTED OUTPUT&gt; Deploy The deployment should be updated and the OAuth Proxy should be configured to allow access only to users with access to the reverse-words namespace.\nAs we did before, let&rsquo;s try to access with user1 to our application:\nIt failed! That is because user1 does not have access to the reverse-words namespace, let&rsquo;s grant access to user2 and try to login again.\noc -n reverse-words adm policy add-role-to-user view user2 Back on the browser:\nScenario 4 - Limiting Access to Service Accounts Authenticate using ServiceAccount tokens requires some extra work. In this scenario we will grant access to a ServiceAccount named test-user to the application deployed in scenario 3. This scenario assumes you have completed scenario 3.\nIn order to authenticate ServiceAccounts we need to allow auth delegation to the oauth-proxy container, we use a ClusterRoleBinding for that targeting the ServiceAccount used to run the oauth-proxy container, reversewords in our case. Make sure you create below ClusterRoleBinding before continuing:\nclusterrolebinding.yaml\napiVersion: rbac.authorization.k8s.io\/v1 kind: ClusterRoleBinding metadata: # Without this role your oauth-proxy will output # Failed to make webhook authenticator request: tokenreviews.authentication.k8s.io is forbidden: # User &#34;system:serviceaccount:reverse-words:reversewords&#34; cannot create resource &#34;tokenreviews&#34; in API # group &#34;authentication.k8s.io&#34; at the cluster scope name: oauth-create-tokenreviews roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: system:auth-delegator subjects: - kind: ServiceAccount name: reversewords namespace: reverse-words Next, we will create the ServiceAccount we will be using for authenticating in our app, we will name it robot-user:\noc -n reverse-words create serviceaccount robot-user Same as we did in scenario 3, we need to restrict the access to ServiceAccounts with access to specific resources (this is a must for authenticating ServiceAccounts via oauth-proxy). In this case we will restrict access to ServiceAccounts that can get Pods in the reverse-words Namespace. Modify the deployment. Add the line below to the oauth-proxy container arguments:\nNote\nIn the parameters used for the URL delegation you will see I&rsquo;m using &quot;\/&quot;. You can have multiple rules and ask for different access rights depending on the destination URL.\noc -n reverse-words edit deployment reverse-words Attention\nWe are requesting different access for users openshift-sar than for service accounts openshift-delegate-urls. We could request the same access if we wanted to.\n&lt;OMITTED OUTPUT&gt; - -openshift-sar={&#34;resource&#34;:&#34;namespaces&#34;,&#34;resourceName&#34;:&#34;reverse-words&#34;,&#34;namespace&#34;:&#34;reverse-words&#34;,&#34;verb&#34;:&#34;get&#34;} - -openshift-delegate-urls={&#34;\/&#34;:{&#34;resource&#34;:&#34;pods&#34;,&#34;namespace&#34;:&#34;reverse-words&#34;,&#34;verb&#34;:&#34;get&#34;}} &lt;OMITTED OUTPUT&gt; Finally, we need to grant access to the robot-user to get Pods in the reverse-words Namespace. The view Role will grant this access.\noc -n reverse-words adm policy add-role-to-user view -z robot-user At this point, we just need to get a token and authenticate with it:\nTOKEN=$(oc -n reverse-words create token robot-user) curl -k -H &#34;Authorization: Bearer ${TOKEN}&#34; https:\/\/$(oc -n reverse-words get route reverse-words-authenticated -o jsonpath=&#39;{.status.ingress[*].host}&#39;) Reverse Words Release: NotSet. App version: v0.0.25 Scenario 5 - Limit Access to Authenticated Users in a TLS-enabled Application In this scenario the main change we have to do is passing the CA public certificate that issued the certificates for the TLS application to the oauth proxy.\nRequired files deployment.yaml\nNOTE: upstream parameter now points to a https endpoint and uses the service name since the cert is only valid for that CommonName. We added the parameter upstream-ca pointing to the CA certificate that issued our TLS app certs.\napiVersion: apps\/v1 kind: Deployment metadata: name: reverse-words-tls labels: name: reverse-words-tls spec: replicas: 1 selector: matchLabels: name: reverse-words-tls template: metadata: labels: name: reverse-words-tls spec: containers: - name: reverse-words-tls image: quay.io\/mavazque\/reversewords:latest imagePullPolicy: Always ports: - name: reverse-words containerPort: 8080 protocol: TCP args: - &#34;--cert&#34; - &#34;\/etc\/tls\/private\/tls.crt&#34; - &#34;--key&#34; - &#34;\/etc\/tls\/private\/tls.key&#34; volumeMounts: - mountPath: \/etc\/tls\/private name: secret-reversewords-tls-tls - name: oauth-proxy args: - -provider=openshift - -https-address=:8888 - -http-address= - -email-domain=* - -upstream=https:\/\/reverse-words-tls.reverse-words.svc:8080 - -upstream-ca=\/var\/run\/secrets\/kubernetes.io\/serviceaccount\/service-ca.crt - -tls-cert=\/etc\/tls\/private\/tls.crt - -tls-key=\/etc\/tls\/private\/tls.key - -cookie-secret-file=\/etc\/proxy\/secrets\/session_secret - -openshift-service-account=reversewords-tls - -openshift-ca=\/var\/run\/secrets\/kubernetes.io\/serviceaccount\/ca.crt - -skip-auth-regex=^\/metrics image: quay.io\/openshift\/origin-oauth-proxy:4.17 imagePullPolicy: IfNotPresent ports: - name: oauth-proxy containerPort: 8888 protocol: TCP volumeMounts: - mountPath: \/etc\/tls\/private name: secret-reversewords-tls-tls - mountPath: \/etc\/proxy\/secrets name: secret-reversewords-proxy serviceAccountName: reversewords-tls volumes: - name: secret-reversewords-tls-tls secret: defaultMode: 420 secretName: reversewords-tls-tls - name: secret-reversewords-proxy secret: defaultMode: 420 secretName: reversewords-tls-proxy service.yaml\napiVersion: v1 kind: Service metadata: annotations: service.alpha.openshift.io\/serving-cert-secret-name: reversewords-tls-tls labels: name: reverse-words-tls name: reverse-words-tls spec: ports: - name: proxy port: 8888 protocol: TCP targetPort: oauth-proxy - name: app port: 8080 protocol: TCP targetPort: reverse-words selector: name: reverse-words-tls sessionAffinity: None type: ClusterIP Prerequisites Create the Secret\noc -n reverse-words create secret generic reversewords-tls-proxy --from-literal=session_secret=$(head \/dev\/urandom | tr -dc A-Za-z0-9 | head -c43) Create and annotate the ServiceAccount\noc -n reverse-words create serviceaccount reversewords-tls oc -n reverse-words annotate serviceaccount reversewords-tls serviceaccounts.openshift.io\/oauth-redirectreference.reversewords-tls=&#39;{&#34;kind&#34;:&#34;OAuthRedirectReference&#34;,&#34;apiVersion&#34;:&#34;v1&#34;,&#34;reference&#34;:{&#34;kind&#34;:&#34;Route&#34;,&#34;name&#34;:&#34;reverse-words-tls-authenticated&#34;}}&#39; Deploy oc -n reverse-words apply -f service.yaml oc -n reverse-words apply -f deployment.yaml oc -n reverse-words create route reencrypt reverse-words-tls-authenticated --service=reverse-words-tls --port=proxy --insecure-policy=Redirect Now we should be able to reach our application, let&rsquo;s see what happens when we try to access without providing any authentication details.\ncurl -k -I https:\/\/$(oc -n reverse-words get route reverse-words-tls-authenticated -o jsonpath=&#39;{.status.ingress[*].host}&#39;) HTTP\/1.1 403 Forbidden Set-Cookie: _oauth_proxy=; Path=\/; Domain=reverse-words-authenticated-reverse-words.apps.okd.linuxlabs.org; Expires=Tue, 30 Jul 2019 15:08:22 GMT; HttpOnly; Secure Date: Tue, 30 Jul 2019 16:08:22 GMT Content-Type: text\/html; charset=utf-8 Set-Cookie: 24c429aac95893475d1e8c1316adf60f=255a07dc5b1af1d2d01721678f463c09; path=\/; HttpOnly; Secure If we try to access like in Scenario 2 it will work.\nFinal Thoughts This is just a sneak peek of what OAuth Proxy can do, if you want to know more you can check the project&rsquo;s repository here.\nKeep in mind that OAuth Proxy is not intended to replace your application authentication and authorization mechanisms, it is just another security layer on top of your applications.\n","permalink":"https:\/\/linuxera.org\/oauth-proxy-secure-applications-openshift\/","summary":"What is OAuth Proxy A reverse proxy and static file server that provides authentication and authorization to an OpenShift OAuth server or Kubernetes master supporting the 1.6+ remote authorization endpoints to validate access to content. It is intended for use withing OpenShift clusters to make it easy to run both end-user and infrastructure services that do not provider their own authentication.\n[Source]\nSecuring an Application with OAuth Proxy In this blog post we are going to deploy OAuth Proxy in front of a simple application.","title":"Using OpenShift OAuth Proxy to secure your Applications on OpenShift"},{"content":"Operators, operators everywhere As you may have noticed, Kubernetes operators are becoming more an more popular those days. In this post we are going to explain the basics around Operators and we will develop a simple Operator using the Operator Framework SDK.\nWhat is an Operator An operator aims to automate actions usually performed manually while lessening the likelihood of error and simplifying complexity.\nWe can think of an operator as a method of packaging, deploying and managing a Kubernetes enabled application. Kubernetes enabled applications are deployed on Kubernetes and managed using the Kubernetes APIs and tooling.\nKubernetes APIs can be extended in order to enable new types of Kubernetes enabled applications. We could say that Operators are the runtime that manages such applications.\nA simple Operator would define how to deploy an application, whereas an advanced one will also take care of day-2 operations like backup, upgrades, etc.\nOperators use the Controller pattern, but not all Controllers are Operators. We could say it&rsquo;s an Operator if it&rsquo;s got:\nController Pattern API Extension Single-App Focus Feel free to read more about operators on the Operator FAQ by CoreOS\nKubernetes Controllers In the Kubernetes world, the Controllers take care of routine tasks to ensure cluster&rsquo;s observed state, matches cluster&rsquo;s desired state.\nEach Controller is responsible for a particular resource in Kubernetes. The Controller runs a control loop that watches the shared state of the cluster through the Kubernetes API server and makes changes attempting to move the current state towards the desired state.\nSome examples:\nReplication Controller Cronjob Controller Controller Components There are two main components in a controller: Informer\/SharedInformer and WorkQueue.\nInformer In order to retrieve information about an object, the Controller sends a request to the Kubernetes API server. However, querying the API repeatedly can become expensive when dealing with thousands of objects.\nOn top of that, the Controller doesn&rsquo;t really need to send requests continuously. It only cares about CRUD events happening on the objects it&rsquo;s managing.\nInformers are not much used in the current Kubernetes, instead SharedInformers are used.\nSharedInformer A Informer creates a local cache for a set of resources used by itself. In Kubernetes there are multiple controllers running and caring about multiple kinds of resources though.\nHaving a shared cache among Controllers instead of one cache for each Controller sounds like a plan, that&rsquo;s a SharedInformer.\nWorkQueue The SharedInformer can&rsquo;t track what each Controller is up to, so the Controller must provide its own queuing and retrying mechanism.\nWhenever a resource changes, the SharedInformer&rsquo;s Event Handler puts a key into the WorkQueue so the Controller will take care of that change.\nHow a Controller Works Control Loop Every controller has a Control Loop which basically does:\nProcesses every single item from the WorkQueue Pops an item and do whatever it needs to do with that item Pushes the item back to the WorkQueue if required Updates the item status to reflect the new changes Starts over Code Examples\nhttps:\/\/github.com\/kubernetes\/sample-controller\/blob\/release-1.18\/controller.go#L180 https:\/\/github.com\/kubernetes\/sample-controller\/blob\/release-1.18\/controller.go#L187 WorkQueue Stuff is put into the WorkQueue Stuff is take out from the WorkQueue in the Control Loop WorkQueue doesn&rsquo;t store objects, it stores MetaNamespaceKeys A MetaNamespaceKey is a key-value reference for an object. It has the namespace for the resource and the name for the resource.\nCode Examples\nhttps:\/\/github.com\/kubernetes\/sample-controller\/blob\/release-1.18\/controller.go#L111 https:\/\/github.com\/kubernetes\/sample-controller\/blob\/release-1.18\/controller.go#L187 SharedInformer As we said before, is a shared data cache which distributes the data to all the Listers interested in knowing about changes happening to specific objects.\nThe most important part of the SharedInformer are the EventHandlers. Using an EventHandler is how you register your interest in specific object updates like addition, creation, updation or deletion.\nWhen an update occurs, the object will be put into the WorkQueue so it gets processed by the Controller in the Control Loop.\nListers are an important part of the SharedInformers as well. Listers are designed specifically to be used within Controllers as they have access to the cache.\nListers vs Client-go\nListers have access to the cache whereas Client-go will hit the Kubernetes API server (which is expensive when dealing with thousands of objects).\nCode Examples\nhttps:\/\/github.com\/kubernetes\/sample-controller\/blob\/release-1.18\/controller.go#L252 https:\/\/github.com\/kubernetes\/sample-controller\/blob\/release-1.18\/controller.go#L274 SyncHandler A.K.A Reconciliation Loop The first invocation of the SyncHandler will always be getting the MetaNamespaceKey for the resource it needs to work with.\nWith the MetaNamespaceKey the object is gathered from the cache, but well.. it&rsquo;s not really an object, but a pointer to the cached object.\nWith the object reference we can read the object, in case the object needs to be updated, then the object have to be DeepCopied. DeepCopy is an expensive operation, making sure the object will be modified before calling DeepCopy is a good practice.\nWith the object reference \/ DeepCopy we are ready to apply our business logic.\nCode Examples\nhttps:\/\/github.com\/kubernetes\/sample-controller\/blob\/release-1.18\/controller.go#L243 Kubernetes Controllers Some information about controllers:\nCronjob controller is probably the smallest one out there Sample Controller will help you getting started with Kubernetes Controllers Writing your very first Operator using the Operator Framework SDK We will create a very simple Operator using the Operator Framework SDK.\nThe Operator will be in charge of deploying a simple GoLang application.\nRequirements At the moment of this writing the following versions were used:\ngolang-1.19.5 Operator Framework SDK v1.26.1 Kubernetes 1.24 Installing the Operator Framework SDK RELEASE_VERSION=v1.26.1 # Linux sudo curl -L https:\/\/github.com\/operator-framework\/operator-sdk\/releases\/download\/${RELEASE_VERSION}\/operator-sdk_linux_amd64 -o \/usr\/local\/bin\/operator-sdk sudo chmod +x \/usr\/local\/bin\/operator-sdk Initializing the Operator Project First, a new new project for our Operator will be initialized.\nmkdir -p ~\/operators-projects\/reverse-words-operator &amp;&amp; cd $_ export GO111MODULE=on export GOPROXY=https:\/\/proxy.golang.org export GH_USER=&lt;github_user&gt; operator-sdk init --domain=linuxera.org --repo=github.com\/$GH_USER\/reverse-words-operator Create the Operator API Types As previously discussed, Operators extend the Kubernetes API, the API itself is organized in groups and versions. Our Operator will define a new Group, object Kind and its versioning.\nIn the example below we will define a new API Group called apps under domain linuxera.org, a new object Kind ReverseWordsApp and its versioning v1alpha1.\noperator-sdk create api --group=apps --version=v1alpha1 --kind=ReverseWordsApp --resource=true --controller=true Now it&rsquo;s time to define the structure of our new Object. The Spec properties that we will be using are:\nreplicas: Will be used to define the number of replicas for our application appVersion: Will be used to define which version of the application is deployed In the Status we will use:\nappPods: Will track the pods associated to our current ReverseWordsApp instance Different conditions Below the code for our Types:\n\/* Licensed under the Apache License, Version 2.0 (the &#34;License&#34;); you may not use this file except in compliance with the License. You may obtain a copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an &#34;AS IS&#34; BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *\/ package v1alpha1 import ( metav1 &#34;k8s.io\/apimachinery\/pkg\/apis\/meta\/v1&#34; ) \/\/ ReverseWordsAppSpec defines the desired state of ReverseWordsApp type ReverseWordsAppSpec struct { Replicas int32 `json:&#34;replicas&#34;` AppVersion string `json:&#34;appVersion,omitempty&#34;` } \/\/ ReverseWordsAppStatus defines the observed state of ReverseWordsApp type ReverseWordsAppStatus struct { AppPods []string `json:&#34;appPods&#34;` Conditions []metav1.Condition `json:&#34;conditions&#34;` } \/\/ +kubebuilder:object:root=true \/\/ +kubebuilder:subresource:status \/\/ ReverseWordsApp is the Schema for the reversewordsapps API type ReverseWordsApp struct { metav1.TypeMeta `json:&#34;,inline&#34;` metav1.ObjectMeta `json:&#34;metadata,omitempty&#34;` Spec ReverseWordsAppSpec `json:&#34;spec,omitempty&#34;` Status ReverseWordsAppStatus `json:&#34;status,omitempty&#34;` } \/\/ +kubebuilder:object:root=true \/\/ ReverseWordsAppList contains a list of ReverseWordsApp type ReverseWordsAppList struct { metav1.TypeMeta `json:&#34;,inline&#34;` metav1.ListMeta `json:&#34;metadata,omitempty&#34;` Items []ReverseWordsApp `json:&#34;items&#34;` } func init() { SchemeBuilder.Register(&amp;ReverseWordsApp{}, &amp;ReverseWordsAppList{}) } \/\/ Conditions const ( \/\/ ConditionTypeReverseWordsDeploymentNotReady indicates if the Reverse Words Deployment is not ready ConditionTypeReverseWordsDeploymentNotReady string = &#34;ReverseWordsDeploymentNotReady&#34; \/\/ ConditionTypeReady indicates if the Reverse Words Deployment is ready ConditionTypeReady string = &#34;Ready&#34; ) You can download the Types file:\ncurl -Ls https:\/\/linuxera.org\/writing-operators-using-operator-framework\/reversewordsapp_types.go -o ~\/operators-projects\/reverse-words-operator\/api\/v1alpha1\/reversewordsapp_types.go Replicas will be defined as an int32 and will reference the Spec property replicas. For the status AppPods will be defined as a stringList and will reference the Status property appPods.\nWith above changes in-place we need to add new dependencies and re-generate some boilerplate code to take into account the latest changes in our types.\ngo mod tidy make manifests make generate Code your Operator business logic An empty controller (well, not that empty) has been created into our project, now it&rsquo;s time to modify it so it actually deploys our application the way we want.\nOur application consists of a Deployment and a Service, so our Operator will deploy the Reverse Words App as follows:\nA Kubernetes Deployment object will be created A Kubernetes Service object will be created Below code (commented) for our Controller:\n\/* Licensed under the Apache License, Version 2.0 (the &#34;License&#34;); you may not use this file except in compliance with the License. You may obtain a copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an &#34;AS IS&#34; BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *\/ package controllers import ( &#34;context&#34; &#34;reflect&#34; &#34;github.com\/go-logr\/logr&#34; appsv1alpha1 &#34;github.com\/mvazquezc\/reverse-words-operator\/api\/v1alpha1&#34; appsv1 &#34;k8s.io\/api\/apps\/v1&#34; corev1 &#34;k8s.io\/api\/core\/v1&#34; &#34;k8s.io\/apimachinery\/pkg\/api\/errors&#34; &#34;k8s.io\/apimachinery\/pkg\/api\/meta&#34; metav1 &#34;k8s.io\/apimachinery\/pkg\/apis\/meta\/v1&#34; &#34;k8s.io\/apimachinery\/pkg\/runtime&#34; &#34;k8s.io\/apimachinery\/pkg\/types&#34; &#34;k8s.io\/apimachinery\/pkg\/util\/intstr&#34; ctrl &#34;sigs.k8s.io\/controller-runtime&#34; &#34;sigs.k8s.io\/controller-runtime\/pkg\/client&#34; &#34;sigs.k8s.io\/controller-runtime\/pkg\/controller&#34; &#34;sigs.k8s.io\/controller-runtime\/pkg\/controller\/controllerutil&#34; &#34;sigs.k8s.io\/controller-runtime\/pkg\/event&#34; ctrllog &#34;sigs.k8s.io\/controller-runtime\/pkg\/log&#34; &#34;sigs.k8s.io\/controller-runtime\/pkg\/predicate&#34; ) \/\/ ReverseWordsAppReconciler reconciles a ReverseWordsApp object type ReverseWordsAppReconciler struct { client.Client Scheme *runtime.Scheme } const ( \/\/ Finalizer for our objects reverseWordsAppFinalizer = &#34;finalizer.reversewordsapp.apps.linuxera.org&#34; concurrentReconciles = 10 ) \/\/ +kubebuilder:rbac:groups=apps.linuxera.org,resources=reversewordsapps,verbs=get;list;watch;create;update;patch;delete \/\/ +kubebuilder:rbac:groups=apps.linuxera.org,resources=reversewordsapps\/status,verbs=get;update;patch \/\/ +kubebuilder:rbac:groups=apps.linuxera.org,resources=reversewordsapps\/finalizers,verbs=get;update;patch \/\/ +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete \/\/ +kubebuilder:rbac:groups=core,resources=services,verbs=get;list;watch;create;update;patch;delete \/\/ +kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch \/\/ +kubebuilder:rbac:groups=core,resources=events,verbs=create;patch func (r *ReverseWordsAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { log := ctrllog.FromContext(ctx) \/\/ Fetch the ReverseWordsApp instance instance := &amp;appsv1alpha1.ReverseWordsApp{} err := r.Get(ctx, req.NamespacedName, instance) if err != nil { if errors.IsNotFound(err) { \/\/ Request object not found, could have been deleted after reconcile request. \/\/ Owned objects are automatically garbage collected. For additional cleanup logic use finalizers. \/\/ Return and don&#39;t requeue log.Info(&#34;ReverseWordsApp resource not found. Ignoring since object must be deleted&#34;) return ctrl.Result{}, nil } \/\/ Error reading the object - requeue the request. log.Error(err, &#34;Failed to get ReverseWordsApp&#34;) return ctrl.Result{}, err } \/\/ Check if the CR is marked to be deleted isInstanceMarkedToBeDeleted := instance.GetDeletionTimestamp() != nil if isInstanceMarkedToBeDeleted { log.Info(&#34;Instance marked for deletion, running finalizers&#34;) if contains(instance.GetFinalizers(), reverseWordsAppFinalizer) { \/\/ Run the finalizer logic err := r.finalizeReverseWordsApp(log, instance) if err != nil { \/\/ Don&#39;t remove the finalizer if we failed to finalize the object return ctrl.Result{}, err } log.Info(&#34;Instance finalizers completed&#34;) \/\/ Remove finalizer once the finalizer logic has run controllerutil.RemoveFinalizer(instance, reverseWordsAppFinalizer) err = r.Update(ctx, instance) if err != nil { \/\/ If the object update fails, requeue return ctrl.Result{}, err } } log.Info(&#34;Instance can be deleted now&#34;) return ctrl.Result{}, nil } \/\/ Add Finalizers to the CR if !contains(instance.GetFinalizers(), reverseWordsAppFinalizer) { if err := r.addFinalizer(log, instance); err != nil { return ctrl.Result{}, err } } \/\/ Reconcile Deployment object result, err := r.reconcileDeployment(instance, log) if err != nil { return result, err } \/\/ Reconcile Service object result, err = r.reconcileService(instance, log) if err != nil { return result, err } \/\/ The CR status is updated in the Deployment reconcile method return ctrl.Result{}, nil } func (r *ReverseWordsAppReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&amp;appsv1alpha1.ReverseWordsApp{}). Owns(&amp;appsv1.Deployment{}). Owns(&amp;corev1.Service{}). WithEventFilter(ignoreDeletionPredicate()). \/\/ Filter events that do not increase generation id, like status updates WithOptions(controller.Options{MaxConcurrentReconciles: concurrentReconciles}). \/\/ run multiple reconcile loops in parallel Complete(r) } func (r *ReverseWordsAppReconciler) reconcileDeployment(cr *appsv1alpha1.ReverseWordsApp, log logr.Logger) (ctrl.Result, error) { \/\/ Define a new Deployment object deployment := newDeploymentForCR(cr) \/\/ Set ReverseWordsApp instance as the owner and controller of the Deployment if err := ctrl.SetControllerReference(cr, deployment, r.Scheme); err != nil { return ctrl.Result{}, err } \/\/ Check if this Deployment already exists deploymentFound := &amp;appsv1.Deployment{} err := r.Get(context.Background(), types.NamespacedName{Name: deployment.Name, Namespace: deployment.Namespace}, deploymentFound) if err != nil &amp;&amp; errors.IsNotFound(err) { log.Info(&#34;Creating a new Deployment&#34;, &#34;Deployment.Namespace&#34;, deployment.Namespace, &#34;Deployment.Name&#34;, deployment.Name) err = r.Create(context.Background(), deployment) if err != nil { return ctrl.Result{}, err } \/\/ Requeue the object to update its status return ctrl.Result{Requeue: true}, nil } else if err != nil { return ctrl.Result{}, err } else { \/\/ Deployment already exists log.Info(&#34;Deployment already exists&#34;, &#34;Deployment.Namespace&#34;, deploymentFound.Namespace, &#34;Deployment.Name&#34;, deploymentFound.Name) } \/\/ Ensure deployment replicas match the desired state if !reflect.DeepEqual(deploymentFound.Spec.Replicas, deployment.Spec.Replicas) { log.Info(&#34;Current deployment replicas do not match ReverseWordsApp configured Replicas&#34;) \/\/ Update the replicas err = r.Update(context.Background(), deployment) if err != nil { log.Error(err, &#34;Failed to update Deployment.&#34;, &#34;Deployment.Namespace&#34;, deploymentFound.Namespace, &#34;Deployment.Name&#34;, deploymentFound.Name) return ctrl.Result{}, err } } \/\/ Ensure deployment container image match the desired state, returns true if deployment needs to be updated if checkDeploymentImage(deploymentFound, deployment) { log.Info(&#34;Current deployment image version do not match ReverseWordsApp configured version&#34;) \/\/ Update the image err = r.Update(context.Background(), deployment) if err != nil { log.Error(err, &#34;Failed to update Deployment.&#34;, &#34;Deployment.Namespace&#34;, deploymentFound.Namespace, &#34;Deployment.Name&#34;, deploymentFound.Name) return ctrl.Result{}, err } } \/\/ Check if the deployment is ready deploymentReady := isDeploymentReady(deploymentFound) \/\/ Create list options for listing deployment pods podList := &amp;corev1.PodList{} listOpts := []client.ListOption{ client.InNamespace(deploymentFound.Namespace), client.MatchingLabels(deploymentFound.Labels), } \/\/ List the pods for this ReverseWordsApp deployment err = r.List(context.Background(), podList, listOpts...) if err != nil { log.Error(err, &#34;Failed to list Pods.&#34;, &#34;Deployment.Namespace&#34;, deploymentFound.Namespace, &#34;Deployment.Name&#34;, deploymentFound.Name) return ctrl.Result{}, err } \/\/ Get running Pods from listing above (if any) podNames := getRunningPodNames(podList.Items) if deploymentReady { \/\/ Update the status to ready cr.Status.AppPods = podNames meta.SetStatusCondition(&amp;cr.Status.Conditions, metav1.Condition{Type: appsv1alpha1.ConditionTypeReverseWordsDeploymentNotReady, Status: metav1.ConditionFalse, Reason: appsv1alpha1.ConditionTypeReverseWordsDeploymentNotReady}) meta.SetStatusCondition(&amp;cr.Status.Conditions, metav1.Condition{Type: appsv1alpha1.ConditionTypeReady, Status: metav1.ConditionTrue, Reason: appsv1alpha1.ConditionTypeReady}) } else { \/\/ Update the status to not ready cr.Status.AppPods = podNames meta.SetStatusCondition(&amp;cr.Status.Conditions, metav1.Condition{Type: appsv1alpha1.ConditionTypeReverseWordsDeploymentNotReady, Status: metav1.ConditionTrue, Reason: appsv1alpha1.ConditionTypeReverseWordsDeploymentNotReady}) meta.SetStatusCondition(&amp;cr.Status.Conditions, metav1.Condition{Type: appsv1alpha1.ConditionTypeReady, Status: metav1.ConditionFalse, Reason: appsv1alpha1.ConditionTypeReady}) } \/\/ Reconcile the new status for the instance cr, err = r.updateReverseWordsAppStatus(cr, log) if err != nil { log.Error(err, &#34;Failed to update ReverseWordsApp Status.&#34;) return ctrl.Result{}, err } \/\/ Deployment reconcile finished return ctrl.Result{}, nil } \/\/ updateReverseWordsAppStatus updates the Status of a given CR func (r *ReverseWordsAppReconciler) updateReverseWordsAppStatus(cr *appsv1alpha1.ReverseWordsApp, log logr.Logger) (*appsv1alpha1.ReverseWordsApp, error) { reverseWordsApp := &amp;appsv1alpha1.ReverseWordsApp{} err := r.Get(context.Background(), types.NamespacedName{Name: cr.Name, Namespace: cr.Namespace}, reverseWordsApp) if err != nil { return reverseWordsApp, err } if !reflect.DeepEqual(cr.Status, reverseWordsApp.Status) { log.Info(&#34;Updating ReverseWordsApp Status.&#34;) \/\/ We need to update the status err = r.Status().Update(context.Background(), cr) if err != nil { return cr, err } updatedReverseWordsApp := &amp;appsv1alpha1.ReverseWordsApp{} err = r.Get(context.Background(), types.NamespacedName{Name: cr.Name, Namespace: cr.Namespace}, updatedReverseWordsApp) if err != nil { return cr, err } cr = updatedReverseWordsApp.DeepCopy() } return cr, nil } \/\/ addFinalizer adds a given finalizer to a given CR func (r *ReverseWordsAppReconciler) addFinalizer(log logr.Logger, cr *appsv1alpha1.ReverseWordsApp) error { log.Info(&#34;Adding Finalizer for the ReverseWordsApp&#34;) controllerutil.AddFinalizer(cr, reverseWordsAppFinalizer) \/\/ Update CR err := r.Update(context.Background(), cr) if err != nil { log.Error(err, &#34;Failed to update ReverseWordsApp with finalizer&#34;) return err } return nil } \/\/ finalizeReverseWordsApp runs required tasks before deleting the objects owned by the CR func (r *ReverseWordsAppReconciler) finalizeReverseWordsApp(log logr.Logger, cr *appsv1alpha1.ReverseWordsApp) error { \/\/ TODO(user): Add the cleanup steps that the operator \/\/ needs to do before the CR can be deleted. Examples \/\/ of finalizers include performing backups and deleting \/\/ resources that are not owned by this CR, like a PVC. log.Info(&#34;Successfully finalized ReverseWordsApp&#34;) return nil } func (r *ReverseWordsAppReconciler) reconcileService(cr *appsv1alpha1.ReverseWordsApp, log logr.Logger) (ctrl.Result, error) { \/\/ Define a new Service object service := newServiceForCR(cr) \/\/ Set ReverseWordsApp instance as the owner and controller of the Service if err := controllerutil.SetControllerReference(cr, service, r.Scheme); err != nil { return ctrl.Result{}, err } \/\/ Check if this Service already exists serviceFound := &amp;corev1.Service{} err := r.Get(context.Background(), types.NamespacedName{Name: service.Name, Namespace: service.Namespace}, serviceFound) if err != nil &amp;&amp; errors.IsNotFound(err) { log.Info(&#34;Creating a new Service&#34;, &#34;Service.Namespace&#34;, service.Namespace, &#34;Service.Name&#34;, service.Name) err = r.Create(context.Background(), service) if err != nil { return ctrl.Result{}, err } \/\/ Service created successfully - don&#39;t requeue return ctrl.Result{}, nil } else if err != nil { return ctrl.Result{}, err } else { \/\/ Service already exists log.Info(&#34;Service already exists&#34;, &#34;Service.Namespace&#34;, serviceFound.Namespace, &#34;Service.Name&#34;, serviceFound.Name) } \/\/ Service reconcile finished return ctrl.Result{}, nil } \/\/ Returns a new deployment without replicas configured \/\/ replicas will be configured in the sync loop func newDeploymentForCR(cr *appsv1alpha1.ReverseWordsApp) *appsv1.Deployment { labels := map[string]string{ &#34;app&#34;: cr.Name, } replicas := cr.Spec.Replicas \/\/ Minimum replicas will be 1 if replicas == 0 { replicas = 1 } appVersion := &#34;latest&#34; if cr.Spec.AppVersion != &#34;&#34; { appVersion = cr.Spec.AppVersion } \/\/ TODO:Check if application version exists containerImage := &#34;quay.io\/mavazque\/reversewords:&#34; + appVersion probe := &amp;corev1.Probe{ ProbeHandler: corev1.ProbeHandler{ HTTPGet: &amp;corev1.HTTPGetAction{ Path: &#34;\/health&#34;, Port: intstr.FromInt(8080), }, }, InitialDelaySeconds: 5, TimeoutSeconds: 2, PeriodSeconds: 15, } return &amp;appsv1.Deployment{ TypeMeta: metav1.TypeMeta{ APIVersion: &#34;apps\/v1&#34;, Kind: &#34;Deployment&#34;, }, ObjectMeta: metav1.ObjectMeta{ Name: &#34;dp-&#34; + cr.Name, Namespace: cr.Namespace, Labels: labels, }, Spec: appsv1.DeploymentSpec{ Replicas: &amp;replicas, Selector: &amp;metav1.LabelSelector{ MatchLabels: labels, }, Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: labels, }, Spec: corev1.PodSpec{ Containers: []corev1.Container{ { Image: containerImage, Name: &#34;reversewords&#34;, Ports: []corev1.ContainerPort{ { ContainerPort: 8080, Name: &#34;reversewords&#34;, }, }, LivenessProbe: probe, ReadinessProbe: probe, }, }, }, }, }, } } \/\/ Returns a new service func newServiceForCR(cr *appsv1alpha1.ReverseWordsApp) *corev1.Service { labels := map[string]string{ &#34;app&#34;: cr.Name, } return &amp;corev1.Service{ TypeMeta: metav1.TypeMeta{ APIVersion: &#34;v1&#34;, Kind: &#34;Service&#34;, }, ObjectMeta: metav1.ObjectMeta{ Name: &#34;service-&#34; + cr.Name, Namespace: cr.Namespace, Labels: labels, }, Spec: corev1.ServiceSpec{ Type: corev1.ServiceTypeLoadBalancer, Selector: labels, Ports: []corev1.ServicePort{ { Name: &#34;http&#34;, Port: 8080, }, }, }, } } \/\/ isDeploymentReady returns a true bool if the deployment has all its pods ready func isDeploymentReady(deployment *appsv1.Deployment) bool { configuredReplicas := deployment.Status.Replicas readyReplicas := deployment.Status.ReadyReplicas deploymentReady := false if configuredReplicas == readyReplicas { deploymentReady = true } return deploymentReady } \/\/ getRunningPodNames returns the pod names for the pods running in the array of pods passed in func getRunningPodNames(pods []corev1.Pod) []string { \/\/ Create an empty []string, so if no podNames are returned, instead of nil we get an empty slice var podNames []string = make([]string, 0) for _, pod := range pods { if pod.GetObjectMeta().GetDeletionTimestamp() != nil { continue } if pod.Status.Phase == corev1.PodPending || pod.Status.Phase == corev1.PodRunning { podNames = append(podNames, pod.Name) } } return podNames } \/\/ checkDeploymentImage returns wether the deployment image is different or not func checkDeploymentImage(current *appsv1.Deployment, desired *appsv1.Deployment) bool { for _, curr := range current.Spec.Template.Spec.Containers { for _, des := range desired.Spec.Template.Spec.Containers { \/\/ Only compare the images of containers with the same name if curr.Name == des.Name { if curr.Image != des.Image { return true } } } } return false } \/\/ contains returns true if a string is found on a slice func contains(list []string, s string) bool { for _, v := range list { if v == s { return true } } return false } \/\/ Ignore changes that do not increase the resource generation func ignoreDeletionPredicate() predicate.Predicate { return predicate.Funcs{ UpdateFunc: func(e event.UpdateEvent) bool { \/\/ Ignore updates to CR status in which case metadata.Generation does not change return e.ObjectOld.GetGeneration() != e.ObjectNew.GetGeneration() }, DeleteFunc: func(e event.DeleteEvent) bool { \/\/ Evaluates to false if the object has been confirmed deleted. return !e.DeleteStateUnknown }, } } You can download the controller code, remember to change the GitHub ID before bulding the operator:\n# Remember to change import: appsv1alpha1 &#34;github.com\/mvazquezc\/reverse-words-operator\/api\/v1alpha1&#34; curl -Ls https:\/\/linuxera.org\/writing-operators-using-operator-framework\/reversewordsapp_controller.go -o ~\/operators-projects\/reverse-words-operator\/controllers\/reversewordsapp_controller.go Setup Watch namespaces By default, the controller will watch all namespaces, in this case we want it to watch only the namespace where it runs, in order to do so we need to update the controller options in the main.go file.\n\/* Copyright 2021. Licensed under the Apache License, Version 2.0 (the &#34;License&#34;); you may not use this file except in compliance with the License. You may obtain a copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an &#34;AS IS&#34; BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *\/ package main import ( &#34;flag&#34; &#34;fmt&#34; &#34;os&#34; \/\/ Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) \/\/ to ensure that exec-entrypoint and run can make use of them. _ &#34;k8s.io\/client-go\/plugin\/pkg\/client\/auth&#34; &#34;k8s.io\/apimachinery\/pkg\/runtime&#34; utilruntime &#34;k8s.io\/apimachinery\/pkg\/util\/runtime&#34; clientgoscheme &#34;k8s.io\/client-go\/kubernetes\/scheme&#34; ctrl &#34;sigs.k8s.io\/controller-runtime&#34; &#34;sigs.k8s.io\/controller-runtime\/pkg\/healthz&#34; &#34;sigs.k8s.io\/controller-runtime\/pkg\/log\/zap&#34; appsv1alpha1 &#34;github.com\/mvazquezc\/reverse-words-operator\/api\/v1alpha1&#34; &#34;github.com\/mvazquezc\/reverse-words-operator\/controllers&#34; \/\/+kubebuilder:scaffold:imports ) var ( scheme = runtime.NewScheme() setupLog = ctrl.Log.WithName(&#34;setup&#34;) ) func init() { utilruntime.Must(clientgoscheme.AddToScheme(scheme)) utilruntime.Must(appsv1alpha1.AddToScheme(scheme)) \/\/+kubebuilder:scaffold:scheme } func main() { var metricsAddr string var enableLeaderElection bool var probeAddr string flag.StringVar(&amp;metricsAddr, &#34;metrics-bind-address&#34;, &#34;:8080&#34;, &#34;The address the metric endpoint binds to.&#34;) flag.StringVar(&amp;probeAddr, &#34;health-probe-bind-address&#34;, &#34;:8081&#34;, &#34;The address the probe endpoint binds to.&#34;) flag.BoolVar(&amp;enableLeaderElection, &#34;leader-elect&#34;, false, &#34;Enable leader election for controller manager. &#34;+ &#34;Enabling this will ensure there is only one active controller manager.&#34;) opts := zap.Options{ Development: true, } opts.BindFlags(flag.CommandLine) flag.Parse() ctrl.SetLogger(zap.New(zap.UseFlagOptions(&amp;opts))) watchNamespace, err := getWatchNamespace() mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ Scheme: scheme, MetricsBindAddress: metricsAddr, Port: 9443, HealthProbeBindAddress: probeAddr, LeaderElection: enableLeaderElection, LeaderElectionID: &#34;1ef59d40.linuxera.org&#34;, Namespace: watchNamespace, \/\/ namespaced-scope when the value is not an empty string }) if err != nil { setupLog.Error(err, &#34;unable to start manager&#34;) os.Exit(1) } if err = (&amp;controllers.ReverseWordsAppReconciler{ Client: mgr.GetClient(), Scheme: mgr.GetScheme(), }).SetupWithManager(mgr); err != nil { setupLog.Error(err, &#34;unable to create controller&#34;, &#34;controller&#34;, &#34;ReverseWordsApp&#34;) os.Exit(1) } \/\/+kubebuilder:scaffold:builder if err := mgr.AddHealthzCheck(&#34;healthz&#34;, healthz.Ping); err != nil { setupLog.Error(err, &#34;unable to set up health check&#34;) os.Exit(1) } if err := mgr.AddReadyzCheck(&#34;readyz&#34;, healthz.Ping); err != nil { setupLog.Error(err, &#34;unable to set up ready check&#34;) os.Exit(1) } setupLog.Info(&#34;starting manager&#34;) if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { setupLog.Error(err, &#34;problem running manager&#34;) os.Exit(1) } } \/\/ getWatchNamespace returns the Namespace the operator should be watching for changes func getWatchNamespace() (string, error) { \/\/ WatchNamespaceEnvVar is the constant for env variable WATCH_NAMESPACE \/\/ which specifies the Namespace to watch. \/\/ An empty value means the operator is running with cluster scope. var watchNamespaceEnvVar = &#34;WATCH_NAMESPACE&#34; ns, found := os.LookupEnv(watchNamespaceEnvVar) if !found { return &#34;&#34;, fmt.Errorf(&#34;%s must be set&#34;, watchNamespaceEnvVar) } return ns, nil } You can download the main.go, remember to change the GitHub ID before bulding the operator:\n# Remember to change import: appsv1alpha1 &#34;github.com\/mvazquezc\/reverse-words-operator\/api\/v1alpha1&#34; curl -Ls https:\/\/linuxera.org\/writing-operators-using-operator-framework\/main.go -o ~\/operators-projects\/reverse-words-operator\/main.go Specify permissions and generate RBAC manifests Our controller needs some RBAC permissions to interact with the resources it manages. These has been specified via RBAC Markers in our controller code:\n\/\/ +kubebuilder:rbac:groups=apps.linuxera.org,resources=reversewordsapps,verbs=get;list;watch;create;update;patch;delete \/\/ +kubebuilder:rbac:groups=apps.linuxera.org,resources=reversewordsapps\/status,verbs=get;update;patch \/\/ +kubebuilder:rbac:groups=apps.linuxera.org,resources=reversewordsapps\/finalizers,verbs=get;update;patch \/\/ +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete \/\/ +kubebuilder:rbac:groups=core,resources=services,verbs=get;list;watch;create;update;patch;delete \/\/ +kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch \/\/ +kubebuilder:rbac:groups=core,resources=events,verbs=create;patch func (r *ReverseWordsAppReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) { The ClusterRole manifest at config\/rbac\/role.yaml is generated from the above markers via controller-gen with the following command:\ngo mod tidy make manifests Build the Operator First, we will build the operator and once the image is built, we will push it to the Quay Registry.\nBefore we start building the operator, we need access to a Kubernetes cluster. If you don&rsquo;t have one you can use Kind, Minikube or my prefered one, KCli\nIn order to get a local cluster with KCli, just run this command:\nkcli create kube generic -P ctlplanes=1 -P workers=1 -P ctlplane_memory=4096 -P numcpus=2 -P worker_memory=4096 -P sdn=calico -P version=1.24 -P ingress=true -P ingress_method=nginx -P metallb=true -P domain=linuxera.org operatorscluster Now that we have the cluster up and running we will build and push the operator.\nNOTE: If you use podman instead of docker you can edit the Makefile and change docker commands by podman commands\nexport USERNAME=&lt;quay-username&gt; make docker-build docker-push IMG=quay.io\/$USERNAME\/reversewords-operator:v0.0.1 Deploy the Operator Create the required CRDs in the cluster\nmake install Deploy the operator\nNOTE: While developing you can run the operator locally (you need a valid kubeconfig) by running make run\nIn order to deploy the different operator pieces, Kustomize is used. There is a Kustomization file (~\/operators-projects\/reverse-words-operator\/config\/default\/kustomization.yaml) where you can define some defaults for your operator, like the namePrefix for the different objects or the namespace where it will be deployed.\nEdit the default kustomization file ~\/operators-projects\/reverse-words-operator\/config\/default\/kustomization.yaml and specify the namespace where your operator should run by modifying the namespace property\nexport NAMESPACE=operators-test sed -i &#34;s\/namespace: .*\/namespace: $NAMESPACE\/g&#34; ~\/operators-projects\/reverse-words-operator\/config\/default\/kustomization.yaml Create the namespace and Deploy the operator\nkubectl create ns $NAMESPACE export USERNAME=&lt;quay_username&gt; make deploy IMG=quay.io\/$USERNAME\/reversewords-operator:v0.0.1 Patch the controller deployment so it only watches the namespace where it&rsquo;s running\nkubectl -n $NAMESPACE patch deployment reverse-words-operator-controller-manager -p &#39;{&#34;spec&#34;:{&#34;template&#34;:{&#34;spec&#34;:{&#34;$setElementOrder\/containers&#34;:[{&#34;name&#34;:&#34;kube-rbac-proxy&#34;},{&#34;name&#34;:&#34;manager&#34;}],&#34;containers&#34;:[{&#34;env&#34;:[{&#34;name&#34;:&#34;WATCH_NAMESPACE&#34;,&#34;valueFrom&#34;:{&#34;fieldRef&#34;:{&#34;fieldPath&#34;:&#34;metadata.namespace&#34;}}}],&#34;name&#34;:&#34;manager&#34;}]}}}}&#39; We should see our operator pod up and running\n1.676311934753094e+09\tINFO\tcontroller-runtime.metrics\tMetrics server is starting to listen\t{&#34;addr&#34;: &#34;127.0.0.\t1:8080&#34;} 1.6763119347534144e+09\tINFO\tsetup\tstarting manager I0213 18:12:14.753860 1 leaderelection.go:248] attempting to acquire leader lease operators-test\/1ef59d40.\tlinuxera.org... 1.6763119347538702e+09\tINFO\tStarting server\t{&#34;kind&#34;: &#34;health probe&#34;, &#34;addr&#34;: &#34;[::]:8081&#34;} 1.6763119347539454e+09\tINFO\tStarting server\t{&#34;path&#34;: &#34;\/metrics&#34;, &#34;kind&#34;: &#34;metrics&#34;, &#34;addr&#34;: &#34;127.0.0.1:8080&#34;} I0213 18:12:37.253145 1 leaderelection.go:258] successfully acquired lease operators-test\/1ef59d40.linuxera.org 1.6763119572531986e+09\tDEBUG\tevents\treverse-words-operator-controller-manager-755f55cffc-9wprb_028ea174-80b7-4294-abfb-1d1aae892cd7 became leader\t{&#34;type&#34;: &#34;Normal&#34;, &#34;object&#34;: {&#34;kind&#34;:&#34;Lease&#34;,&#34;namespace&#34;:&#34;operators-test&#34;,&#34;name&#34;:&#34;1ef59d40.linuxera.org&#34;,\t&#34;uid&#34;:&#34;ae3f7dff-1624-47b2-9010-c666d559473d&#34;,&#34;apiVersion&#34;:&#34;coordination.k8s.io\/v1&#34;,&#34;resourceVersion&#34;:&#34;11102046&#34;}, &#34;reason&#34;: &#34;LeaderElection&#34;} 1.6763119572534668e+09\tINFO\tStarting EventSource\t{&#34;controller&#34;: &#34;reversewordsapp&#34;, &#34;controllerGroup&#34;: &#34;apps.\tlinuxera.org&#34;, &#34;controllerKind&#34;: &#34;ReverseWordsApp&#34;, &#34;source&#34;: &#34;kind source: *v1alpha1.ReverseWordsApp&#34;} 1.6763119572535148e+09\tINFO\tStarting EventSource\t{&#34;controller&#34;: &#34;reversewordsapp&#34;, &#34;controllerGroup&#34;: &#34;apps.\tlinuxera.org&#34;, &#34;controllerKind&#34;: &#34;ReverseWordsApp&#34;, &#34;source&#34;: &#34;kind source: *v1.Deployment&#34;} 1.6763119572535224e+09\tINFO\tStarting EventSource\t{&#34;controller&#34;: &#34;reversewordsapp&#34;, &#34;controllerGroup&#34;: &#34;apps.\tlinuxera.org&#34;, &#34;controllerKind&#34;: &#34;ReverseWordsApp&#34;, &#34;source&#34;: &#34;kind source: *v1.Service&#34;} 1.6763119572535274e+09\tINFO\tStarting Controller\t{&#34;controller&#34;: &#34;reversewordsapp&#34;, &#34;controllerGroup&#34;: &#34;apps.\tlinuxera.org&#34;, &#34;controllerKind&#34;: &#34;ReverseWordsApp&#34;} 1.6763119573569405e+09\tINFO\tStarting workers\t{&#34;controller&#34;: &#34;reversewordsapp&#34;, &#34;controllerGroup&#34;: &#34;apps.\tlinuxera.org&#34;, &#34;controllerKind&#34;: &#34;ReverseWordsApp&#34;, &#34;worker count&#34;: 10} Now it&rsquo;s time to create ReverseWordsApp instances\ncat &lt;&lt;EOF | kubectl -n $NAMESPACE create -f - apiVersion: apps.linuxera.org\/v1alpha1 kind: ReverseWordsApp metadata: name: example-reversewordsapp spec: replicas: 1 EOF cat &lt;&lt;EOF | kubectl -n $NAMESPACE create -f - apiVersion: apps.linuxera.org\/v1alpha1 kind: ReverseWordsApp metadata: name: example-reversewordsapp-2 spec: replicas: 2 EOF We should see two deployments and services being created, and if wee look at the status of our object we should see the pods backing the instance\nkubectl -n $NAMESPACE get reversewordsapps example-reversewordsapp -o yaml apiVersion: apps.linuxera.org\/v1alpha1 kind: ReverseWordsApp metadata: creationTimestamp: &#34;2023-02-13T18:13:48Z&#34; finalizers: - finalizer.reversewordsapp.apps.linuxera.org generation: 1 name: example-reversewordsapp namespace: operators-test resourceVersion: &#34;11103763&#34; uid: ef9351b2-cd44-47b0-ba66-8143f06267dc spec: replicas: 1 status: appPods: - dp-example-reversewordsapp-75cff95fd8-5qvm9 conditions: - lastTransitionTime: &#34;2023-02-13T18:13:48Z&#34; message: &#34;&#34; reason: ReverseWordsDeploymentNotReady status: &#34;True&#34; type: ReverseWordsDeploymentNotReady - lastTransitionTime: &#34;2023-02-13T18:13:48Z&#34; message: &#34;&#34; reason: Ready status: &#34;False&#34; type: Ready We can test our application now\nLB_ENDPOINT=$(kubectl -n $NAMESPACE get svc --selector=&#39;app=example-reversewordsapp&#39; -o jsonpath=&#39;{.items[*].status.loadBalancer.ingress[*].ip}&#39;) curl -X POST -d &#39;{&#34;word&#34;:&#34;PALC&#34;}&#39; http:\/\/$LB_ENDPOINT:8080 {&#34;reverse_word&#34;:&#34;CLAP&#34;} Cleanup\nkubectl -n $NAMESPACE delete reversewordsapp example-reversewordsapp example-reversewordsapp-2 kubectl delete -f config\/crd\/bases\/apps.linuxera.org_reversewordsapps.yaml kubectl delete ns operators-test That&rsquo;s it!\nIn the next episode: We will look at how to use OLM to release our operator We will see a K8s controllers deep dive Sources Operators by CoreOS A deep dive into Kubernetes Controllers Writing Kube Controllers for Everyone ","permalink":"https:\/\/linuxera.org\/writing-operators-using-operator-framework\/","summary":"Operators, operators everywhere As you may have noticed, Kubernetes operators are becoming more an more popular those days. In this post we are going to explain the basics around Operators and we will develop a simple Operator using the Operator Framework SDK.\nWhat is an Operator An operator aims to automate actions usually performed manually while lessening the likelihood of error and simplifying complexity.\nWe can think of an operator as a method of packaging, deploying and managing a Kubernetes enabled application.","title":"Writing Operators using the Operator Framework SDK"}]