<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sergii Bieliaievskyi on Medium]]></title>
        <description><![CDATA[Stories by Sergii Bieliaievskyi on Medium]]></description>
        <link>https://medium.com/@magelan09?source=rss-dcaa4a6adc6f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*CHL99MSxuM5rfDLZ.jpg</url>
            <title>Stories by Sergii Bieliaievskyi on Medium</title>
            <link>https://medium.com/@magelan09?source=rss-dcaa4a6adc6f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 14:40:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@magelan09/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The kustomize feature that I found out about too late.]]></title>
            <link>https://medium.com/@magelan09/the-kustomize-feature-that-i-found-out-about-too-late-65bec9be5647?source=rss-dcaa4a6adc6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/65bec9be5647</guid>
            <dc:creator><![CDATA[Sergii Bieliaievskyi]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 15:04:11 GMT</pubDate>
            <atom:updated>2025-10-27T15:04:11.556Z</atom:updated>
            <content:encoded><![CDATA[<p>How many things are hidden, even though they definitely have to be somewhere in the official documentation. It’s mind-blowing. One of these things I discovered recently, even though it has been available for the last 3–4 years.</p><p>The main reason that motivates us to seek a solution is a very specific case. This is exactly what happened to me recently. The most common and widely used <strong>Kustomization</strong> use-case is the “<strong>overlay</strong>”. You would typically want to use an overlay when you have a base manifest and multiple environments. By applying patches to the base, you create different variations of it, like, for example, development, production etc. I am no exception. I also actively use overlays. Once, I needed to remove some objects from an overlay for a fresh environment. I could not just delete them, because they would also be deleted from all existing environments. So, how can we achieve that without affecting the old environments? The answer is “$patch: delete”.</p><p>I found nothing in the official documentation and I asked google. There, I stumbled across the github issue: <a href="https://github.com/kubernetes-sigs/kustomize/issues/5249">https://github.com/kubernetes-sigs/kustomize/issues/5249</a>. It made my day. Because I am not the only one who suffer without that feature and the fact that I finally know what to do.</p><p>This is how it works.</p><pre>overlay-test<br>├── base<br>│   ├── configmap-del.yaml<br>│   ├── configmap.yaml<br>│   └── kustomization.yaml<br>└── development<br>    ├── kustomization.yaml<br>    └── patch-configmap.yaml</pre><p>base/configmap.yaml</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: test-configmap<br>data:<br>  env_dir: base #&lt;--- ENV</pre><p>base/configmap-del.yaml</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: redundant-configmap<br>data:<br>  key: value</pre><p>base/kustomization.yaml</p><pre>resources:<br>- configmap.yaml</pre><p>development/patch-configmap.yaml</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: test-configmap<br>data:<br>  env_dir: development #&lt;--- ENV</pre><p>development/kustomization.yaml without “<strong>patch:delete</strong>”</p><pre>apiVersion: kustomize.config.k8s.io/v1beta1<br>kind: Kustomization<br><br>resources:<br>- ../base<br><br>patches:<br>- path: patch-configmap.yaml<br>  target:<br>    name: test-configmap</pre><p>kustomize build .</p><pre>apiVersion: v1<br>data:<br>  key: value<br>kind: ConfigMap<br>metadata:<br>  name: redundant-configmap<br>---<br>apiVersion: v1<br>data:<br>  env_dir: development<br>kind: ConfigMap<br>metadata:<br>  name: test-configmap</pre><p>development/kustomization.yaml with “<strong>patch:delete</strong>”</p><pre>apiVersion: kustomize.config.k8s.io/v1beta1<br>kind: Kustomization<br><br>resources:<br>- ../base<br><br>patches:<br>- path: patch-configmap.yaml<br>  target:<br>    name: test-configmap<br>- patch: |-<br>    $patch: delete<br>    apiVersion: v1<br>    kind: ConfigMap<br>    metadata:<br>      name: redundant-configmap</pre><p>kustomize build .</p><pre>apiVersion: v1<br>data:<br>  env_dir: development<br>kind: ConfigMap<br>metadata:<br>  name: test-configmap</pre><p>If you use Kustomize and you haven’t used “patch: delete” yet, just wait — sooner or later you’ll need it, probably when you least expect it.</p><p><em>If I may, I’d like to ask all readers to support my open-source GitHub project, Kubecui, by giving it a star. Even a small action from you means a lot to me.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zHnAFzAWIwatROJf.png" /></figure><p><a href="https://github.com/pymag09/kubecui">GitHub - pymag09/kubecui: Simple but still extremely powerful K9S alternative. An interactive `explain` command. Security scanning based on `trivy`. Supports multiple envs. Midnight commander like interface. Custom hotkeys</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65bec9be5647" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Notes to Action: Optimizing CI/CD with a Practical Checklist. [ Updated ]]]></title>
            <link>https://medium.com/@magelan09/from-notes-to-action-optimizing-ci-cd-with-a-practical-checklist-7559b7bb8515?source=rss-dcaa4a6adc6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7559b7bb8515</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Sergii Bieliaievskyi]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 08:52:50 GMT</pubDate>
            <atom:updated>2025-02-13T09:36:57.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-zTi1DH2eVN2JAB5" /><figcaption>Photo by <a href="https://unsplash.com/@thisisengineering?utm_source=medium&amp;utm_medium=referral">ThisisEngineering</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of my good habits is storing information I come across on the internet, which is potentially interesting for me and I can benefit from it in the future. But the opposite, the bad side of the habit is collected information rarely used again. CI/CD happens to be one of the heaviest categories in my notes . If I were to summarize the information in this category, it would probably be my attempt to answer a single, practical question: What is the best CI/CD pipeline? Unfortunately you won’t find the secret recipe of the best pipeline here. But what you will find instead, is the checklist I ended up creating based on my notes and some books.</p><p><strong><em>[ SCROLL DOWN DIRECTLY TO THE LIST, IF YOU DON’T WANT TO READ THE WHOLE ARTICLE ]</em></strong></p><p>This is not my expert opinion — absolutely not. A random question about CI/CD can still easily slip the ground out from under my feet. So, feel free to share your thoughts in the comment section, if you see any misconceptions.</p><p><em>If you’re enjoying this content or find it valuable, don’t forget to hit that </em><strong><em>Follow</em></strong><em> button and give it a </em><strong><em>clap</em></strong><em>! Your support keeps this going and helps bring more great insights your way!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*Y2-pW53Xpe6Zf19YapAe5g.gif" /></figure><p><em>I would be even more grateful if you could give my open-source GitHub project a star.</em></p><p><a href="https://github.com/pymag09/kubecui">GitHub - pymag09/kubecui: Simple but still extremely powerful K9S alternative. An interactive `explain` command. Security scanning based on `trivy`. Supports multiple envs. Midnight commander like interface. Custom hotkeys</a></p><h4><strong>Value Stream Mapping is nonsense. </strong>I never took it seriously. But then I changed my mind!</h4><p>When I need to change existing pipeline or design a new one, my brain starts connecting puzzles. Quickly it becomes too complex to remember all the details and I “save” a picture on paper to free up my human ‘RAM’. I suddenly realized that I was using Value Stream Mapping (VSM) all the time without even knowing. VSM is a technique of Lean manufacturing used to help identify product line waste and bottlenecks. In modern world we use it in software development nevertheless it was initially created for manufacturing. Looking at a CI/CD pipeline as if it were a factory line changed my perception. Now, it’s no longer something ephemeral like before — I can draw it on a sheet of paper, making it more tangible. Although true VSM flourish when used properly, I believe I can also benefit from its limit implementation. <strong>Gene Kim,</strong> in <em>the Devops Handbook,</em> defines two types of measurements: Lead time and Process time</p><blockquote>In the Lean community, lead time is one of two measures commonly used to measure performance in value streams, with the other being processing time. Whereas the lead time clock starts when the request is made and ends when it is fulfilled, the process time clock starts only when we begin work on the customer request — specifically, it omits the time that the work is in queue, waiting to be processed.</blockquote><p>Why couldn’t I start my “Process time” from the first commit, even though I believe the “Process time” has a bit broader implementation? Sorry <strong>Gene</strong>.</p><p><strong>Commit</strong> -&gt; <strong>Build</strong> -&gt; <strong>Test</strong> -&gt; <strong>Deploy</strong>.</p><p>Even though it is far from a comprehensive CI/CD pipeline, it is good base — skeleton for almost all pipelines.</p><h4><strong>The move toward advanced pipeline.</strong></h4><p>The skeleton above, gives us no clues on what steps comprise each stage and when stages have to be triggered (except the commit stage, it’s obvious that git commit triggers the stage). Let’s assume we are building a pipeline for a Java project. We commit to a Git server and agreed on using GitHub Flow.</p><p><strong>Briefly</strong>. GitHub Flow is a branch strategy that allows short-lived feature branches, which are regularly merged into the main branch through Merge Requests.</p><p>Further pipeline evolution, beyond the base, is hardly possible without clarifying details. We have enough now to sketch preliminary version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Mrv_542hwsIvAhY1-p45w.png" /></figure><p>The pipeline has evolved significantly. Now it’s full of necessary details.</p><p>I have the impression that very few teams use pure flows whether it’s Git Flow, GitHub Flow or Trunk-Base Development. There is alway space for variability and engineers take advantage of this freedom. Going further, we should also take into consideration the case of a pipeline being solid or CI is separated from CD, GitOps, promotion artifacts between environments. Maybe there is nothing wrong with it. If a pipeline delivers value, we are free to make any freaky pipeline modifications. At least this is a strong argument in any discussion if somebody is going to critique decisions you made.</p><h4>Continuous improvement.</h4><p>The situation we are in, may differ depends on project’s maturity. However regardless of the project being greenfield or brownfield, we need to regularly review and assess the pipeline. I started making notes long time ago, so I searched my notes, plus I run over the books <strong>The DevOps Handbook</strong> by Gene Kim, <strong>Continuous Delivery</strong> by Jez Humble. I was looking for any practical recommendations and best practices which I can use to evaluate whether a pipeline, so to speak, “good” or “bad”. Here is what I ended up having in the end.</p><h4>The checklist.</h4><ul><li><strong>Are all steps in your CI/CD pipeline fully automated, from code commit to deployment?</strong><br>Automation eliminates manual errors, speeds up delivery, and ensures consistency. Examples include automating build, test, deployment, and infrastructure provisioning processes.</li><li><strong>Is the pipeline capable of automatically triggering builds and tests upon code changes?</strong><br>Automatically triggering builds ensures immediate feedback for developers, reducing delays. Tools like GitHub Actions or Jenkins can listen for code changes and initiate builds automatically.</li><li><strong>Can the pipeline handle parallel processing for efficiency?</strong><br>Parallel processing (e.g., running multiple tests or builds simultaneously) speeds up pipeline execution, ensuring quicker feedback and faster deployments.</li><li><strong>Does the pipeline include automated smoke tests to verify basic functionality after every deployment?</strong><br>Smoke tests validate essential workflows (e.g., login, registration) to ensure the application functions properly post-deployment. These tests help catch critical issues early.</li><li><strong>Is the pipeline definition itself managed as code (e.g., Jenkinsfile, YAML)?</strong><br>Managing pipeline definitions as code enables version control, collaboration, and easy replication of pipelines. Changes are traceable, reviewable, and reusable.</li><li><strong>Are unit tests, integration tests, and acceptance tests automated?</strong><br>Automating tests at all levels ensures comprehensive validation of functionality, interactions, and end-user workflows. This reduces the risk of regressions and accelerates feedback loops.</li><li><strong>Does the pipeline follow a “test pyramid” structure, with a focus on fast and reliable tests?</strong><br>The test pyramid prioritizes unit tests (fast, small scope), followed by integration tests (medium scope), and finally end-to-end tests (comprehensive but slower). This structure ensures efficient testing.</li><li><strong>Are non-functional tests (e.g., capacity, performance) integrated into the pipeline?</strong><br>Non-functional tests assess aspects like scalability and performance under load. Integrating these into the pipeline ensures the system meets requirements for real-world scenarios. Although such tests are always crucial part of any pipeline, we have to consider running them as a separate pipeline when they will not interfere with the main pipeline tests. Furthermore, performance tests usually requires significant amount of time and resources which inevitable slows down the main pipeline.</li><li><strong>Are security tests integrated into the pipeline to detect vulnerabilities in dependencies, third-party libraries, and configurations?</strong><br>Security tests catch vulnerabilities early by scanning code, configurations, and dependencies. Tools like dependency-check, Snyk or OWASP ZAP can automate this step.</li><li><strong>Is secrets management implemented using appropriate tools and techniques?</strong><br>Proper secrets management prevents sensitive information (e.g., API keys, passwords) from being hardcoded or exposed. Use tools like HashiCorp Vault or AWS Secrets Manager etc.</li><li><strong>Does the pipeline support safe deployment strategies, such as Blue-Green Deployments or Canary Releases?</strong><br>Safe deployment strategies ensure minimal downtime and reduce the impact of issues during deployments by gradually rolling out changes.</li><li><strong>Is rollback or roll-forward implemented for failed deployments?</strong><br>Rollback reverts to a previous stable version, while roll-forward fixes the issue in the current version. Both ensure quick recovery during failures.</li><li><strong>Is automated rollback triggered based on monitoring alerts? (like for example it’s implemented in Argo Rollouts)</strong><br>Automated rollback uses real-time monitoring to detect critical issues (e.g., high error rates) and automatically reverts to the last stable version.</li><li><strong>Are database migrations automated and versioned?</strong><br>Automating and versioning database migrations ensures schema changes are consistent across environments and easy to roll back if needed.</li><li><strong>Are logs and metrics collected and analyzed continuously?</strong><br>Continuous log and metric analysis (e.g., using ELK Stack/Loki or Prometheus) provides visibility into pipeline health and identifies issues in real time.</li><li><strong>Are failures or issues in any phase of the pipeline flagged and reported in real-time?</strong><br>Real-time notifications (e.g., via Slack or email) ensure teams can respond to issues promptly, minimizing downtime or disruptions.</li><li><strong>Are release metrics and deployment frequency tracked to assess pipeline health?</strong><br>Metrics like deployment frequency, lead time, and mean time to recovery (MTTR) measure the pipeline’s efficiency and reliability.</li><li><strong>Can you reproduce any previous state of the software and infrastructure?</strong><br>Version-controlled infrastructure and code ensure you can recreate any application state to debug or roll back.</li><li><strong>Is the same build artifact promoted across all environments? </strong>A<em> </em>common mistake is rebuilding the application at each stage, which can introduce inconsistencies. Instead, generate a single build artifact and promote it through the pipeline. This ensures that all previous tests are valid and that the artifact deployed to production is identical to what was tested.</li><li><strong>Are changes traceable, with clear documentation of who made changes and why?</strong><br>Version control and commit messages provide a history of changes, helping teams understand and audit modifications.</li><li><strong>Is absolutely everything, including test scripts and environment configurations, maintained in version control?</strong><br>Storing all artifacts (code, configs, tests) in version control ensures consistency, reproducibility, and easy collaboration.</li><li><strong>Is the time from code commit to deployment sufficiently short to enable rapid iteration?</strong><br>Short feedback loops enable faster delivery of features and fixes, improving team productivity and business responsiveness.</li><li><strong>Is there a “stop the line” culture when builds or deployments fail?</strong><br>A stop-the-line culture prioritizes resolving failures immediately, ensuring quality is maintained and preventing compounding issues.</li><li><strong>Are you able to easily add new tools, tests, or steps as needed?</strong><br>Flexible pipelines allow teams to integrate new tools or processes without significant rework, ensuring adaptability to evolving needs.</li></ul><p><strong>Infrastructure as Code addition.</strong></p><p>One of the pillars, the DevOps movement is standing on is automation. From this point of view it doesn’t really matter whether it’s an application or infra pipeline. Here are some questions we may ask ourself in regards to Infrastructure as Code. At least this is what I found in my notes and books.</p><ol><li>Are environments (test, staging, production) automatically provisioned and identical?</li><li>Are Infrastructure as Code (IaC) practices followed using tools such as Docker, Terraform, or Kubernetes?</li><li>Are environment-specific configurations managed systematically and reproducible?</li><li>Are strategies in place to detect and fix configuration drift across environments?</li></ol><h4>The final words.</h4><p>It had to be a rote clean-up task, I usually do from time to time. However, CI/CD category was the biggest and the most chaotic. Well-known fact — the bigger task is the lower your motivation. Well. I am glad I came over the mental barrier.<br>Because of immense diversity it will be hard or even impossible to create the checklist which will cover all possible cases, and probably we don’t need to. There are basic principles and best-practices which were tested and proved their potency. All this CI/CD stuff was created to help business deliver high quality product faster. Any extension beyond best practices should reinforce — not hinder — the core goal of delivering high-quality software efficiently.</p><p>Thank you for reading till the end and looking forward to your thoughts in the comment section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7559b7bb8515" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Crossplane Fits into the IaC World Dominated by Terraform]]></title>
            <link>https://medium.com/@magelan09/how-crossplane-fits-into-the-iac-world-dominated-by-terraform-5a1b55ba590d?source=rss-dcaa4a6adc6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a1b55ba590d</guid>
            <category><![CDATA[crossplane]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[iac]]></category>
            <dc:creator><![CDATA[Sergii Bieliaievskyi]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 09:04:40 GMT</pubDate>
            <atom:updated>2024-06-11T09:04:40.205Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This article is not a step by step instruction. Writing this text, I assume that readers got themselves familiar with Crossplane official documentation.</blockquote><p>Frequently, on the internet, I come across the opinion that Crossplane is not mature enough to be used in production. I cannot confirm or debunk that statement. But I am ready to start an experiment at the end of which I will decide which group to join — the group of haters or the group of fans.</p><p><em>Subscribe me if you want to know what will be the outcome of the experiment.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*Y2-pW53Xpe6Zf19YapAe5g.gif" /></figure><p><em>If I may, I’d like to ask all readers to support my open-source GitHub project, Kubecui, by giving it a star. Even a small action from you means a lot to me.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7YRUJAyqkCp9srvaEkZDXA.png" /></figure><p><a href="https://github.com/pymag09/kubecui">GitHub - pymag09/kubecui: Simple but still extremely powerful K9S alternative. An interactive `explain` command. Security scanning based on `trivy`. Supports multiple envs. Midnight commander like interface. Custom hotkeys</a></p><p>Being able to manage cloud resources, such as AWS EC2 and Route53, as if they were Kubernetes objects sounds extremely attractive to me. Wouldn’t it be great to deploy an app and its underlying infrastructure in a single run? This is also interesting in the context of my previous publication.</p><p><a href="https://medium.com/@magelan09/helm-how-to-create-reusable-modules-from-helm-templates-my-mom-said-that-i-am-a-platform-engineer-9bd8b294ff62">Helm: How to create reusable modules from Helm templates. My mom said that I am a Platform Engineer</a></p><p>Platform Engineers will appreciate the ability to incorporate the infrastructure into the Helm library.</p><h4>My plan.</h4><p>One of the recent article I wrote was about External-DNS.</p><p><a href="https://medium.com/@magelan09/external-dns-route53-cross-account-update-from-jira-ticket-to-an-article-2acac06aac0e">External-DNS. Route53 — cross-account update. From JIRA ticket to an article</a></p><p>Before Crossplane, deploying External-DNS was a two-step operation:</p><ol><li>Create IAM role either manually or with Terraform</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*G5PQELkY8CA1N0YKYS0sRg.png" /></figure><p>2. run helm install …</p><p>With Crossplane, we can do it in one step.</p><h4>Crossplane. Ready! Steady! GO!</h4><p>I went through several cycles of emotional ups and downs, before realizing that achieving the same results as with Terraform requires delving deeper than the official documentation. This led me to functions and the pipeline. I suggest we briefly touch installation and initial configuration part and then focus our attention on the pipeline.</p><h4>Installation.</h4><p>Follow the installation instructions from the <a href="https://docs.crossplane.io/v1.16/software/install/">official documentation</a>. Make sure that the “<strong>default</strong>” <strong>providerconfigs.aws.upbound.io </strong>spec section contains:</p><pre>apiVersion: aws.upbound.io/v1beta1<br>kind: ProviderConfig<br>metadata:<br>  name: default<br>spec:<br>  credentials:<br>    source: IRSA</pre><p>Create an IAM role which Crossplane can use to manage external resources. Map the role to service accounts. This role could have admin access (<strong>arn:aws:iam::aws/AdministratorAccess</strong>) or a custom policy with limited access.</p><pre>apiVersion: pkg.crossplane.io/v1beta1<br>kind: DeploymentRuntimeConfig<br>metadata:<br>  name: default<br>spec:<br>  serviceAccountTemplate:<br>    metadata:<br>      annotations:<br>        eks.amazonaws.com/role-arn: arn:aws:iam::000000000:role/RoleName</pre><p>Once this is done, proceed to install the providers and functions.</p><p><a href="https://marketplace.upbound.io/providers/upbound/provider-aws-iam/v1.5.0">provider-aws-iam</a>, <a href="https://marketplace.upbound.io/functions/crossplane-contrib/function-shell/v0.1.0">function-shell</a>, <a href="https://marketplace.upbound.io/functions/crossplane-contrib/function-go-templating/v0.4.1">function-go-templating</a>, <a href="https://marketplace.upbound.io/functions/crossplane-contrib/function-auto-ready/v0.2.1">function-auto-ready</a>, <a href="https://marketplace.upbound.io/functions/crossplane-contrib/function-environment-configs/v0.0.7">function-environment-configs</a></p><pre>---<br>apiVersion: pkg.crossplane.io/v1<br>kind: Provider<br>metadata:<br>  name: upbound-provider-aws-iam<br>spec:<br>  package: xpkg.upbound.io/upbound/provider-aws-iam:v1.4.0<br>---<br>apiVersion: pkg.crossplane.io/v1beta1<br>kind: Function<br>metadata:<br>  name: crossplane-contrib-function-auto-ready<br>spec:<br>  package: xpkg.upbound.io/crossplane-contrib/function-auto-ready:v0.2.1<br>---<br>apiVersion: pkg.crossplane.io/v1beta1<br>kind: Function<br>metadata:<br>  name: crossplane-contrib-function-environment-configs<br>spec:<br>  package: xpkg.upbound.io/crossplane-contrib/function-environment-configs:v0.0.7<br>---<br>apiVersion: pkg.crossplane.io/v1beta1<br>kind: Function<br>metadata:<br>  name: crossplane-contrib-function-go-templating<br>spec:<br>  package: xpkg.upbound.io/crossplane-contrib/function-go-templating:v0.4.1<br>---<br>apiVersion: pkg.crossplane.io/v1beta1<br>kind: Function<br>metadata:<br>  name: function-shell<br>spec:<br>  package: xpkg.upbound.io/crossplane-contrib/function-shell:v0.1.0<br></pre><h4>The pipeline.</h4><p>“Pipeline” and “Resources” are two modes of a Crossplane Composition. While I was reading the documentation I thought that “Resources” was the preferable mode. However, it’s not true and here is why…</p><p>I was considering delegating a small portion of IaC from Terraform to Crossplane. Ultimately, 99.9% of the resources remain managed by HashiCorp’s tool. To assert that both tools offer the same level of resource management, we need to ensure we can reference resources, use loops and conditions. The simple question “how can I reference resources created by Terraform” emerges immediately. This is where functions become handy.</p><p>There are two options recommended by Crossplane creators:</p><ul><li>Use existing function (<a href="https://marketplace.upbound.io/functions">https://marketplace.upbound.io/functions</a>)</li><li>Write function using Python or GO language, make it available on the Upbound marketplace.</li></ul><p>and one <strong>workaround,</strong> which I end up using. I will explain it later in the article. But now let’s focus on the pipeline.</p><pre>apiVersion: apiextensions.crossplane.io/v1<br>kind: Composition<br>metadata:<br>  name: iam-roles.mycompany.com<br>spec:<br>  compositeTypeRef:<br>    apiVersion: aws.mycompany.com/v1<br>    kind: ClusterIamRoleCommon<br>  mode: Pipeline<br>  pipeline:<br>    #<br>    # Global variables.<br>    #<br>    - step: environmentConfigs<br>      functionRef:<br>        name: crossplane-contrib-function-environment-configs<br>      input:<br>        apiVersion: environmentconfigs.fn.crossplane.io/v1beta1<br>        kind: Input<br>        spec:<br>          environmentConfigs:<br>            - type: Reference<br>              ref:<br>                name: global-env<br>    #<br>    # Get AWS account ID and store the values in the varible<br>    #<br>    - step: get_account_id<br>      functionRef:<br>        name: crossplane-contrib-function-shell<br>      input:<br>        apiVersion: shell.fn.crossplane.io/v1alpha1<br>        kind: Parameters<br>        shellCommand: |<br>           aws sts get-caller-identity --query &quot;Account&quot; --output text || exit 0<br>        stdoutField: status.atFunction.shell.accountid<br>        stderrField: status.atFunction.shell.stderr<br>    #<br>    # Get EKS cluster ID and store the values in the varible<br>    #<br>    - step: get_account_eksid<br>      functionRef:<br>        name: crossplane-contrib-function-shell<br>      input:<br>        apiVersion: shell.fn.crossplane.io/v1alpha1<br>        kind: Parameters<br>        shellCommand: |<br>           aws eks describe-cluster --name &lt;CLUSTER_NAME&gt; --query &quot;cluster.endpoint&quot; --output text | sed -r &#39;s|https://([0-9A-F]+)\..*|\1|&#39; || exit 0<br>        stdoutField: status.atFunction.shell.eksid<br>        stderrField: status.atFunction.shell.stderr<br>    #<br>    # Create role, policy and role attachment using stored variables from previous steps<br>    #<br>    - step: role_template<br>      functionRef:<br>        name: crossplane-contrib-function-go-templating<br>      input:<br>        apiVersion: gotemplating.fn.crossplane.io/v1beta1<br>        kind: GoTemplate<br>        source: Inline<br>        inline:<br>          template: |<br>            ---<br>            apiVersion: iam.aws.upbound.io/v1beta1<br>            kind: Role<br>            metadata:<br>              name: {{ .observed.composite.resource.spec.name }}<br>              annotations:<br>                gotemplating.fn.crossplane.io/composition-resource-name: {{ .observed.composite.resource.spec.name }}-role<br>              labels:<br>                module: iamCommon<br>                obj: role<br>            spec:<br>              forProvider:<br>                assumeRolePolicy: |<br>                  {{- if regexMatch &quot;(?:lambda|ec2|root)&quot; .observed.composite.resource.spec.forPrincipal }}<br>                  {<br>                    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>                    &quot;Statement&quot;: [<br>                        {<br>                          &quot;Effect&quot;: &quot;Allow&quot;,<br>                          &quot;Action&quot;: [<br>                              &quot;sts:AssumeRole&quot;<br>                          ],<br>                          &quot;Principal&quot;: {<br>                              {{- if regexMatch &quot;(?:lambda|ec2)&quot; .observed.composite.resource.spec.forPrincipal }}<br>                              &quot;Service&quot;: [<br>                              {{- end }}<br>                              {{- if eq .observed.composite.resource.spec.forPrincipal &quot;root&quot; }}<br>                              &quot;AWS&quot;: [<br>                              {{- end }}<br>                                  {{- if eq .observed.composite.resource.spec.forPrincipal &quot;lambda&quot; }}<br>                                  &quot;lambda.amazonaws.com&quot;<br>                                  {{- end }}<br>                                  {{- if eq .observed.composite.resource.spec.forPrincipal &quot;ec2&quot; }}<br>                                  &quot;ec2.amazonaws.com&quot;<br>                                  {{- end }}<br>                                  {{- if eq .observed.composite.resource.spec.forPrincipal &quot;root&quot; }}<br>                                  &quot;arn:aws:iam::{{ .observed.composite.resource.status.atFunction.shell.accountid }}:root&quot;<br>                                  {{- end }}<br>                              ]<br>                          }<br>                        }<br>                      ]<br>                  }<br>                  {{- end }}<br>                  {{- if eq .observed.composite.resource.spec.forPrincipal &quot;serviceaccount&quot; }}<br>                  {<br>                      &quot;Version&quot;: &quot;2012-10-17&quot;,<br>                      &quot;Statement&quot;: [<br>                          {<br>                              &quot;Effect&quot;: &quot;Allow&quot;,<br>                              &quot;Principal&quot;: {<br>                                  &quot;Federated&quot;: &quot;arn:aws:iam::{{ .observed.composite.resource.status.atFunction.shell.accountid }}:oidc-provider/oidc.eks.{{ index .context &quot;apiextensions.crossplane.io/environment&quot; &quot;locations&quot; &quot;eu&quot; }}.amazonaws.com/id/{{ .observed.composite.resource.status.atFunction.shell.eksid }}&quot;<br>                              },<br>                              &quot;Action&quot;: &quot;sts:AssumeRoleWithWebIdentity&quot;,<br>                              &quot;Condition&quot;: {<br>                                  &quot;StringEquals&quot;: {<br>                                      &quot;oidc.eks.{{ index .context &quot;apiextensions.crossplane.io/environment&quot; &quot;locations&quot; &quot;eu&quot; }}.amazonaws.com/id/{{ .observed.composite.resource.status.atFunction.shell.eksid }}:sub&quot;: &quot;system:serviceaccount:{{ .observed.composite.resource.spec.namespace }}:{{ .observed.composite.resource.spec.serviceAccount }}&quot;<br>                                  }<br>                              }<br>                          }<br>                      ]<br>                  }<br>                  {{- end }}<br>                tags:<br>                  {{ toYaml (index .context &quot;apiextensions.crossplane.io/environment&quot; &quot;default_tags&quot;) | nindent 6 }}<br>            ---<br>            apiVersion: iam.aws.upbound.io/v1beta1<br>            kind: Policy<br>            metadata:<br>              name: {{ .observed.composite.resource.spec.name }}<br>              annotations:<br>                gotemplating.fn.crossplane.io/composition-resource-name: {{ .observed.composite.resource.spec.name }}-policy<br>              labels:<br>                module: iamCommon<br>                obj: policy<br>            spec:<br>              forProvider:<br>                policy: {{ toJson .observed.composite.resource.spec.rolePolicy }}<br>            ---<br>            apiVersion: iam.aws.upbound.io/v1beta1<br>            kind: RolePolicyAttachment<br>            metadata:<br>              name: {{ .observed.composite.resource.spec.name }}<br>              annotations:<br>                gotemplating.fn.crossplane.io/composition-resource-name: {{ .observed.composite.resource.spec.name }}-attachment<br>              labels:<br>                module: iamCommon<br>            spec:<br>              forProvider:<br>                policyArnSelector:<br>                  matchLabels:<br>                    module: iamCommon<br>                    obj: policy<br>                roleSelector:<br>                  matchLabels:<br>                    module: iamCommon<br>                    obj: role<br>    #<br>    # Marks the composite resource as ready when the resource becomes ready.<br>    #<br>      - step: resources_ready<br>        functionRef:<br>          name: crossplane-contrib-function-auto-ready</pre><p>As you can see, the pipeline is a list of steps executed sequentially from the top, down to the bottom. Steps may accept parameters and generate output to be passed to the next steps.</p><h4>Global varibales.</h4><pre>...<br><br>- step: environmentConfigs<br>  functionRef:<br>    name: crossplane-contrib-function-environment-configs<br>  input:<br>    apiVersion: environmentconfigs.fn.crossplane.io/v1beta1<br>    kind: Input<br>    spec:<br>      environmentConfigs:<br>        - type: Reference<br>          ref:<br>            name: global-env<br><br>...</pre><p>Environment, team, company name are the tags any resource, within the account, should be labeled with. Defined once, tags can be included in any Composition, avoiding multiple definitions.</p><pre>apiVersion: apiextensions.crossplane.io/v1alpha1<br>kind: EnvironmentConfig<br>metadata:<br>  name: global-env<br>data:<br>  locations:<br>    eu: eu-central-1<br>  default_tags:<br>    company: mycompany<br>    c7n: ignore<br>    environment: development</pre><h4>External resources.</h4><p>Don’t worry, I haven’t forgotten about “<strong>get_account_id</strong>”, “<strong>get_account_eksid</strong>” steps. We will get back to them right after reviewing the core of the pipeline — “<strong>role_template</strong>”.</p><pre>- step: role_template<br>  functionRef:<br>    name: crossplane-contrib-function-go-templating<br>  input:<br>    apiVersion: gotemplating.fn.crossplane.io/v1beta1<br>    kind: GoTemplate<br>    source: Inline<br>    inline:<br>      template: |<br>        ---<br>        apiVersion: iam.aws.upbound.io/v1beta1<br>        kind: Role<br>        metadata:<br>          name: {{ .observed.composite.resource.spec.name }}<br>          annotations:<br>            gotemplating.fn.crossplane.io/composition-resource-name: {{ .observed.composite.resource.spec.name }}-role<br>          labels:<br>            module: iamCommon<br>            obj: role<br>        spec:<br>          forProvider:<br>            assumeRolePolicy: |<br>              {{- if regexMatch &quot;(?:lambda|ec2|root)&quot; .observed.composite.resource.spec.forPrincipal }}<br>              {<br>                &quot;Version&quot;: &quot;2012-10-17&quot;,<br>                &quot;Statement&quot;: [<br>                    {<br>                      &quot;Effect&quot;: &quot;Allow&quot;,<br>                      &quot;Action&quot;: [<br>                          &quot;sts:AssumeRole&quot;<br>                      ],<br>                      &quot;Principal&quot;: {<br>                          {{- if regexMatch &quot;(?:lambda|ec2)&quot; .observed.composite.resource.spec.forPrincipal }}<br>                          &quot;Service&quot;: [<br>                          {{- end }}<br>                          {{- if eq .observed.composite.resource.spec.forPrincipal &quot;root&quot; }}<br>                          &quot;AWS&quot;: [<br>                          {{- end }}<br>                              {{- if eq .observed.composite.resource.spec.forPrincipal &quot;lambda&quot; }}<br>                              &quot;lambda.amazonaws.com&quot;<br>                              {{- end }}<br>                              {{- if eq .observed.composite.resource.spec.forPrincipal &quot;ec2&quot; }}<br>                              &quot;ec2.amazonaws.com&quot;<br>                              {{- end }}<br>                              {{- if eq .observed.composite.resource.spec.forPrincipal &quot;root&quot; }}<br>                              &quot;arn:aws:iam::{{ .observed.composite.resource.status.atFunction.shell.accountid }}:root&quot;<br>                              {{- end }}<br>                          ]<br>                      }<br>                    }<br>                  ]<br>              }<br>              {{- end }}<br>              {{- if eq .observed.composite.resource.spec.forPrincipal &quot;serviceaccount&quot; }}<br>              {<br>                  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>                  &quot;Statement&quot;: [<br>                      {<br>                          &quot;Effect&quot;: &quot;Allow&quot;,<br>                          &quot;Principal&quot;: {<br>                              &quot;Federated&quot;: &quot;arn:aws:iam::{{ .observed.composite.resource.status.atFunction.shell.accountid }}:oidc-provider/oidc.eks.{{ index .context &quot;apiextensions.crossplane.io/environment&quot; &quot;locations&quot; &quot;eu&quot; }}.amazonaws.com/id/{{ .observed.composite.resource.status.atFunction.shell.eksid }}&quot;<br>                          },<br>                          &quot;Action&quot;: &quot;sts:AssumeRoleWithWebIdentity&quot;,<br>                          &quot;Condition&quot;: {<br>                              &quot;StringEquals&quot;: {<br>                                  &quot;oidc.eks.{{ index .context &quot;apiextensions.crossplane.io/environment&quot; &quot;locations&quot; &quot;eu&quot; }}.amazonaws.com/id/{{ .observed.composite.resource.status.atFunction.shell.eksid }}:sub&quot;: &quot;system:serviceaccount:{{ .observed.composite.resource.spec.namespace }}:{{ .observed.composite.resource.spec.serviceAccount }}&quot;<br>                              }<br>                          }<br>                      }<br>                  ]<br>              }<br>              {{- end }}<br>            tags:<br>              {{ toYaml (index .context &quot;apiextensions.crossplane.io/environment&quot; &quot;default_tags&quot;) | nindent 6 }}<br>        ---<br>        apiVersion: iam.aws.upbound.io/v1beta1<br>        kind: Policy<br>        metadata:<br>          name: {{ .observed.composite.resource.spec.name }}<br>          annotations:<br>            gotemplating.fn.crossplane.io/composition-resource-name: {{ .observed.composite.resource.spec.name }}-policy<br>          labels:<br>            module: iamCommon<br>            obj: policy<br>        spec:<br>          forProvider:<br>            policy: {{ toJson .observed.composite.resource.spec.rolePolicy }}<br>        ---<br>        apiVersion: iam.aws.upbound.io/v1beta1<br>        kind: RolePolicyAttachment<br>        metadata:<br>          name: {{ .observed.composite.resource.spec.name }}<br>          annotations:<br>            gotemplating.fn.crossplane.io/composition-resource-name: {{ .observed.composite.resource.spec.name }}-attachment<br>          labels:<br>            module: iamCommon<br>        spec:<br>          forProvider:<br>            policyArnSelector:<br>              matchLabels:<br>                module: iamCommon<br>                obj: policy<br>            roleSelector:<br>              matchLabels:<br>                module: iamCommon<br>                obj: role</pre><p>You are familiar with GO templates if you’ve ever worked with Helm. Why GO templates? They offer a convenient way for looping, if statements, and variable referencing. Using these template constructions, I created a reusable piece of code. The template below, generates assume policy for the role. The policy differs depending on the Principal (ec2, lambda, root or service account).</p><pre>{{- if regexMatch &quot;(?:lambda|ec2|root)&quot; .observed.composite.resource.spec.forPrincipal }}<br>  {<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>          &quot;Effect&quot;: &quot;Allow&quot;,<br>          &quot;Action&quot;: [<br>              &quot;sts:AssumeRole&quot;<br>          ],<br>          &quot;Principal&quot;: {<br>              {{- if regexMatch &quot;(?:lambda|ec2)&quot; .observed.composite.resource.spec.forPrincipal }}<br>              &quot;Service&quot;: [<br>              {{- end }}<br>              {{- if eq .observed.composite.resource.spec.forPrincipal &quot;root&quot; }}<br>              &quot;AWS&quot;: [<br>              {{- end }}<br>                  {{- if eq .observed.composite.resource.spec.forPrincipal &quot;lambda&quot; }}<br>                  &quot;lambda.amazonaws.com&quot;<br>                  {{- end }}<br>                  {{- if eq .observed.composite.resource.spec.forPrincipal &quot;ec2&quot; }}<br>                  &quot;ec2.amazonaws.com&quot;<br>                  {{- end }}<br>                  {{- if eq .observed.composite.resource.spec.forPrincipal &quot;root&quot; }}<br>                  &quot;arn:aws:iam::{{ .observed.composite.resource.status.atFunction.shell.accountid }}:root&quot;<br>                  {{- end }}<br>              ]<br>          }<br>        }<br>      ]<br>  }<br>  {{- end }}<br>  {{- if eq .observed.composite.resource.spec.forPrincipal &quot;serviceaccount&quot; }}<br>  {<br>      &quot;Version&quot;: &quot;2012-10-17&quot;,<br>      &quot;Statement&quot;: [<br>          {<br>              &quot;Effect&quot;: &quot;Allow&quot;,<br>              &quot;Principal&quot;: {<br>                  &quot;Federated&quot;: &quot;arn:aws:iam::{{ .observed.composite.resource.status.atFunction.shell.accountid }}:oidc-provider/oidc.eks.{{ index .context &quot;apiextensions.crossplane.io/environment&quot; &quot;locations&quot; &quot;eu&quot; }}.amazonaws.com/id/{{ .observed.composite.resource.status.atFunction.shell.eksid }}&quot;<br>              },<br>              &quot;Action&quot;: &quot;sts:AssumeRoleWithWebIdentity&quot;,<br>              &quot;Condition&quot;: {<br>                  &quot;StringEquals&quot;: {<br>                      &quot;oidc.eks.{{ index .context &quot;apiextensions.crossplane.io/environment&quot; &quot;locations&quot; &quot;eu&quot; }}.amazonaws.com/id/{{ .observed.composite.resource.status.atFunction.shell.eksid }}:sub&quot;: &quot;system:serviceaccount:{{ .observed.composite.resource.spec.namespace }}:{{ .observed.composite.resource.spec.serviceAccount }}&quot;<br>                  }<br>              }<br>          }<br>      ]<br>  }<br>  {{- end }}<br>tags:<br>  {{ toYaml (index .context &quot;apiextensions.crossplane.io/environment&quot; &quot;default_tags&quot;) | nindent 6 }}<br></pre><p>The role is labeled with global tags, that we made available through the pipeline environment. You’ve seen different ways of referencing variables in the template. There are two more notations in addition to those you’ve seen in the template. Here is the complete list:</p><pre><br>{{ .observed.composite.resource.metadata.name }}<br>{{ index .context &quot;apiextensions.crossplane.io/environment&quot; }}<br><br>{{ .desired.composite.resource.status.widgets }}<br>{{ (index .desired.composed &quot;resource-name&quot;).resource.spec.widgets }}<br></pre><h4>“get_account_id” and “get_account_eksid”</h4><p>This is how assume policy looks when the “Principal” is a service account:</p><pre>{<br>      &quot;Version&quot;: &quot;2012-10-17&quot;,<br>      &quot;Statement&quot;: [<br>          {<br>              &quot;Effect&quot;: &quot;Allow&quot;,<br>              &quot;Principal&quot;: {<br>                  &quot;Federated&quot;: &quot;arn:aws:iam::&lt;AWS_ACCOUNT_ID&gt;:oidc-provider/oidc.eks.&lt;EKS_CLUSTER_ID&gt;&quot;<br>              },<br>              &quot;Action&quot;: &quot;sts:AssumeRoleWithWebIdentity&quot;,<br>              &quot;Condition&quot;: {<br>                  &quot;StringEquals&quot;: {<br>                      &quot;oidc.eks.&lt;REGION&gt;.amazonaws.com/id/&lt;EKS_CLUSTER_ID&gt;:sub&quot;: &quot;system:serviceaccount:&lt;NAMESPACE&gt;:&lt;SERVICE_ACCOUNT&gt;&quot;<br>                  }<br>              }<br>          }<br>      ]<br>  }</pre><p>It’s obvious that the resource created by Crossplane can be referenced anywhere within Crossplane. It’s time to answer the question of whether we are able to reference resources created somewhere else. And the answer is YES.</p><p>Anyone can get needed information by executing aws CLI commands from their laptops. Why can’t we run such command in the pipeline? Actually we can:</p><pre>#<br># Get AWS account ID and store the values in the varible<br>#<br>- step: get_account_id<br>  functionRef:<br>    name: crossplane-contrib-function-shell<br>  input:<br>    apiVersion: shell.fn.crossplane.io/v1alpha1<br>    kind: Parameters<br>    shellCommand: |<br>       aws sts get-caller-identity --query &quot;Account&quot; --output text || exit 0<br>    stdoutField: status.atFunction.shell.accountid<br>    stderrField: status.atFunction.shell.stderr<br>#<br># Get EKS cluster ID and store the values in the varible<br>#<br>- step: get_account_eksid<br>  functionRef:<br>    name: crossplane-contrib-function-shell<br>  input:<br>    apiVersion: shell.fn.crossplane.io/v1alpha1<br>    kind: Parameters<br>    shellCommand: |<br>       aws eks describe-cluster --name &lt;CLUSTER_NAME&gt; --query &quot;cluster.endpoint&quot; --output text | sed -r &#39;s|https://([0-9A-F]+)\..*|\1|&#39; || exit 0<br>    stdoutField: status.atFunction.shell.eksid<br>    stderrField: status.atFunction.shell.stderr</pre><p>We already know that steps accept parameters and return output. But what does happen to the output afterwards? How can we access it? Roughly speaking there is a “buffer” where we can store information.</p><p>“Confused about Compositions, XRDs, XRs and Claims?” is the question you will come across many times, while reading the official documentation. Indeed, in the beginning, it might be confusing. But it’s important to sort everything out at an earlier stages, because it’s the key to understanding, the so-called, buffer.</p><h4>Compositions.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*MVJMfdYEqVioXvPW87SfQg.png" /></figure><p>Let’s try to decompose the composition. An IAM role comprise three resources.</p><ul><li>The role.</li><li>The policy.</li><li>The Role/Policy association.</li></ul><p>They are “<strong>External resources</strong>”. “<strong>Managed resource — MR</strong>” is a definition of “<strong>External resource</strong>”. “<strong>Composition”</strong>, is a collection of multiple “<strong>Managed resources</strong>”. If it helps, think about Composition as a “Docker Compose” YAML file. In order to turn a static “Composition” into the reuseable template, we need to create “<strong>Composition Resource Definition- XRD</strong>”. The object created from the <strong>XRD (Composition Resource Definition) </strong>is called an <strong>XR. </strong>It was a long journey but we’ve made it to the point where I can say <strong>XR</strong> is our “buffer”. The output is stored in the <strong>XR</strong>s status field.</p><pre>stdoutField: status.atFunction.shell.XXXXXX<br>stderrField: status.atFunction.shell.stderr</pre><p>And to make it clear even more, here is <strong>XRD </strong>of<strong> XR:</strong></p><pre>apiVersion: apiextensions.crossplane.io/v1<br>kind: CompositeResourceDefinition<br>metadata:<br>  name: clusteriamrolescommon.aws.home-lab.com<br>spec:<br>  group: aws.home-lab.com<br>  names:<br>    kind: ClusterIamRoleCommon<br>    plural: clusteriamrolescommon<br>    shortNames:<br>    - cirsc<br>  claimNames:<br>    kind: IamRole<br>    plural: iamroles<br>    shortNames:<br>    - ir<br>  versions:<br>  - name: v1<br>    served: true<br>    referenceable: true<br>    schema:<br>      openAPIV3Schema:<br>        type: object<br>        properties:<br>          spec:<br>            type: object<br>            properties:<br>              namespace:<br>                type: string<br>              forPrincipal:<br>                type: string<br>              serviceAccount:<br>                type: string<br>              rolePolicy:<br>                type: string<br>              name:<br>                type: string<br>            required:<br>            - rolePolicy<br>            - name<br>            - forPrincipal<br>#<br># Status section. status.atFunction.shell.stderr<br>#<br>          status:<br>            type: object<br>            properties:<br>              atFunction:<br>                type: object<br>                x-kubernetes-preserve-unknown-fields: true</pre><h4>The workaround.</h4><p>Even if you try to reproduce the pipeline it will fail and the reason for that is absence of aws CLI in <strong>xpkg.upbound.io/crossplane-contrib/function-shell:v0.1.0</strong> image. I didn’t find a way of hosting functions inside the organization. I also didn’t want to upload dubious clone of <strong>function-shell </strong>image, to <strong>upbound.io</strong>, with the embedded aws CLI. Furthermore, you can find commented lines for aws CLI installation in Dockerfile.</p><p><a href="https://github.com/crossplane-contrib/function-shell/blob/main/Dockerfile#L16">function-shell/Dockerfile at main · crossplane-contrib/function-shell</a></p><p>We can expect the aws CLI to be part of the image soon. Meanwhile, go ahead, uncomment and build the custom image because we can not wait, we need it right now.</p><p>Functions and providers, they are just pods after all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbISts7CEtF6HqnyiGrCSw.png" /></figure><p>What if we try to change the image? Crossplane does not allow editing functions image directly; all your changes will be overwritten immediately. However here is an instruction on how to make it possible.</p><p>Using your custom image, edit and change “<strong>function-shell” </strong>related<strong> </strong>objects :</p><ul><li><strong>functions.pkg.crossplane.io</strong></li><li><strong>functionrevisions.pkg.crossplane.io</strong></li><li><strong>apps.deployment</strong></li></ul><p>Voilà — you are using custom shell function.</p><h4>Wrapping up.</h4><p>Up until now, we haven’t created a single <strong>XR</strong>.</p><pre>clusteriamrolescommon               cirsc        aws.home-lab.com/v1                           false        ClusterIamRoleCommon<br>iamroles                            ir           aws.home-lab.com/v1                           true         IamRole</pre><p><strong>XRD</strong> (CompositeResourceDefinition) tells us that we’ve defined two objects, “<strong>clusteriamrolescommon</strong>” and “<strong>iamroles</strong>” which are cluster-scoped and namespace-scoped objects respectively.</p><pre>apiVersion: apiextensions.crossplane.io/v1<br>kind: CompositeResourceDefinition<br>metadata:<br>  name: clusteriamrolescommon.aws.home-lab.com<br>spec:<br>  group: aws.home-lab.com<br>  names:<br>    kind: ClusterIamRoleCommon<br>    plural: clusteriamrolescommon<br>    shortNames:<br>    - cirsc<br>  claimNames:<br>    kind: IamRole<br>    plural: iamroles<br>    shortNames:<br>    - ir</pre><p>We want users working in different namespaces within the Kubernetes cluster to be able to create roles by applying manifests or as part of Helm releases. Here is an example:</p><pre>apiVersion: aws.home-lab.com/v1<br>kind: IamRole<br>metadata:<br>  name: crossaccountexternaldns<br>  namespace: default<br>spec:<br>  name: crossplane-crossaccount-externaldns<br>  namespace: &quot;kube-system&quot;<br>  serviceAccount: &quot;crooss-account-external-dns&quot;<br>  forPrincipal: ec2<br>  rolePolicy: |-<br>    {<br>      &quot;Statement&quot;: [<br>          {<br>              &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>              &quot;Effect&quot;: &quot;Allow&quot;,<br>              &quot;Resource&quot;: &quot;arn:aws:iam::ZZZZZZZZZ:role/EnvAccountExternalDNSRole&quot;<br>          }<br>      ],<br>      &quot;Version&quot;: &quot;2012-10-17&quot;<br>    }</pre><p>We’ve just created the composition.</p><pre>k get ir -n default</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h6j0BIkb8gXy7MjAfePhwg.png" /></figure><p>We also can check resources created by the composition:</p><pre>k get policies.iam.aws.upbound.io<br>k get rolepolicyattachments.iam.aws.upbound.io <br>k get roles.iam.aws.upbound.io</pre><h4>Final words.</h4><p>Terraform is clearly the frontrunner in IaC, but Crossplane is well-positioned to become the second most popular tool. Surprisingly, its main feature is also its biggest limitation. Until Kubernetes is universally accepted as the gold standard for IT projects, Crossplane will stay in Terraform’s shadow. But what does this mean for people who have already adopted Kubernetes? It means that we can benefit from both tools. My plan is to keep core to be managed by Terrafrom and migrate remaining resources to Crossplane. By saying core I mean:</p><ul><li>network infra (VPC, subnetes, gateways etc.)</li><li>global IAM resource, such as users, roles and polcies.</li><li>EKS clusters</li><li>Route53</li><li>Services that are global for whole organization, like Codeartifact or Elastic Container Registry</li></ul><p>and many others.</p><p><strong>Thank you! If you enjoyed my article, please consider hitting the ‘Clap’ button. I would be even more grateful if you could give my open-source GitHub project a star.</strong></p><p><a href="https://github.com/pymag09/kubecui">GitHub - pymag09/kubecui: Simple but still extremely powerful K9S alternative. An interactive `explain` command. Security scanning based on `trivy`. Supports multiple envs. Midnight commander like interface. Custom hotkeys</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a1b55ba590d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Helm: How to create reusable modules from Helm templates. My mom said that I am a Platform Engineer]]></title>
            <link>https://medium.com/@magelan09/helm-how-to-create-reusable-modules-from-helm-templates-my-mom-said-that-i-am-a-platform-engineer-9bd8b294ff62?source=rss-dcaa4a6adc6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bd8b294ff62</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[helm]]></category>
            <dc:creator><![CDATA[Sergii Bieliaievskyi]]></dc:creator>
            <pubDate>Mon, 20 May 2024 12:02:56 GMT</pubDate>
            <atom:updated>2024-05-20T12:04:07.396Z</atom:updated>
            <content:encoded><![CDATA[<p>What will happen if we suddenly make developers responsible for everything: writing code, managing Helm charts, and configuring Terraform? The answer is, it depends, but usually nothing good. The story began more than a year ago, and all that time, I was waiting for the best moment to tell it. I am writing it now, but the moment is still not the best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jH8K6b-ALr7oC3JX" /><figcaption>Photo by <a href="https://unsplash.com/@sentidoshumanos?utm_source=medium&amp;utm_medium=referral">sentidos humanos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Before we dive into the wild ride of this article, let’s give a virtual high-five and a massive shoutout to all you awesome peeps who’ve hit that ‘</em><strong><em>follow</em></strong><em>’ button on my Medium.com profile.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*KpnGsY0MucQTPNlmIJpsCQ.png" /></figure><p><em>Your support keeps the momentum going and the inspiration flowing! And to those who haven’t joined our digital tribe yet, what are you waiting for? Come on board and hit that ‘</em><strong><em>follow</em></strong><em>’ button to stay updated on all the latest content. Let’s make this journey even more epic together!”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ebLFif2sTNf5cW_y" /><figcaption>Photo by <a href="https://unsplash.com/@nixcreative?utm_source=medium&amp;utm_medium=referral">Tyler Nix</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As the title suggests, today’s article is about Helm and platform engineering. A Helm chart can be roughly divided into ‘code’ and ‘data’. To use Helm as a service, we need to integrate the ‘code’ into the self-service platform. What if I told you that a Helm chart might look like this:</p><pre>{{ include &quot;app.deployment&quot; . }}</pre><p>and still be able to create not only the ‘Deployment’ object, but also other tightly and loosely dependent objects such as ‘Service’, ‘ServiceAccount’, ‘HPA’, ‘PersistentVolumeClaim’, ‘Secrets’, and so on. From that moment, Helm will be like the near and far sides of the moon. The near side is data (values.yaml) and the one-line Helm chart (include ‘app.deployment’ .). The far side is Helm templates created by Platform Engineers. Software Engineers should not worry about scaling, correct pod scheduling (affinity, taints), disruption budgets, exposing plain-text secrets, or security best practices anymore. Additionally, it reduces waste by omitting the review of unnecessary merge requests, resulting in a reduced cycle time. (“Lean” defined seven major types of manufacturing waste: <strong>inventory, overproduction, extra processing, transportation, waiting, motion, and defects</strong>)</p><blockquote><strong>Waiting</strong>: Any delays between work requiring resources to wait until they can<br>complete the current work. Delays increase cycle time and prevent the<br>customer from getting value.</blockquote><blockquote>📙 <strong>“The DevOPS Handbook: How to Create World-Class Agility, Reliability, and Security in Technology Organizations”</strong></blockquote><p>So, what is it from a technical standpoint? When we think about Helm, we usually refer to Go templates for generating Kubernetes manifests. But there is another type of Helm chart, which is a library.</p><blockquote>A library chart is a type of Helm chart that defines chart primitives or definitions which can be shared by Helm templates in other charts. This allows users to share snippets of code that can be re-used across charts, avoiding repetition and keeping charts DRY.</blockquote><blockquote>📙 <a href="https://helm.sh/docs/topics/library_charts/#helm">https://helm.sh/docs/topics/library_charts/#helm</a></blockquote><p>We write a library, or module if you want, and store it somewhere. Then, we use it as an external dependency within a ‘traditional’ or application-type Helm chart. I won’t be talking much about Go templates, maybe just briefly. The goal is to remind that Helm is not merely a templating and packaging system. With that said, let’s delve a bit deeper.</p><p>Examples of writing a library you can find <a href="https://helm.sh/docs/topics/library_charts/#helm">here</a>. For better understanding of the Helm “<strong>include</strong>” underlying mechanisms you might need to read the article I published some time ago:</p><p><a href="https://blog.devops.dev/from-hidden-to-hero-embracing-helms-secret-weapon-go-templates-4e6227f8aae3">From Hidden to Hero: Embracing HELM’s Secret Weapon — GO Templates!</a></p><p>Well. Let’s imagine that the library is ready and we are about to use it. For a moment we need to get back to the Helm official documentation:</p><blockquote>To be able to use the common code, we need to add mylibchart as a dependency. Add the following to the end of the file mychart/Chart.yaml:<br><strong>dependencies</strong>:<br>- <strong>name</strong>: mylibchart<br> <strong>version</strong>: 0.1.0<br> <strong>repository</strong>: file://../mylibchart</blockquote><p>The documentation says: “we need to add <em>mylibchart</em> as a dependency”. Dependency definition is simple and straightforward</p><p>📌 <em>For more details please read this: </em><a href="https://helm.sh/docs/topics/charts/#the-chart-file-structure"><em>https://helm.sh/docs/topics/charts/#the-chart-file-structure</em></a><em> There you will find complete information about </em><strong><em>Chart.yaml</em></strong><em> fields, including “</em><strong><em>dependencies</em></strong><em>”.</em></p><p>However, I didn’t find any options other then <strong>http[s]://</strong> and <strong>file://</strong> Usually this not a problem if you already have or you are going to setup helm repository.</p><blockquote>The ‘repository’ URL should point to a Chart Repository. Helm expects that by appending ‘/index.yaml’ to the URL, it should be able to retrieve the chart repository’s index</blockquote><blockquote>📙 <a href="https://helm.sh/docs/helm/helm_dependency/#helm">https://helm.sh/docs/helm/helm_dependency/#helm</a></blockquote><p>But I would like to share an alternative method. I suggest keeping everything in Git. For that, we need a helm plugin: <a href="https://github.com/aslafy-z/helm-git">https://github.com/aslafy-z/helm-git</a></p><blockquote>For more information about plugin in Helm you can read</blockquote><blockquote>📙 <a href="https://helm.sh/docs/topics/plugins/#installing-a-plugin">https://helm.sh/docs/topics/plugins/#installing-a-plugin</a></blockquote><p>The plugin extends the list of the supported sources, on top of “http[s]:// “ and “file://” we also get “git+ssh://”</p><p>After the plugin has taken its place, go ahead and define all the dependencies</p><pre>dependencies:<br>  - name: deployment<br>    version: 0.6.2<br>    repository: git+ssh://git@bitbucket.in/deployment@/?ref=0.6.2&amp;sparse=0<br>  - name: ingress<br>    version: 0.4.2<br>    repository: git+ssh://git@bitbucket.in/ingress@/?ref=0.4.2&amp;sparse=0</pre><p>When I release a new version of a library, I always create a new git tag. By doing this I can reference the tag later in the URL “<strong>…?ref=0.6.2…” </strong>to download a specific version. Apart from that the release process hasn’t changed a lot. You still have to take care of versions in <strong>Chart.yaml</strong> and “<strong>dependencies.version:”</strong> respectively. Since the dependencies are taken from external sources, Helm requires us to download them by executing a command:</p><pre>helm dependencies update</pre><p>CD pipeline steps:</p><pre>helm plugin install https://github.com/aslafy-z/helm-git --version 0.XX.X<br>helm dependency update<br>helm upgrade --install .....</pre><h3>Final words.</h3><p>There isn’t much information available online about real-world use cases for Helm libraries, unlike with OpenTelemetry. A while back, articles about OpenTelemetry seemed to pop up several times a day. To address this gap, I decided to share more about Helm libraries. When Software Engineer at our company needs to deploy a microservice he/she downloads values.yaml file and creates app.yaml file. Depending on the microservice, the app.yaml file might utilize some or all of the libraries I’ve prepared.</p><pre>.<br>├── Chart.yaml<br>├── templates<br>│   └── app.yaml<br>└── values.yaml</pre><p><strong>app.yaml</strong></p><pre>{{ include &quot;app.deployment&quot; . }} # Mandatory<br>{{ include &quot;app.ingress&quot; . }} # Optional<br>{{ include &quot;keda.scaler&quot; . }} # Optional</pre><p>Understanding what’s behind the {{ include &quot;app.deployment&quot; . }} line isn&#39;t necessary for them(Software Engineers). Recently I released the first stable version that contains 7 Kubernetes objects. By enabling options in the values.yaml file, SEs can deploy:”</p><p>* apiVersion: v1</p><p>kind: Service</p><pre>apiVersion: bitnami.com/v1alpha1<br>kind: SealedSecret</pre><pre>kind: PersistentVolumeClaim<br>apiVersion: v1</pre><pre>apiVersion: policy/v1<br>kind: PodDisruptionBudget</pre><pre>apiVersion: v1<br>kind: ServiceAccount</pre><pre>apiVersion: apps/v1<br>kind: Deployment</pre><p>Of course nothing stops you from adding values verification, defining default values, embedding security best practices, throwing error messages saying what SEs did wrong, all these fancy things that SEs will certainly avoid doing when forced to write Helm charts.</p><p>If you’re reading this, you’ve made it to the end of the article. Thank you! For a bit of fun, let’s prank those who didn’t finish by writing ‘Golden Brotherhood of Helm’ in the comments.</p><h4>If helm library looks appealing to you, let me know that by hitting clap button.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bd8b294ff62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[External-DNS. Route53 — cross-account update. From JIRA ticket to an article]]></title>
            <link>https://medium.com/@magelan09/external-dns-route53-cross-account-update-from-jira-ticket-to-an-article-2acac06aac0e?source=rss-dcaa4a6adc6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2acac06aac0e</guid>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[route-53]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Sergii Bieliaievskyi]]></dc:creator>
            <pubDate>Thu, 16 May 2024 06:04:03 GMT</pubDate>
            <atom:updated>2024-05-16T06:04:03.718Z</atom:updated>
            <content:encoded><![CDATA[<h3>External-DNS. Route53 — cross-account update. From JIRA ticket to an article</h3><p>From JIRA ticket to an article. Story #6</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zmYlTrblHHHmUKWY" /><figcaption>Photo by <a href="https://unsplash.com/@mrpeker?utm_source=medium&amp;utm_medium=referral">Mehmet Ali Peker</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong><em>An article shouldn’t always be a work of art; otherwise, an author might wait ages for a suitable topic. I believe a story created from a JIRA ticket (or a similar system) could also be interesting and find its audience.</em></strong></p><p>Our job seems easy and straightforward when applying the “Quick Start” tutorial instructions, allowing us to close a ticket in 15 minutes. But we know very well that the “Quick Start” doesn’t work for production and, of course, doesn’t work for special cases. Ironically, our job involves navigating through a series of special cases and fine-tuning for production. I consider the ability of Kubernetes ExternalDNS pod to update Route53 records belonging to another AWS account as a special case and invite you to read the article till the very end. If you’d like to share your thoughts, feel free to do so in the comment section.</p><p><em>Before we dive into the wild ride of this article, let’s give a virtual high-five and a massive shoutout to all you awesome peeps who’ve hit that ‘</em><strong><em>follow</em></strong><em>’ button on my Medium.com profile.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*KpnGsY0MucQTPNlmIJpsCQ.png" /></figure><p><em>Your support keeps the momentum going and the inspiration flowing! And to those who haven’t joined our digital tribe yet, what are you waiting for? Come on board and hit that ‘</em><strong><em>follow</em></strong><em>’ button to stay updated on all the latest content. Let’s make this journey even more epic together!”</em></p><h4>The task.</h4><p>There are four AWS accounts. Three environments and one dedicated DNS account. Each environment account hosts one or more private DNS zones. In turn, DNS account hosts only public zones. We need ExternalDNS to be able to create DNS records for the private and public zones.</p><h4>The solution.</h4><p>If we need to perform cross-account operations, role assumption is the right way to go. Indeed, External-DNS provides a parameter ‘ — aws-assume-role’ for this purpose. What about “local”, private zones then? We plan to deploy two instances of External-DNS; one for the private zones and another for public zones. If you have a solution for achieving the same outcome with a single instance, please share it in the comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*-YZtYsxBHUWC7cuVFGfTFg.png" /></figure><h4>The implementation.</h4><h4>AWS IAM.</h4><p>Instructions for configuring External-DNS for locally hosted zones are available in the official documentation, under the following <a href="https://github.com/kubernetes-sigs/external-dns/blob/master/docs/tutorials/aws.md">LINK</a>. Our focus here is on configuring the second instance of External-DNS for cross-account operations. In our minds we differentiate local and cross-account instances. To avoid ambiguity we must reflect the difference in the config file.</p><p><strong>CLI arguments</strong>:</p><pre>--domain-filter=...<br>--regex-domain-filter=...</pre><p><strong>Helm chart parameters:</strong></p><pre>regexDomainFilter: []<br>domainFilters: []</pre><p>Now we can be sure that no interference is possible between those instances. Each acts within its zone of responsibility.<br>OK. It’s time to get our hands dirty with AWS IAM. I would like to quickly remind you that to be able to interact with AWS API, pod needs service account with a ARN IAM role attached to it via annotations.</p><pre>eks.amazonaws.com/role-arn: arn:aws:iam::XXXXXXXXXX:role/CrossAccountExternalDNSRole</pre><p>By the way. A Helm chart can create service account and annotations, you just need to pass proper parameters:</p><pre>serviceAccount:<br>  create: true<br>  name: cross-account-external-dns<br>  annotations:<br>    eks.amazonaws.com/role-arn: arn:aws:iam::XXXXXXXXXX:role/CrossAccountExternalDNSRole</pre><p>The same is true for both instances with no exceptions.</p><p>Let’s go ahead and look what’s inside the role that is attached to the service account.</p><p>CrossAccountExternalDNSRole. <strong>Trust relationships:</strong></p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: {<br>                &quot;Federated&quot;: &quot;arn:aws:iam::XXXXXXX:oidc-provider/oidc.eks.a-world-1.amazonaws.com/id/YYYYYYYYYYYY&quot;<br>            },<br>            &quot;Action&quot;: &quot;sts:AssumeRoleWithWebIdentity&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringEquals&quot;: {<br>                    &quot;oidc.eks.a-world-1.amazonaws.com/id/YYYYYYYYYYYY:sub&quot;: &quot;system:serviceaccount:kube-system:cross-account-external-dns&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p>It tells IAM <strong>WHO</strong> can, or it’s better to say, <strong>WHO</strong> is authorized to assume the role.</p><p>CrossAccountExternalDNSRole. <strong>Policy:</strong></p><pre>{<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:iam::ZZZZZZZZZ:role/EnvAccountExternalDNSRole&quot;<br>        }<br>    ],<br>    &quot;Version&quot;: &quot;2012-10-17&quot;<br>}</pre><p>If trust relationships tells “<strong>WHO</strong>”, policies tell — “<strong>WHAT</strong>”. They specify what actions the service account is allowed to perform. In this case the role allows the service account to assume a role from another AWS account.</p><p>Great. Moving on to the role that should be assumed.</p><p>EnvAccountExternalDNSRole. <strong>Trust relationships:</strong></p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: {<br>                &quot;AWS&quot;: [<br>                    &quot;arn:aws:iam::XXXXXX:root&quot;,<br>                    &quot;arn:aws:iam::YYYYYY:root&quot;,<br>                    &quot;arn:aws:iam::ZZZZZZ:root&quot;<br>                ]<br>            },<br>            &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>        }<br>    ]<br>}</pre><p>When you grant a trust relationship to the root user of an AWS account, you are essentially allowing any user or resource to assume the role. This can be useful in certain situations, but it’s generally considered less secure compared to specifying specific IAM users, roles, or AWS services as trusted entities. Therefore, for simplicity’s sake, I used the root account here. However, you should consider using a specific role ARN instead, as relying on the root account could potentially introduce security risks if not managed properly.</p><p>EnvAccountExternalDNSRole. <strong>Policy:</strong></p><pre>{<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Action&quot;: &quot;route53:ChangeResourceRecordSets&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:route53:::hostedzone/*&quot;<br>        },<br>        {<br>            &quot;Action&quot;: [<br>                &quot;route53:ListResourceRecordSets&quot;,<br>                &quot;route53:ListHostedZones&quot;<br>            ],<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ],<br>    &quot;Version&quot;: &quot;2012-10-17&quot;<br>}</pre><p>You can also take a policy JSON from the official documentation <a href="https://github.com/kubernetes-sigs/external-dns/blob/master/docs/tutorials/aws.md">HERE</a> or use mine. It’s up to you.</p><p>Finally, configure the External-DNS pod to assume the role we diligently created beforehand.</p><p><strong>CLI arguments:</strong></p><pre>--aws-assume-role=arn:aws:iam::ZZZZZZZZ:role/EnvAccountExternalDNSRole</pre><p><strong>Helm chart parameters:</strong></p><pre>aws:<br>  region: a-world-1<br>  assumeRoleArn: arn:aws:iam::ZZZZZZZZ:role/EnvAccountExternalDNSRole</pre><p>Make sure that the pod has passed all probes and be ready to test the setup. Let me know in the comments if the first attempt of cross-account update went smoothly.</p><h3>If you’ve discovered something interesting, show your appreciation with a clap and subscribe.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fx9PNN4H4KtmMl4J" /><figcaption>Photo by <a href="https://unsplash.com/@katjaano?utm_source=medium&amp;utm_medium=referral">Katja Anokhina</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2acac06aac0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A CLI command. 1000+ k8s nodes. You have 30 sec. Run it!!!]]></title>
            <link>https://medium.com/@magelan09/a-cli-command-1000-k8s-nodes-you-have-30-sec-run-it-22626a119b9f?source=rss-dcaa4a6adc6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/22626a119b9f</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubecui]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubectl]]></category>
            <category><![CDATA[logging]]></category>
            <dc:creator><![CDATA[Sergii Bieliaievskyi]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 09:15:19 GMT</pubDate>
            <atom:updated>2024-04-09T09:15:19.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j935IP-vs3s8O_80" /><figcaption>Photo by <a href="https://unsplash.com/@tsbcreative?utm_source=medium&amp;utm_medium=referral">Andy Hall</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We were taught to treat instances as cattle. In today’s article, we will be working with an AWS EKS cluster, all nodes of which are automatically created by karpenter. The nodes come and go; the cluster is “breathing”. SSH is not needed. If something doesn’t work — just drain the node, karpenter will kill it and create a new one in a couple of seconds. But nobody told us that someday, you might need to run just a command on one or all nodes without SSH.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SkKXQjSKvAwN3t_e" /><figcaption>Photo by <a href="https://unsplash.com/@miinyuii?utm_source=medium&amp;utm_medium=referral">Duy Pham</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Salutations, fellow explorers of the digital frontier! Before we plunge into the depths of this article, I wish to express my deepest gratitude to all those who’ve taken the leap of faith and clicked that ‘follow’ button on </em><a href="https://medium.com/@magelan09"><em>my Medium.com profile</em></a><em>. Your decision to accompany me on this expedition fills my heart with joy and purpose.</em></p><p>Of course the problem is not a big deal. It is not even a problem. There are several ways how to attain the goal. For example:</p><ul><li>AWS <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html">Session Manager</a></li></ul><blockquote>Session Manager provides secure and auditable node management without the need to open inbound ports, maintain bastion hosts, or manage SSH keys</blockquote><p>But I suggest not forgetting that we are in the Kubernetes world, so go ahead and create a Kubernetes <strong>DaemonSet</strong>.</p><pre><br>apiVersion: apps/v1<br>kind: DaemonSet<br>metadata:<br>  name: run-cli-command<br>  namespace: kube-system<br>  labels:<br>    app: shell-command<br>spec:<br>  selector:<br>    matchLabels:<br>      app: shell-command<br>  template:<br>    metadata:<br>      labels:<br>        app: shell-command<br>    spec:<br>      hostPID: true<br>      containers:<br>      - name: ubuntu-container<br>        image: ubuntu<br>        securityContext:<br>          privileged: true<br>        command:<br>          - nsenter<br>          - &quot;-t&quot;<br>          - &quot;1&quot;<br>          - &quot;-a&quot;<br>        args:<br>          - &quot;bash&quot;<br>          - &quot;-c&quot;<br>          - &quot;&lt;YOUR_SHELL_COMMAND&gt;&quot;<br>      tolerations:<br>      - operator: &quot;Exists&quot;<br>      priorityClassName: &quot;system-node-critical&quot;<br>      enableServiceLinks: true</pre><p>Might sound like I am trying to waste your precious time, giving such a trivial solution. Indeed, for some of you it is trivial and waste of your time. But the <strong>DaemonSet</strong> is more advanced that you might think.</p><p><strong>DaemonSet</strong>, <strong>Deployment</strong>, <strong>StatefulSet</strong>, <strong>Job</strong>, <strong>CronJob</strong> and so on and so forth, are objects that create <strong>Pods</strong> underneath. <strong>Pods</strong> are containers on a worker node. In its turn, containers are isolated environments which are made possible thanks to Linux namespaces and cgroups. So, running CLI commands this way, you are running them in isolated environment but not on the host machine, which is not what we need right now.</p><p>You’ve probably heard about privileged containers and how dangerous they might be. However, it is a must for such cases.</p><p><em>I will not copy/past the description of </em><strong><em>hostPID</em></strong><em>, </em><strong><em>hostIPC</em></strong><em> and other options. Instead, I would like to encourage you to install </em><a href="https://github.com/pymag09/kubecui"><strong><em>kubecui</em></strong></a><em>, then press “</em><strong><em>Ctrl+b 0</em></strong><em>” and </em><strong><em>F1</em></strong><em> to open a complete Pod specification with detailed description. Like this:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQed2TZyF_emBeOwJtQsWw.png" /></figure><p>To be able to execute a command on the host machine, we need to destroy the walls which keeps us in isolation.</p><ul><li>run the container in privileged mode</li></ul><pre>securityContext:<br>   privileged: true</pre><ul><li>“attache” to namespaces of process with <strong>PID</strong> 1</li></ul><pre>command:<br>- nsenter<br>- &quot;-t&quot;<br>- &quot;1&quot;<br>- &quot;-a&quot;</pre><p>Taints are something that will not allow a Pod to be scheduled if the Pod doesn’t tolerate one. To deal with the taints I added a very broad ”<strong>toleration</strong>”:</p><pre>tolerations:<br>- operator: &quot;Exists&quot;</pre><p>Using <strong>kube-system</strong> namespace is not a coincidence. It is rarely heavily restricted by policies, like for example OPA or kyverno which is particularly great for our case.</p><p>And the last item in a list is priority class.</p><pre>priorityClassName: &quot;system-node-critical&quot;<br></pre><p>In Kubernetes, a PriorityClass is a way to tell the system how important certain workloads or tasks are compared to others. It helps Kubernetes decide which workloads should be scheduled first when there&#39;s competition for resources like CPU and memory.</p><p>If you apply the manifest, a pod will be scheduled on all nodes and the command will be executed, sending something to <strong>stdout</strong>. What’s next? Next, we need to collect logs from these pods.</p><pre>kubectl logs -n kube-system -l app=shell-command</pre><p>Or, which is even better, to read the logs from logging system, like ELK or Grafana Loki. The result can be share with others just by providing URL.</p><h4>Wrapping up.</h4><p>It’s amazing how versatile Kubernetes is. If you also share my beliefs, feel free to hit the “clap” button. And of course don’t forget to leave a comment if you have something say.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22626a119b9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OWASP dependency-check.]]></title>
            <link>https://medium.com/@magelan09/pretending-to-be-a-devsecops-professional-ci-cd-pipeline-owasp-dependency-check-database-c95bb1ac6f2f?source=rss-dcaa4a6adc6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c95bb1ac6f2f</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sergii Bieliaievskyi]]></dc:creator>
            <pubDate>Tue, 02 Apr 2024 09:57:08 GMT</pubDate>
            <atom:updated>2024-04-02T12:05:11.468Z</atom:updated>
            <content:encoded><![CDATA[<h3>OWASP dependency-check. Solving problem of slow db downloading. Pretending to be a DevSecOps professional.</h3><p>From JIRA ticket to an article. Story #5</p><h3>Security scanning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bpiUV2uz2VHYpjzR" /><figcaption>Photo by <a href="https://unsplash.com/@evgenit?utm_source=medium&amp;utm_medium=referral">Evgeni Tcherkasski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong><em>An article shouldn’t always be a work of art; otherwise, an author might wait ages for a suitable topic. I believe a story created from a JIRA ticket (or a similar system) could also be interesting and find its audience.</em></strong></p><p>Spoilers in the title. Fifteen minutes ago, a pipeline finished, turning green. I understand that a single successful run is not enough to conclude that this is a fully functional, production-ready solution. However, my dopamine levels have risen, and I can’t wait to share the details with you.</p><p><strong>Before we start, I want to take a moment to express my sincere gratitude to all those who’ve elected to accompany me on this voyage by clicking that ‘follow’ button on my Medium.com profile. Your support is the wind in my sails, propelling me onward in my mission to enlighten and inspire!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BaOileT0x9Ys8bP1" /><figcaption>Photo by <a href="https://unsplash.com/@nate_dumlao?utm_source=medium&amp;utm_medium=referral">Nathan Dumlao</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Oftentimes using free tools comes with some kind of limitations. Like: number of users, deliberate shortening of an output on a report page or speed limiting. And when those restrictions and limitations break or slow down the pipeline, this is the moment when a new ticket emerges. Those people who used <strong>dependency-check</strong> tool probably understand what I mean. The first problem that immediately punch you in the face is speed — it’s unbelievably slow. In the output there is an information: “[WARNING] An NVD API Key was not provided - it is highly recommended to use an NVD API key as the update can take a VERY long time without an API Key” which might sound like a great solution. But it is not. Providing the key speeds up your first several runs and then it dies. Even small projects have multiple pipelines, and the credits that NVD API key gives to boost speed, run out quickly. On top of that, you might face the problem described <a href="https://github.com/jeremylong/DependencyCheck/issues/6144">here</a>, as I did. So, the solution would be to have the DB somewhere inside your organization. This is exactly what I want to share with you today.</p><h4>Creating a local database.</h4><p>I found this <a href="https://nvd.nist.gov/vuln/data-feeds"><strong>page</strong></a> and maybe it would be much faster (no speed limits imposed on downloads initiated from this page) to download files from there but I don’t know what files to download and how to use them afterward. So I chose to implement the most primitive and the longest approach, as it conforms to MVP (minimum viable product) concept and is truly Agile way, I run <strong>dependency-check</strong> which slowly gets the DB. Fortunately, I’m going to do this in a cronjob, once a day, late in the night, so I don’t care how slow it is.</p><p>It’s time to get our hands dirty.</p><ol><li>We need a place where we want to store the DB inside our organization.</li><li>Kubernetes CronJob which will be triggered once a day to pull the DB</li><li>make this work, from the pipeline</li></ol><h4>The place.</h4><p>In my particular situation, the most convenient place for MVP is — a Bitbucket static page (<a href="https://support.atlassian.com/bitbucket-cloud/docs/publishing-a-website-on-bitbucket-cloud/">https://support.atlassian.com/bitbucket-cloud/docs/publishing-a-website-on-bitbucket-cloud/</a>).</p><h4>The kubernetes cronjob.</h4><p>The Bitbucket static page is nothing else as a git repo behind it. As I mentioned above I chose the native way of retrieving the DB — run dependency-check from the command line. However, we need to make couple of more steps to make the process predictable. By saying “predictable” I mean using non-default directory for the database. For that, I used “<strong>-d &lt;path_to_data_rirectory&gt;</strong>” key. Here is a bash script I end up using, with comments and debugging lines are being skipped:</p><pre>#!/bin/bash<br><br>apt update &amp;&amp; apt install -y zip git<br><br>cd /app_root<br>wget https://github.com/jeremylong/DependencyCheck/releases/download/v9.0.10/dependency-check-9.0.10-release.zip<br>unzip dependency-check-9.0.10-release.zip<br><br>git clone &lt;MY BITBUCKET URL&gt;<br>git config --global user.email &quot;&lt;EMAIL&gt;&quot;<br>git config --global user.name &quot;bitbucket cronjob&quot;<br><br>dependency-check/bin/dependency-check.sh -s /tmp -d /app_root/data<br><br>msg_commit=$(date +%H_%M_%d_%m_%Y)<br>suffix_file_name=$(head /dev/urandom | tr -dc &#39;A-Za-z0-9&#39; | head -c 50)<br><br>tar -czvf dependency-check-database.bitbucket.io/bal-bla-prefix-${suffix_file_name}.tar.gz data<br><br>cd /app_root/dependency-check-database.bitbucket.io<br><br>git reset --hard HEAD^<br>git push origin master -f<br>echo ${suffix_file_name} &gt; file.id<br>git add bal-bla-prefix-${suffix_file_name}.tar.gz file.id<br>git -m &quot;DB ${msg_commit}&quot;<br>git push origin master</pre><p>Probably there is a lot of space for future improvements, but for MVP, this is more than enough.</p><p>There are several moments I want to point your attention to.</p><pre>git reset --hard HEAD^<br>git push origin master -f</pre><p>A git repo keeps whole history. The repo will be growing over the time if we just add the new DB every time again. So prior pushing a new file, delete the old one and force push to rewrite the history.</p><p>The Bitbucket static page is a great solution, but regardless of whether a repo public or private the static page will always be accessible from the internet. So using words like DevSecOps, security and bitbucket static page in the same context, sounds a bit doubting. However we can take some actions to mitigate the problem. It’s true, the page is on the internet but in order to access it, a one needs to know a URL and a file name (there is no index.html in there).</p><p>With that being said, let’s generate a random suffix for the database file name:</p><pre>suffix_file_name=$(head /dev/urandom | tr -dc &#39;A-Za-z0-9&#39; | head -c 50) </pre><p><strong>BTW. All directory, URL and file names were changed before putting them here.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*ersnOW80F8LUmYipSHNJAg.png" /></figure><p>On top of that, we need to add a `<strong>robots.txt` </strong>file to prevent indexing by any search engines:</p><pre>User-agent: *<br>Disallow: /</pre><p>Still not cool, but evidently better.</p><p>I am not sure about putting full Kubernetes manifests here. Let me know in the comment section what you think. For now, I leave it as is. But you have to know that “<strong>cronjob”</strong> comes along with a “<strong>configmap”</strong> that contains the bash script and a secret with ssh key for all git related operations. In the context of security, it is worth mentioning, that if you are going to have Kubernets manifests in the git you should not commit “<strong>secrets</strong>” directly. A “<strong>secret”</strong> is encoded, not encrypted. So I replace “secrets” with a “SealedSecret” object.</p><h4>The pipeline.</h4><p>We are almost done. The easiest part of the entire setup. Previously, I was taking actions, to hinder access to the static page for unauthorized people by randomizing names. The pipeline, happened to be that unauthorized person as well.</p><p>I store the random part in the dedicated file:</p><pre>echo ${suffix_file_name} &gt; file.id</pre><p>Downloading the file, must the very first step in the flow:</p><pre>curl https://dependency-check-database.bitbucket.io/file.id -o /tmp/nvd-db/file.id</pre><p>Now we can put static and random part together and download the DB itself:</p><pre>curl https://dependency-check-database.bitbucket.io/bal-bla-prefix-$(cat /tmp/nvd-db/file.id | tr -d &quot;\n&quot;).tar.gz -o /tmp/nvd-db/bal-bla-prefix-$(cat /tmp/nvd-db/file.id | tr -d &quot;\n&quot;).tar.gz</pre><p>We’ve got the archive. Extract the content to the data directory and run “dependency-check”.</p><h4>Final words.</h4><p>I am happy and sad at the same time. I am happy because the JIRA task seems to be solved. I am sad because there is nothing innovative in this article. But if the information given here somehow helped you or you think the text deserves “Like”, please smash “clap” button and subscribe me on Medium.com. Also, let me know in comment section, what mistakes I made and how would you solve that problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c95bb1ac6f2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleashing Unlimited Potential: The Secret to kubecui’s Unmatched Flexibility]]></title>
            <link>https://medium.com/@magelan09/unleashing-unlimited-potential-the-secret-to-kubecuis-unmatched-flexibility-4a41ba7003c1?source=rss-dcaa4a6adc6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a41ba7003c1</guid>
            <category><![CDATA[kubecui]]></category>
            <category><![CDATA[kubectl]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sergii Bieliaievskyi]]></dc:creator>
            <pubDate>Tue, 19 Mar 2024 12:50:44 GMT</pubDate>
            <atom:updated>2024-03-19T12:50:44.873Z</atom:updated>
            <content:encoded><![CDATA[<p>I welcome those great and perseverant people who read articles one after another, every single time. I know they exist. Today’s chapter is about how easy it is to extend/add new functionality to <a href="https://github.com/pymag09/kubecui"><strong>kubecui</strong></a><strong>. </strong>I truly believe no other app can offer something similar.</p><p><em>Before we delve into the depths of this article, let’s take a moment to recognize and celebrate the incredible individuals who’ve become part of our digital family by clicking that ‘follow’ button on my Medium.com profile. Your support means the world to me and fuels my passion for sharing ideas and insights.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cz1bBfMCP9EnxMEf" /><figcaption>Photo by <a href="https://unsplash.com/@the3dragons?utm_source=medium&amp;utm_medium=referral">The3dragons</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>How often do you ask yourself why the app I use doesn’t have some features? I think such question in different form arises in everyone’s heads from time to time. Starting from release version 1.0.0, everytime the question pops up, you can modify kubecui and keep enjoying interaction with kubernetes . You can make almost any adjustments that fit your needs. An idea of writing the article emerged when I had to upgrade version of a Kubernetes cluster. Being aware of the deprecated or removed Kubernetes APIs is mandatory step prior to performing any upgrade. The other day, I discovered that AWS EKS uses <a href="https://github.com/doitintl/kube-no-trouble"><strong>kubent</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mg0x_2NEnTDlHKyBHmoaMA.png" /></figure><p>I installed <strong>kubent</strong>, then I opened the <strong>kubecui</strong> configuration and added the tool to be able to call it anytime directly from <strong>kubecui</strong>.</p><p>Entire configuration it is not a single file; it is rather a folder that contains per-object configuration.</p><pre>├── daemonsets<br>│   └── config<br>├── default<br>│   └── config<br>├── deployments -&gt; daemonsets<br>├── libs<br>│   ├── explain.entrypoint<br>│   ├── explain.sh<br>│   ├── node-shell.entrypoint<br>│   ├── node-shell.sh<br>│   ├── pod_containers.entrypoint<br>│   ├── pod_containers.sh<br>│   ├── sa-token.entrypoint<br>│   ├── sa-token.sh<br>│   ├── secret_base64_decode.entrypoint<br>│   ├── secret_base64_decode.sh<br>│   ├── tcp_port_pair.entrypoint<br>│   ├── tcp_port_pair.sh<br>│   ├── trivy_scan_image.entrypoint<br>│   ├── trivy_scan_image.sh<br>│   ├── trivy_scan_manifest.entrypoint<br>│   └── trivy_scan_manifest.sh<br>├── nodes<br>│   └── config<br>├── pods<br>│   └── config<br>├── secrets<br>│   └── config<br>├── serviceaccounts<br>│   └── config<br>└── statefulsets -&gt; daemonsets</pre><p>I wanted to call <strong>kubent</strong> from nodes object interface:</p><p><strong><em>kubecui/fx/nodes/config</em></strong></p><pre>HEADER=&#39;==========================================================================================================<br>[F1]Explain [F2]Shell [F3]YAML [F5]Descr search [F6]Cordon [F7]Uncordon [F8]Delete [F9]Drain [F10] Api deprecation report<br>Scrolling (SHIFT - up/down) || CTRL-/ (change view) || CTRL-R (refresh. omit -o wide) || Ctrl-L (-o wide)<br>==========================================================================================================&#39;<br><br>PARAMS+=(--bind &#39;f2:execute:node-shell {1}&#39;)<br>PARAMS+=(--bind &#39;f6:execute:kubectl cordon {1}&#39;)<br>PARAMS+=(--bind &#39;f7:execute:kubectl uncordon {1}&#39;)<br>PARAMS+=(--bind &#39;f9:execute:kubectl drain {1} --ignore-daemonsets --delete-emptydir-data&#39;)<br># The line below is what I added to be able to call kubent<br>PARAMS+=(--bind &#39;f10:execute:kubent -t $(kubectl version -o yaml | yq .serverVersion.major).$(($(kubectl version -o yaml | yq .serverVersion.minor | sed -E &quot;s/^([0-9]+).*/\1/&quot;) + 1)).0 | less -R --use-color&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tn54ngQ6OOWrtcSBS4xibg.png" /></figure><h4>The report page:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*WyELxYj_F51tCzvr4_u2uA.png" /></figure><p>As simple as that.</p><p>If you use k<strong>ubecui</strong> and have already made any adjustments, please share your experience in the comment section. I am really curious about how it worked for you.</p><p>If you share my belief that no other app can do this, I would appreciate it if you repost the article on other platforms.</p><p>You can show your support by hitting the “clap” button. <strong>It’s free, I worked it out.</strong></p><h4>Previous artices:</h4><ul><li><a href="https://medium.com/@magelan09/kubectl-on-steroids-there-is-life-beyond-k9s-5c214e878c83">kubectl on steroids. There is life beyond k9s.</a></li><li><a href="https://medium.com/@magelan09/kubecui-enhanced-interactive-kubectl-dark-side-mode-720a1f19b0bf">kubecui - enhanced interactive kubectl. Dark-side mode.</a></li><li><a href="https://medium.com/@magelan09/navigating-kubernetes-effortlessly-with-kubecui-new-shortcuts-and-features-part-3-df3ab0449518">Navigating Kubernetes Effortlessly with Kubecui: New Shortcuts and Features (Part 3)</a></li><li><a href="https://medium.com/@magelan09/kubecui-ephemeral-containers-and-more-part-4-f069d7ebc405">kubecui. Ephemeral containers and more. Part 4</a></li><li><a href="https://medium.com/@magelan09/kubecui-has-reached-its-first-big-milestone-part-5-in-the-series-of-the-articles-c520c3c33ab1">kubecui has reached its first big milestone. Part #5 in the series of the articles.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a41ba7003c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Hidden to Hero: Embracing HELM’s Secret Weapon — GO Templates!]]></title>
            <link>https://blog.devops.dev/from-hidden-to-hero-embracing-helms-secret-weapon-go-templates-4e6227f8aae3?source=rss-dcaa4a6adc6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e6227f8aae3</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Sergii Bieliaievskyi]]></dc:creator>
            <pubDate>Tue, 19 Mar 2024 06:59:39 GMT</pubDate>
            <atom:updated>2024-03-26T14:58:49.628Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Hidden to Hero: Embracing HELM’s Secret Weapon — GO Templates!</h3><h3>&gt; Intro</h3><p>I am an average guy whose job is in the IT sector. The fact that I work with HELM doesn’t mean that my head has comprehensive knowledge about it. Being conscious of that, I try to gather and store the most useful information, from the internet, for later times. Below are the “<strong>selected”</strong> findings from my notes. I’ve been collecting them for several years, ranging from trivial to advanced.</p><p><em>Before we dive into the wild ride of this article, let’s give a virtual high-five and a massive shoutout to all you awesome peeps who’ve hit that ‘follow’ button on my Medium.com profile. You rock harder than a rock concert on Mars! Seriously, you’re the cream of the crop, the cherry on top, the bacon to my eggs… You get the picture!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ynugbEqHgod9DmFy" /><figcaption>Photo by <a href="https://unsplash.com/@heftiba?utm_source=medium&amp;utm_medium=referral">Toa Heftiba</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>&gt; Scope.</h3><p>Every time, working with GO templating you will stumble across something called scope. Roughly speaking, we distinguish local and global scope.</p><p><strong>local</strong>:</p><ul><li>loops (range)</li><li>with (scope switch)</li><li>include. etc.</li></ul><p><strong>global</strong>:</p><ul><li>root scope — ‘$’</li><li>current scope — ‘.’</li></ul><p>Remember about <strong>scopes</strong> when you have trouble with accessing some variables.</p><h4>Several examples:</h4><pre>{{- define &quot;scope_test&quot; -}}<br>{{- printf &quot;\nscope:\n%s\nglobal scope:\n%s&quot; (toYaml .) (toYaml $) -}}<br>{{- end }}</pre><pre>{{ $res := include &quot;scope_test&quot; (list 1 2 3) }}<br>{{ fail $res}}</pre><pre>scope:<br>- 1<br>- 2<br>- 3<br>global scope:<br>- 1<br>- 2<br>- 3</pre><p>You probably noticed that current and global scope, both pointing to the same variable. How to access “.” , “$” or “Values” then?</p><pre>{{- define &quot;scope_test&quot; -}}<br>{{- printf &quot;\nscope:\n%s\n global scope:\n%s\n argument:\n%s&quot; (toYaml (index . 1)) (toYaml (index . 0)) (toYaml (index . 2)) -}}<br>{{- end }}</pre><pre>{{ $res := include &quot;scope_test&quot; (list $ . (list 1 2 3)) }}<br>{{ fail $res}}</pre><p><strong>include</strong> accepts only one argument. The argument can be of any type. So we can add current, global scope and variable to a list to be passed as the argument. The output is too long, so I encourage you to run and explore it by yourself.</p><h3>&gt; Debugging.</h3><p>It’s hard to underestimate the ability to debug your code. Whereas other languages offer native debugging tools, HELM forces you to be creative when it comes to debugging. The paramount idea behind HELM is to use template to generate manifests. To debug effectively, we need to stop generation of the template and display debugging information. To do that you can use <strong>fail</strong> function.</p><h4>Single variable:</h4><p><strong>values.yaml:</strong></p><pre>root:<br>  sub1:<br>    sub2:<br>      sub3: &quot;val&quot;</pre><p><strong>helm code:</strong></p><pre>{{- .Values.root | toYaml | printf &quot;\nVar debugger: \n%s&quot; | fail }}</pre><p><strong>The output:</strong></p><pre>Error: execution error at (medium/templates/examples.yaml:6:60): <br>Var debugger: <br>sub1:<br>  sub2:<br>    sub3: val</pre><h4>Batch debugging:</h4><p>collect multiple values and display them all as a final debugging step. For example “value” before and “value” after.</p><p><strong>values.yaml</strong></p><pre>root:<br>  sub1:<br>    sub2:<br>      sub3: &quot;d string 1&quot;<br>  sub12:<br>    sub22:<br>      sub3: &quot;d string 33&quot;</pre><pre>{{- $_ := set $.Values &quot;debugger&quot; dict }}<br>{{- merge $.Values.debugger (dict &quot;d1&quot; .Values.root.sub1.sub2.sub3)  }}<br>{{- merge $.Values.debugger (dict &quot;d2&quot; .Values.root.sub12.sub22.sub3)  }}<br>{{ fail (toYaml $.Values.debugger) }}</pre><h4>The output:</h4><pre>d1: d string 1<br>d2: d string 33</pre><h3>&gt; Empty data structure.</h3><p>I know, somebody might say — it is trivial. On the other hand, first incentive might be using [] instead of <strong>list</strong> or {} instead of <strong>dict</strong>.</p><p>For HELM these are:</p><p>list</p><ul><li>$l := list</li></ul><p>dict</p><ul><li>$d := dict</li></ul><h4>&gt; Triming spaces</h4><p><a href="https://helm.sh/docs/chart_template_guide/control_structures/">https://helm.sh/docs/chart_template_guide/control_structures/</a></p><blockquote>{{- (with the dash and space added) indicates that whitespace should be chomped left, while -}} means whitespace to the right should be consumed. <em>Be careful! Newlines are whitespace!</em></blockquote><p>Once again. &gt;&gt;&gt; <strong><em>Newlines are whitespace! &lt;&lt;&lt;</em></strong></p><p>Oh my. How many hours were wasted trying to understand why:</p><pre>&lt;skipped&gt; ... mapping values are not allowed in this context</pre><p>The biggest challenge is to find the bug in abundance of</p><pre>{{- end }} ... {{- end -}} ... {{ end }}</pre><p>elements.</p><h3>&gt; tpl</h3><p><strong>tpl</strong> function is a powerful tool for templating where it was previously impossible. It has proven to be particularly useful for templating values in values.yaml. You might saw it in loki <a href="https://github.com/grafana/loki/blob/main/production/helm/loki/values.yaml">helm chart</a></p><h4>Exmaple:</h4><p>values.yaml</p><pre>memConfig: 4G<br>cmData: |<br>  date: {{ now | unixEpoch }}<br>  memory: {{ .Values.memConfig }}</pre><p>helm code:</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: my-cm<br>data:<br>{{- tpl .Values.cmData . | nindent 2 }}</pre><p>The output:</p><pre># Source: medium/templates/examples.yaml<br>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: my-cm<br>data:<br>  date: 1709362245<br>  memory: 4G</pre><h3>&gt; Functions.</h3><p>Although HELM is not a real programming language it has something which resembles functions. An entity that accepts arguments and return result. Its capabilities might surprise you. I’m currently referring to ‘include,’ which we discussed earlier in the text, specifically in the “scope” chapter</p><p>Although ‘include’ accepts only one argument, nothing prevents passing a list with multiple arguments. ‘index function helps us access each element — index &lt;var&gt; &lt;index&gt;.</p><pre>{{ include &quot;MyNewFunc&quot; (list $val1 $val2) }}</pre><p>Include is quite straightforward: it simply replaces {{ include }} with the text that has been rendered inside the template. By default, the template lacks the ability to return anything other than a string. Consequently, we are unable, for example, to return a list or a dictionary. However, this limitation can be bypassed using serialization.</p><pre>{{- define &quot;MyNewFunc&quot; }}<br>  {{- list 55 2 3 | toJson }}<br>{{- end }}</pre><pre>{{- $res := (include &quot;MyNewFunc&quot; . | fromJsonArray) }}<br>{{- index $res 0 | toString | fail }}<br><br>Will print: 55</pre><h3>&gt; Access undefined variables.</h3><p>For sake of flexibility we can make some variables to be optional. Usually HELM fails trying to access undefined variable. If we could check the variable prior accessing, it would prevent HELM from failing. There are 3 levels of difficultly:</p><h4>1. simple var:</h4><pre>{{ if .Values.var }}<br><br>OR<br><br>{{- .Values.nonexistentvar | default &quot;def_val&quot; }}</pre><h4>2. dictionary:</h4><pre>var1:<br>  var2: &quot;var2&quot;<br>  var3: &quot;var3&quot;</pre><pre>{{- if get .Values.var1 &quot;var333&quot; }}<br><br>OR<br><br>{{- get .Values.sub1 &quot;sub233&quot; | default &quot;def_val&quot; }}</pre><p><strong>“</strong><a href="https://helm.sh/docs/chart_template_guide/function_list/#get"><strong>get</strong></a><strong>”</strong> returns value or empty string if key doesn’t exist. Empty string equals <strong>false </strong>in HELM<strong>.</strong></p><h4>3. nested dictionary</h4><p>Instead of checking each level one by one — use <a href="https://helm.sh/docs/chart_template_guide/function_list/#dig"><strong>dig</strong></a>, which will check each level for you and use default value if any level undefined.</p><p>values.yaml</p><pre>root:<br>  sub1:<br>    sub2:<br>      sub3: &quot;val&quot;</pre><p>helm code:</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: my-cm<br>data:<br>    mayvar: {{ dig &quot;root&quot; &quot;sub1&quot; &quot;sub2&quot; &quot;sub3&quot; &quot;default_value&quot; .Values.AsMap }}</pre><p>the output:</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: my-cm<br>data:<br>    mayvar: val</pre><h3>&gt; Final words</h3><p>There is an unfinished article, from the JIRA task article cycle, which has been waiting to be published for about 1 year. It’s crazy, I know. Almost all the information in this text has been made possible thanks to the aforementioned mystery article.</p><p>Hope it was useful. If at least one chapter caught your attention, please let me know by smashing the clap button. And if you have something to add, I invite you to the comment section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e6227f8aae3" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/from-hidden-to-hero-embracing-helms-secret-weapon-go-templates-4e6227f8aae3">From Hidden to Hero: Embracing HELM’s Secret Weapon — GO Templates!</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laughing in the Face of Complexity: OpenTelemetry and Multiline Logs records]]></title>
            <link>https://medium.com/@magelan09/laughing-in-the-face-of-complexity-opentelemetry-and-multiline-logs-records-baf6ef361955?source=rss-dcaa4a6adc6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/baf6ef361955</guid>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[logs]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sergii Bieliaievskyi]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 17:23:42 GMT</pubDate>
            <atom:updated>2024-03-07T17:23:42.602Z</atom:updated>
            <content:encoded><![CDATA[<p>From JIRA ticket to an article. Story #4</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TfMW70MAnNMnQInZ" /><figcaption>Photo by <a href="https://unsplash.com/@claybanks?utm_source=medium&amp;utm_medium=referral">Clay Banks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong>An article shouldn’t always be a work of art; otherwise, an author might wait ages for a suitable topic. I believe a story created from a JIRA ticket (or a similar system) could also be interesting and find its audience.</strong></blockquote><p>The systems like logstash, promtail, and opentelemetry, they have to deal with multiline log records, like this one:</p><pre>Error: java.lang.Exception: Stack trace<br>        at java.lang.Thread.dumpStack(Thread.java:1336)<br>        at Main.demo3(Main.java:15)<br>        at Main.demo2(Main.java:12)<br>        at Main.demo1(Main.java:9)<br>        at Main.demo(Main.java:6)<br>        at Main.main(Main.java:3)</pre><p>The text you are reading right now is about opentelemetry. And filelog is the most mysterious log parser I’ve ever seen. Here is the link <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/filelogreceiver#multiline-configuration">https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/filelogreceiver#multiline-configuration</a></p><p>If we open the page we will find this:</p><blockquote>multiline A multiline configuration block. See <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/filelogreceiver#multiline-configuration">below</a> for more details.</blockquote><p><a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/filelogreceiver#example---multiline-logs-parsing">opentelemetry-collector-contrib/receiver/filelogreceiver at main · open-telemetry/opentelemetry-collector-contrib</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QneGzCEIciseyJYMnJ2yag.png" /></figure><p>It’s simple! Right? Let’s try to figure it out.</p><p>The first thing you should know is that the multiline option is not for processing multilines. Here is the thing. We deploy opentelemetry to k8s cluster. After kubernetes got rid of dockershim and switched to CRI, raw logs files, stored on the disk, use containerd format (I use containerd. For CRI-O the format is different).</p><pre>2024-03-07T14:18:39.716426545Z stdout F 2024-03-07T14:18:39.716Z 22.33.44.55 GET &quot;http://m.facebook.com/&quot; &quot;Mozilla/5.0 (Linux; Android 11; SM-A405FN Build/RP1A.200720.012; wv) </pre><p>That’s why filelog configuration starts with:</p><pre>filelog:<br>    exclude: []<br>    include:<br>    - /var/log/pods/*/*/*.log<br>    include_file_name: false<br>    include_file_path: true<br>    preserve_trailing_whitespaces: true<br>    preserve_leading_whitespaces: false<br>    operators:<br>    - id: parser-containerd<br>      regex: ^(?P&lt;time&gt;[^ Z]+Z)\s(?P&lt;stream&gt;stdout|stderr)\s(?P&lt;logtag&gt;[^ ]*)\s?(?P&lt;log&gt;.*)<br>      output: containerd-recombine<br>      type: regex_parser<br>    - id: containerd-recombine<br>      combine_field: attributes.log<br>      combine_with: &quot;&quot;<br>      is_last_entry: attributes.logtag == &#39;F&#39;<br>      max_log_size: 102400<br>      output: extract_metadata_from_filepath<br>      source_identifier: attributes[&quot;log.file.path&quot;]<br>      type: recombine</pre><p>The regex operator (parser-containerd) turns the raw record to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AdPcVd1Rb7ANiyYqF3vZ9g.png" /></figure><p>Then “Group <strong>log” </strong>is moved to body:</p><pre>- from: attributes.log<br>  to: body<br>  type: move</pre><p>This is how we see it in grafana loki:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7RUAaTooN25VbbcRNKBlVA.png" /></figure><p>And now we are ready for multilines.</p><pre>- id: recombine-multiline<br>  type: recombine<br>  combine_field: body<br>  is_first_entry: body matches &quot;^[^\\s]&quot;<br>  source_identifier: attributes[&quot;log.file.path&quot;]</pre><h3>Final configuration.</h3><pre>receivers:<br>  k8sobjects:<br>    objects:<br>      - name: pods<br>        mode: pull<br>      - name: events<br>        mode: watch<br>  filelog:<br>      exclude: []<br>      include:<br>      - /var/log/pods/*/*/*.log<br>      include_file_name: false<br>      include_file_path: true<br>      preserve_trailing_whitespaces: true<br>      preserve_leading_whitespaces: false<br>      operators:<br>      - id: parser-containerd<br>        regex: ^(?P&lt;time&gt;[^ Z]+Z)\s(?P&lt;stream&gt;stdout|stderr)\s(?P&lt;logtag&gt;[^ ]*)\s?(?P&lt;log&gt;.*)<br>        output: containerd-recombine<br>        type: regex_parser<br>      - id: containerd-recombine<br>        combine_field: attributes.log<br>        combine_with: &quot;&quot;<br>        is_last_entry: attributes.logtag == &#39;F&#39;<br>        max_log_size: 102400<br>        output: extract_metadata_from_filepath<br>        source_identifier: attributes[&quot;log.file.path&quot;]<br>        type: recombine<br>      - id: extract_metadata_from_filepath<br>        parse_from: attributes[&quot;log.file.path&quot;]<br>        regex: ^.*\/(?P&lt;namespace&gt;[^_]+)_(?P&lt;pod_name&gt;[^_]+)_(?P&lt;uid&gt;[a-f0-9\-]+)\/(?P&lt;container_name&gt;[^\._]+)\/(?P&lt;restart_count&gt;\d+)\.log$<br>        type: regex_parser<br>      - from: attributes.container_name<br>        to: resource[&quot;k8s.container.name&quot;]<br>        type: move<br>      - from: attributes.namespace<br>        to: resource[&quot;k8s.namespace.name&quot;]<br>        type: move<br>      - from: attributes.pod_name<br>        to: resource[&quot;k8s.pod.name&quot;]<br>        type: move<br>      - from: attributes.restart_count<br>        to: resource[&quot;k8s.container.restart_count&quot;]<br>        type: move<br>      - from: attributes.uid<br>        to: resource[&quot;k8s.pod.uid&quot;]<br>        type: move<br>      - from: attributes.log<br>        to: body<br>        type: move<br>      - id: recombine-multiline<br>        type: recombine<br>        combine_field: body<br>        is_first_entry: body matches &quot;^[^\\s]&quot;<br>        source_identifier: attributes[&quot;log.file.path&quot;]</pre><h3>The last words.</h3><p>I am writing this to save your time, trying to process, so-called, “multilines” correctly. If so, please hit “clap” button. If you know how to use the filelog multiline option, please let me know in the comment section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baf6ef361955" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>