# Infraspec > Managed open source observability, reliability and platform engineering inside your cloud. Infraspec is an infrastructure engineering company. Every blog post and case study below is available as clean Markdown at the same URL plus `.md`. ## Core pages - [Infrastructure Engineering](https://www.infraspec.dev/): Managed open source observability, reliability and platform engineering inside your cloud. - [Engineering Offerings](https://www.infraspec.dev/offerings): Reliability, platform, backend, AI and forward-deployed engineering. - [Reliability Engineering](https://www.infraspec.dev/offerings/reliability-engineering): SRE and observability engineering, run as one discipline. - [Platform Engineering](https://www.infraspec.dev/offerings/platform-engineering): A paved road from commit to production. - [Backend & Product Engineering](https://www.infraspec.dev/offerings/backend-and-product-engineering): The APIs, services and data behind the button. - [AI & LLM Engineering](https://www.infraspec.dev/offerings/ai-and-llm-engineering): From a clever demo to something you can trust in production. - [Forward-deployed Engineering](https://www.infraspec.dev/offerings/forward-deployed-engineering): Senior engineers inside your team, owning the outcome with you. - [Case Studies](https://www.infraspec.dev/our-work): How we helped engineering teams cut cloud cost, migrate and see their systems. - [Engineering Blog](https://www.infraspec.dev/blog): Field notes on observability, infrastructure, cloud, reliability and software engineering. - [Garage](https://www.infraspec.dev/garage): Engineering side quests: local AI, PicFusion and Raspberry Pi netboot orchestration. - [Life at Infraspec](https://www.infraspec.dev/team): How Infraspec grows engineers: first principles, mentorship and learning in public. - [Bootcamp](https://www.infraspec.dev/team/bootcamp): Our five-week bootcamp for new engineers. - [Internship](https://www.infraspec.dev/team/internship): Two months, two mentors, one real problem. - [Campus hiring](https://www.infraspec.dev/team/campus): How we meet, test and hire engineers straight from campus. - [Careers](https://www.infraspec.dev/careers): Hiring updates for Infraspec. - [Contact](https://www.infraspec.dev/contact): Tell us what your engineers are wrestling with. ## Case studies - [Cutting onboarding time by 40% with iGPT, our internal AI assistant for platform engineering](https://www.infraspec.dev/case-studies/igpt-platform-engineering-onboarding.md): Grounded in our own documentation and project experience, iGPT helps new engineers find answers without pulling senior teammates away from their work. - [Moving from infrastructure silos to a platform model](https://www.infraspec.dev/case-studies/infrastructure-silos-to-platform.md): Infrastructure as Code and a clearer request workflow gave developers self-service infrastructure in under an hour. - [Maintaining 99.96% uptime as a lending business doubled](https://www.infraspec.dev/case-studies/lending-reliability-at-scale.md): A lending platform maintained 99.96% uptime while almost doubling every six months, with clearer signals and resilient third-party integrations. - [Reducing AWS costs for a hyperlocal delivery platform](https://www.infraspec.dev/case-studies/hyperlocal-aws-cost-optimization.md): Engineering teams brought AWS spend under control, saving about $161,000 in three months while gaining a clear view of costs by team and service. - [Moving a TV AdTech platform from on-premise to AWS](https://www.infraspec.dev/case-studies/tv-adtech-on-premise-to-aws.md): A bare-metal platform moved to AWS one environment at a time. New environments now take minutes instead of weeks to provision. - [Automating multi-tenant AWS infrastructure for an AI platform](https://www.infraspec.dev/case-studies/multi-tenant-ai-platform.md): Enterprise customer environments went from days of manual setup to automated provisioning in under an hour. - [Docker Swarm to Amazon ECS migration](https://www.infraspec.dev/case-studies/docker-swarm-to-ecs.md): A six-person engineering team traded manual cluster upkeep for an easier-to-run AWS environment and roughly 25% lower infrastructure costs. - [Using DORA metrics to understand software delivery performance](https://www.infraspec.dev/case-studies/dora-metrics-delivery.md): A clearer delivery workflow and ongoing team-level metrics replaced fragmented tooling and one-off surveys. - [Infrastructure modernisation for a fast-growing hyperlocal platform](https://www.infraspec.dev/case-studies/hyperlocal-platform-modernization.md): A proactive platform roadmap improved detection, delivery and cost control while the business kept growing. - [Building a vendor-neutral observability platform for an online wellness platform](https://www.infraspec.dev/case-studies/wellness-platform): A complete observability transformation across more than 20 services on AWS. ## Blog - [Exploring SPIFFE and SPIRE: How Workloads Prove Who They Are Without Secrets](https://www.infraspec.dev/blog/exploring-spiffe-and-spire.md): Take a small company running a payments-api service. It runs as pods in a Kubernetes cluster in the company's own data centre, and it has to: - [Which Logs Can You Delete? Deciding What's Necessary Before You Cut](https://www.infraspec.dev/blog/which-logs-can-you-delete.md): Every conversation about observability cost ends up in the same place: drop the unnecessary logs. - [Exporting Langfuse LLM metrics to the OpenTelemetry Collector](https://www.infraspec.dev/blog/exporting-langfuse-llm-metrics-to-opentelemetry-collector.md): Teams building LLM applications often use Langfuse to trace model calls and track cost, latency, and quality. Their dashboards and alerts, however,… - [Scaling OTel Collectors When Push and Pull Don't Scale the Same Way](https://www.infraspec.dev/blog/scaling-otel-collectors-push-and-pull.md): This came out of a conversation with one of our engineers about a production incident she'd just been through. It sounded small at first (a pod got… - [Taking Back Control: Observability as Reclaiming Agency](https://www.infraspec.dev/blog/taking-back-control.md): The story of every growing system is fundamentally a story about losing and regaining control. - [Pragmatism Over Perfection](https://www.infraspec.dev/blog/pragmatism-over-perfection.md): We as Engineers often chase perfection. It fuels our curiosity, sharpens our skills, and makes us feel good about the things we build. But at the same… - [Apache Spark: Unleashing Big Data with RDDs, DataFrames and Beyond](https://www.infraspec.dev/blog/apache-spark-unleashing-big-data-with-rdds-dataframes-and-beyond.md): Before I knew Spark, I mostly used only Pandas and NumPy for data processing. They worked well for small datasets, and I never really had any… - [Building Scalable Multi-Tenant Systems with AWS CDK](https://www.infraspec.dev/blog/multi-tenant-system-with-aws-cdk.md): In this blog, I will be taking you on a journey of building the scalable and efficient IAC solution that we build for our multi-tenant system. Here we… - [Efficient Data Migration: Hive Metastore to Unity Catalog](https://www.infraspec.dev/blog/hive-to-unity-catalog-data-migration-databricks.md): We had to migrate extensive data from Hive Metastore to Unity Catalog in a regulated large-scale enterprise environment. This task required precise… - [ClickHouse Performance Benchmarking on ECS](https://www.infraspec.dev/blog/clickhouse-benchmarking.md): Imagine being a Formula One driver, racing at breakneck speeds, but without any telemetry data to guide you. It’s a thrilling ride, but one wrong turn or… - [Cache Strategies](https://www.infraspec.dev/blog/cache-strategies.md): Caching is a technique that enhances application performance by temporarily storing frequently accessed data in high-speed data storage hardware like… - [Managing Environments with Terragrunt](https://www.infraspec.dev/blog/terragrunt-envs-management.md): Managing multiple environments was a never-ending headache for me. Like many others in the DevOps world, I was responsible for deploying applications… - [NFS Filesystem as Docker Volumes](https://www.infraspec.dev/blog/nfs-fs-as-docker-volume.md): As an Infrastructure engineer, I’ve had my fair share of experiences with containerized environments and the challenges of managing data persistence. One… - [AWS ECS: FARGATE vs self-managed EC2](https://www.infraspec.dev/blog/aws-ecs-fargate-vs-self-managed-ec2.md): The Amazon Elastic Container Service (ECS) from Amazon deploys and manages containerised applications in two distinct modes of operation: Fargate and… - [Managing Credentials and Secrets in Terraform](https://www.infraspec.dev/blog/terraform_secrets_management_guide.md): Imagine you’re working on a project where you need to deploy resources to aws using terraform. In a rush to get things done, you decide to hard-code your… - [Essential AWS Tagging Strategies](https://www.infraspec.dev/blog/tag-strat-blog.md): Managing cloud resources efficiently in AWS requires a robust tagging strategy. Tags are key-value pairs attached to resources, providing crucial… - [GenAI Dictionary: Part 1 - LLM](https://www.infraspec.dev/blog/genai-dictionary-part1-llm.md): We bring to you this weekly series of articles, to help understand and demystify the lexicon in the GenAI space. Here is part 1 - Large Language Model. - [Building a Discord GPT Bot](https://www.infraspec.dev/blog/building-a-discord-gpt-bot.md): Amidst the excitement surrounding AI, we were eager to delve into this field ourselves. As engineers, we wanted more than just a casual conversation with… - [Argo Rollout & AWS ALB 502 fix](https://www.infraspec.dev/blog/argo-rollout-aws-alb.md): The blog discusses resolving a deployment issue with 502 errors on AWS EKS using AWS ALB and Argo Rollouts. It details the root cause, attempted… - [Header-Based Traffic Routing with Argo Rollouts](https://www.infraspec.dev/blog/header-based-traffic-routing-using-argo-rollouts.md): This blog explores how to use Argo Rollouts for deploying software updates smoothly. It covers the challenges faced when rolling back updates and… - [RBAC in Kubernetes](https://www.infraspec.dev/blog/kubernetes-rbac.md): Role-Based Access Control (RBAC) is a crucial feature in Kubernetes that allows administrators to define and manage permissions for users and services… - [Winston Logger Guide for Node.js](https://www.infraspec.dev/blog/guide-to-implement-winston-logger.md): “The only thing more satisfying than fixing a bug is reading the frustrated log messages that led you there.” This humorous yet insightful quote… - [Getting Started with GitHub Runners](https://www.infraspec.dev/blog/github-runners.md): In today’s fast-paced world of software development, automation is key to staying competitive. GitHub, a leading platform for collaboration and version… - [Docker: Simplify, Scale & Secure](https://www.infraspec.dev/blog/docker-deep-dive.md): This blog will cover the foundational concepts of Docker layers, caching mechanisms, and Dockerfile optimization. Additionally, provide insights on… - [Secrets Rotation w/ AWS Secrets Manager - Part 2](https://www.infraspec.dev/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2.md): In Part 1 , we discussed upon configuring AWS Secrets Manager, AWS Lambda, and Automatic Rotation for our Secret. We also defined permissions for our… - [Secrets Rotation w/ AWS Secrets Manager - Part 1](https://www.infraspec.dev/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-1.md): Managing secrets has always been a significant aspect when deploying applications. Typically, we set up a pipeline to provide secrets to our application… - [TFTP Overview](https://www.infraspec.dev/blog/tftp-overview.md): TFTP known as Trivial File transfer protocol is a simple file transfer protocol with features such as get or put files. Unlike FTP or SFTP which can… - [Automated Netbooting for Raspberry Pi](https://www.infraspec.dev/blog/rpi-netboot-automation.md): In this blog, we’ll delve into automating the netbooting process using a bash script ( pxeService.sh ) and an address list ( addresslist.txt ) to enhance… - [PXE Boot Sequence Deep Dive](https://www.infraspec.dev/blog/rpi-netboot-deep-dive.md): The Preboot Execution Environment (PXE) specification describes a standardized client-server environment that boots a software assembly retrieved from a… - [Cron Jobs Guide](https://www.infraspec.dev/blog/cron-jobs.md): In this article, tailored specifically for users of Unix-like systems such as Linux, we’ll explore everything you need to know about cron jobs. From… - [Linux Memory & Swap](https://www.infraspec.dev/blog/linux-memory-swap.md): This blog will help you figure out how to check how much memory is left on your Linux machine. Knowing this will tell you if your server is running low… - [Building Internal Tooling in Legacy Systems](https://www.infraspec.dev/blog/building-internal-tools.md): This article takes you through what it is like to build an internal tool while dealing with a lot of legacy systems where a lot of tech debts already… - [Streams in Java](https://www.infraspec.dev/blog/java-streams.md): Imagine a lazy river carrying data elements one by one. That’s essentially what a stream is – a sequence of elements that you can process on the fly,… - [How TDD helps design better software](https://www.infraspec.dev/blog/tdd-design-benefits.md): Most of us think of TDD as a tool for software testing and verification. But if used effectively it is more than that. - [k3s cluster on Raspberry Pi's](https://www.infraspec.dev/blog/lightweight-k3s-cluster-raspberry-pi.md): As a developer at Infraspec, I am responsible for managing internal tooling and ensuring the smooth operation of local tooling and network services in… - [Is DNS migration a tricky affair?](https://www.infraspec.dev/blog/is-dns-migration-a-tricky-affair.md): Never trust a friend who says DNS migration is easy. Your instinct says it’s easy, well don’t trust your instinct. In this post, I will be sharing my… - [Office/Home Lab Internet Failover Setup](https://www.infraspec.dev/blog/office-home-lab-internet-failover-setup.md): An overview of how to set up internet failover for an office or home lab. - [Setting up Ingress on EKS](https://www.infraspec.dev/blog/setting-up-ingress-on-eks.md): An Ingress in Kubernetes provides external access to your Kubernetes services. You configure access by creating a collection of routing rules that define… - [Container Networking Deep Dive - Part 3](https://www.infraspec.dev/blog/container-networking-deep-dive-p3.md): In part 3 of this series, we will see how containers running on the host communicates with the outside world i.e., the internet - [Container Networking Deep Dive - Part 2](https://www.infraspec.dev/blog/container-networking-deep-dive-p2.md): In part 2 of this series, we will demystify how multiple containers running on the same host communicates with the host and vice versa. - [Container Networking Deep Dive - Part 1](https://www.infraspec.dev/blog/container-networking-deep-dive-p1.md): In part 1 of this series, we will demystify how a container communicates with the host and vice versa. --- # Cutting onboarding time by 40% with iGPT, our internal AI assistant for platform engineering Client: Infraspec’s internal engineering team Offerings: Platform Engineering Canonical: https://www.infraspec.dev/case-studies/igpt-platform-engineering-onboarding Grounded in our own documentation and project experience, iGPT helps new engineers find answers without pulling senior teammates away from their work. A lot of the infrastructure work we do builds on things the team has already figured out before. We had built up a lot of knowledge around Terraform, Kubernetes, Ansible and the way we approached platform engineering across different projects. New engineers at Infraspec had a lot of similar questions when they started working. Some of the answers were documented, and a lot more were in the heads of senior engineers who had solved the same problem on an earlier project. That works when the team is small. As the team grew and more projects were running at the same time, it started slowing everyone down. That’s the whole reason why iGPT was built. ## Highlights - 2×: junior engineer productivity - 30%: improvement in project efficiency ## Why not just use a general LLM? Our new engineers had a lot of context to pick up before they could get comfortable with the kind of infrastructure work we do. We already had all the knowledge to provide, but finding the right bit of it was still taking time. A general LLM could definitely explain Terraform or Kubernetes. It just wouldn't have been able to tell you how we’ve set things up on our own projects or why we picked one approach over another. We wanted engineers to ask iGPT what they’d ask a senior engineer, and get an answer based on how Infraspec does things. ## How did we get our own knowledge into it? We started with the documentation that we had, along with FAQs and other internal knowledge we wanted iGPT to use. We cleaned up all that material before indexing it. We then created embeddings from the content and stored them in a vector database. When someone asks iGPT something, it pulls the relevant material from our docs and uses them while answering. This keeps the response tied to the way we’ve actually worked on these problems. ## What did we use to build it? We used OpenWebUI for the chat interface and connected it to the knowledge we already had internally. We used GPT-3.5 as well as open-source models like Gemma and Llama to generate responses. We added a feedback mechanism as well, so engineers could tell us when an answer needed some work. Now the team had something concrete to use while improving the responses over time. ## How did we test it? We first rolled iGPT out to a smaller group and let them use iGPT before opening it up to the whole team. Our domain experts worked with the development team during that period to check if the right information was being retrieved and whether the answers were accurate enough. We kept making changes based on the feedback from those users. Once the team was comfortable with how it was performing, we rolled it out more widely and continued monitoring it. ## What changed for the team after rolling this out? New engineers could get to the context they needed much faster, without having to rely as much on someone who had already worked through the problem. That made onboarding easier for them and also reduced some of the back-and-forth for experienced engineers who were otherwise being pulled in to answer those questions. The change showed up in the numbers as well. Onboarding time came down by 40%. Also, junior engineer productivity doubled, and overall project efficiency improved by 30%. --- # Moving from infrastructure silos to a platform model Client: A large education technology company Offerings: Platform Engineering, Reliability · Observability Canonical: https://www.infraspec.dev/case-studies/infrastructure-silos-to-platform Infrastructure as Code and a clearer request workflow gave developers self-service infrastructure in under an hour. We worked with a large EdTech company with more than 100 engineers. The infrastructure team had a stream of requests from developer teams, and developer requests were coming in faster than the team could properly step back and improve the way that work was done. We worked with the team on both sides of that problem. We looked at how requests were handled day to day, and how much of the infrastructure developers could get without needing someone to provision it manually. ## Highlights - 100%: IaC adoption for new cloud infrastructure - <1 hour: to get infrastructure - 25 → 3: exposed microservice endpoints ## What was getting in the infrastructure team’s way? The team had a lot of work in progress at any given time. Ad hoc requests from developers kept getting added and WIP kept growing. There wasn’t enough time for them to work on automation or improve how infrastructure was provisioned. We introduced Kanban to keep WIP under control and brought more structure to how those service requests were coming in. The team also started going through those requests every week. If the same kind of request kept coming up, the team could use that to decide what they needed to focus on over the next month or quarter. ## How did we make infrastructure easier to provision? We moved new cloud infrastructure to Infrastructure as Code. That covered Kubernetes clusters, EC2 workloads, S3, RDS, ALBs and ElastiCache. New cloud infrastructure reached 100% IaC adoption, with a reported reduction of around 95% in provisioning. That was a significant shift from developers depending on someone in the infrastructure team every time they needed something new. ## What else changed in the platform? We used API Gateway to reduce the number of exposed microservice endpoints from 25 to 3. That gave the team a much smaller API surface to manage. We added monitoring and alerting for infrastructure such as Kubernetes, API Gateway and Certificate Manager as well. Cost tagging was added as well, so teams and leadership could see cloud spend by service, team and infrastructure resource. ## How did we get a clearer view of software delivery? We ran a survey across the engineering teams to understand how software delivery was working and where teams were getting stuck. We used DORA metrics to compare delivery performance across teams. The findings were shared with the engineering organisation and helped us agree on what needed attention next. The team later started tracking DORA metrics at service and team levels. What changed for the infrastructure team? The team had a much more repeatable and consistent way to provide infrastructure to the rest of the engineering team. New cloud resources were created through code instead of depending on someone to provision them manually, and developers could get infrastructure in under an hour. The team also had a better handle on incoming requests and more time to work on the platform itself. --- # Maintaining 99.96% uptime as a lending business doubled Client: A fast-growing consumer lending business Offerings: Reliability Engineering, Reliability · Observability Canonical: https://www.infraspec.dev/case-studies/lending-reliability-at-scale A lending platform maintained 99.96% uptime while almost doubling every six months, with clearer signals and resilient third-party integrations. We worked with a consumer lending team while the business was growing very fast, almost doubling every six months. Completing a lending journey involved KYC, mandates, lender integrations and disbursals. A lot of these depended on external systems that the company had no control over. That made reliability harder as the business grew. More people were using the lending product, but the company was also depending on providers that could slow down or go down completely. ## Highlights - 30 → 3: minutes to detect an issue - 800 → 30: weekly on-call pages - 40%: fewer onboarding failures ## Why were third-party systems such a big reliability problem? KYC was a major source of friction. The company depended on external KYC providers, lender APIs and mandate systems. Some of these were older state-owned systems too, so there was only so much the company could control from its side. If a KYC provider went down, users could get stuck during onboarding. The team first needed to know where the failure was actually coming from. Was it something inside the company, or was one of the providers having a problem? Even if it was a provider, users still couldn’t just be left stuck there. ## How did we figure out where a failure was coming from? We put Datadog APM across the lending services. KYC, mandates, lender integrations and disbursals were all covered. The team could trace a request through the company’s services and see which third-party calls it made. We also gave the external providers their own dashboards. So instead of looking at KYC as one big thing, the team could see what was happening with each vendor or lender API separately. This made it much easier to tell whether the company’s service had a problem or whether the issue was with the provider. We also started including observability in the acceptance criteria for new work. Teams had to decide what they wanted to monitor while they were building the feature instead of coming back and doing it later. ## What changed for the on-call team? The team was getting around 800 pages a week. On-call engineers had to work through that noise before they could identify which alerts actually needed attention. We tied alerts back to SLOs and error budgets to cut some of that down. We connected Datadog to PagerDuty and the team had proper on-call rotations and escalation paths there. We also split incidents by severity, from P0 to P3. For the important alerts, we wrote runbooks. So, whoever got paged didn’t have to wait around for the person who knew that service best before they could do anything. We also started doing blameless RCAs for P0 and P1 incidents. The team reviewed the follow-up work from those incidents each week. Blue-green deployments helped with releases too. If a release caused a problem, the team could switch traffic back quickly. MTTD came down from 30 minutes to 3 minutes and P0 & P1 incidents went from around 8-10 a month to 2-3. And those 800 weekly pages also came down to around 30. ## How did we stop one problem from affecting others? We used Resilience4J circuit breakers around the third-party calls. If a provider started slowing down or failing, we didn’t want more requests to just keep piling up. The circuit breaker could stop sending requests there. We also separated the resources used by each provider. Each provider also got its own thread pool and connection pool. So if one KYC vendor became slow, it couldn’t take up the capacity the others needed. We set timeouts separately for each provider too. We were careful with retries too and only retried a request when it was safe to do so. We also moved a lot of database reads to replicas so the primary database had less work to do as traffic grew. ## What happened when a KYC provider or lender went down? The company was already working with multiple KYC vendors and lenders. We wanted the system to be able to switch providers if one of them started having problems. Each provider had its own adapter, but the company’s services could work with all of them through the same interface. We also added routing based on how the providers were performing at that moment. If one provider started slowing down or failing more, traffic could be sent to another one. The circuit breaker was checked as well. The team could change these routing rules without doing a new deployment. They could send more traffic to one provider, for example, or change which provider got priority. Cost and approval rate were important factors as well. This made a significant difference during KYC outages. Before, a provider going down could completely block users from finishing KYC. After the changes, around 90% of KYC journeys could still go through. ## How did the system hold up through the growth? The company maintained 99.96% uptime through this period, even when the lending business was growing as quickly as it was. Onboarding failures came down by 40%. Repayment settlement got much faster too. It came down from hours to minutes. --- # Reducing AWS costs for a hyperlocal delivery platform Client: A hyperlocal delivery company Offerings: Platform Engineering Canonical: https://www.infraspec.dev/case-studies/hyperlocal-aws-cost-optimization Engineering teams brought AWS spend under control, saving about $161,000 in three months while gaining a clear view of costs by team and service. We worked with a leading hyperlocal delivery company running a large microservices setup across several product verticals, with millions of transactions moving through the platform every day. We worked with the engineering teams to understand where the AWS bill was going, bring it down, and make it easier for teams to keep track of their own spend. ## Highlights - $161k: saved over three months - 20%: lower costs accounting for projected growth - 45%: lower QA infrastructure costs ## Why was the AWS bill getting harder to control? The AWS bill was already around $800,000 a month, and it was still going up by 5–8% every month. The company had more products and more engineering teams than before, which also meant more infrastructure being added on AWS. Nobody had a clean view of what each team, service or product was actually costing. Resources hadn’t been tagged consistently, so engineering and finance could see the total bill, but tracing that spend back to the teams and services behind it was much harder. ## What did we find when we started digging into the bill? We pulled six months of billing data into Cost Explorer and ran AWS Trusted Advisor against the account. That first pass with Trusted Advisor alone pointed us to around $30,000 a month in potential savings from things like idle RDS instances, underused load balancers and unattached EBS volumes. There was more once we went through the resource inventory. Some EC2 instances had been running at under 5% CPU utilisation for 30 days. We also found unused Elastic IPs, S3 buckets that were no longer needed and redundant NAT instances. We dealt with the easier fixes first. Backup retention was tightened, old snapshots and storage were cleaned up, and QA and development workloads moved to Spot Instances. That brought QA infrastructure costs down by 45%. ## How did teams get a clearer view of their AWS spend? We introduced consistent tags for team, service, product and environment. The Terraform CI/CD flow checked new infrastructure for those tags, and AWS Service Control Policies stopped untagged resources from being created. We tagged existing resources separately and used weekly reports showing anything that was still missing. Teams could then see cost by service and team through Grafana and dashboards from the AWS billing partner. Budget alerts picked up overages, and AWS Athena gave people a SQL interface into the Cost and Usage Report data when they needed to dig further. Team leads took responsibility for their AWS costs, while the platform team continued to own shared infrastructure. ## Where did the bigger savings come from? We checked which workloads could move to Graviton instead of forcing everything across. That brought down the overall compute costs by 9% and Production Reserved Instance coverage went up to 70% too. EKS had another nice surprise for us. A lot of pods were asking for 2–4x more resources than they were actually using. We reset requests and limits around P95 utilisation and the same workloads could run with 20% fewer nodes. We also found 23 over-provisioned RDS instances. Kafka was running at only around 40% of provisioned capacity, and moving compatible ElastiCache workloads to Graviton cut those costs by 15%. S3 was another big one. We moved older data into cheaper storage classes and cleared out unnecessary data. That saved $19,000 a month. We used VPC Flow Logs and Athena and found that around 70% of transfer costs were coming from cross-zone traffic. We changed how that traffic moved and added VPC endpoints. Data-transfer costs came down by 25% and the endpoint work alone saved around $8,000 a month. We also moved Sentry in-house and shifted GitHub Actions runners onto EKS with Spot Instances. That cut runner costs by 60%, and local caching made them 3x faster. ## How did cloud cost become something every team owned? Team leads took responsibility for their own AWS costs, while the platform team continued to own shared infrastructure. Every two weeks, teams would look at what had changed and share anything useful they’d found along the way. Cost also started coming up earlier in the engineering process. Estimates went into technical design docs and infrastructure cost was discussed during sprint planning. ## What changed after three months? Over three months, the work saved about $161,000. Once we accounted for the growth the AWS bill was otherwise on track for, that came out to a 20% cost reduction. The client could also see AWS spend by team and service instead of looking at one big number. And none of the savings came at the cost of reliability or performance. In a few places, performance actually improved. --- # Moving a TV AdTech platform from on-premise to AWS Client: A TV AdTech company Offerings: Platform Engineering, Reliability Engineering Canonical: https://www.infraspec.dev/case-studies/tv-adtech-on-premise-to-aws A bare-metal platform moved to AWS one environment at a time. New environments now take minutes instead of weeks to provision. We worked with a TV AdTech company that was still running its infrastructure on bare metal server in an on-prem setup. That setup had worked for a long time, but adding capacity would take weeks and the infrastructure team was spending a lot of time keeping the on-prem environment running. We worked with the infrastructure and backend teams to plan the move to AWS and take it one environment at a time. ## Highlights - Weeks → minutes: to provision a new environment - 99.5%: uptime SLO maintained - Code: used to create infrastructure instead of manual setup ## Why was the old setup difficult to run? There was no virtualisation layer. If the team needed more compute, they had to provision more physical machines, which could take weeks. Some of the hardware was also getting old, which was starting to show up in performance. To stay on the safe side, the team sometimes compensated by provisioning more capacity than they really needed. There was a lot of operational work around the setup too. The team was bogged down maintaining out-of-date services and self-hosted tools, while also dealing with environments that weren't properly isolated from each other. ## Why couldn’t we just copy-paste the same setup to AWS? The existing platform had been built around physical servers, so copying it one-for-one in AWS would’ve just carried a lot of problems over. We sat down with the infrastructure and backend teams and went through the migration plan together. Data migration needed more thought. So did rollback. We also had to be clear about what would move first and what could wait. So instead of treating AWS like a new place to host the old setup, we used the migration to change how the infrastructure was put together. ## What did we need to set up in AWS first? We set up AWS Organizations with separate accounts for production, staging and development, along with central logging and audit accounts and a shared platform layer. We used Terraform and Atmos to build the infrastructure. We built reusable components for things like VPCs, EKS, RDS, S3, KMS, Secrets Manager and ALBs. We also kept AWS console access read-only. If infrastructure needed to change, the change went through code, a pull request and a Terraform plan before it was applied. ## How did we get the data across? The data the application services depended on had to be moved to AWS first. The source data was in Ceph clusters. We worked with the data engineering team on a custom sync process that moved it into S3. That wasn’t completely smooth. Some consistency issues in the Ceph clusters were causing the sync to fail, so we fixed those first. We also set up the database clusters in AWS and synced the data into RDS before the application services moved over. ## How did we move the different environments? We started with a lower environment because there was simply less to worry about there. There was no production data to migrate and fewer external integrations. That gave us a chance to catch dependency changes early and sort them out before staging and production moved. Staging added external integrations, test data and UAT requirements. Production was a different beast. We had to account for connectivity back to the on-prem setup, data migration, API Gateway changes and external IP allowlists. We did take on a few bits of technical debt to keep the migration going, but it was tracked so the team could come back to it afterwards. ## What did we change in deployment and security? We used GitHub Actions for CI and ArgoCD for deployments. ArgoCD also gave developers a better view of rollouts and application logs, which helped once teams started deploying into the new environment. We also tightened up security. We removed static AWS credentials where they existed and switched those workloads over to AWS roles. We put WAF in front of public endpoints and moved secrets into Secrets Manager. For the AWS side, we used GuardDuty, CloudTrail and Security Hub, and VPC Flow Logs gave us a view into network activity. ## What happened after the migration was done? Provisioning a new environment went from weeks to minutes. We also got to a point where infrastructure was being created through automation instead of manually. The platform maintained a 99.5% uptime SLO without breaching its monthly error budgets. The infrastructure team didn’t have to plan weeks ahead for physical capacity anymore. They could add capacity when they needed it, and spend less time maintaining the on-prem setup and the tooling around it. --- # Automating multi-tenant AWS infrastructure for an AI platform Client: A Salesforce AI platform Offerings: Platform Engineering, Reliability Engineering Canonical: https://www.infraspec.dev/case-studies/multi-tenant-ai-platform Enterprise customer environments went from days of manual setup to automated provisioning in under an hour. We worked with a Salesforce AI platform that helps enterprises cut Salesforce implementation time from months to days. As more enterprise customers came in, setting up the infrastructure for each one was taking longer than it should and slowing the whole onboarding process down. A two-person team from Infraspec built a consistent multi-tenant AWS setup with enterprise security and compliance requirements built in. ## Highlights - 52 min: customer environment provisioning - 60%: lower infrastructure costs - 3×: enterprise onboarding capacity ## What was slowing enterprise onboarding down? A new AWS account could take three to four days to set up for each enterprise customer. Security controls varied between environments, making it difficult to demonstrate the controls required by regulated industries and getting in the way of enterprise deals. The development team was also spending around 60% of its time on infrastructure rather than the product. ## How did we standardise each customer environment? We built the setup around AWS Organizations, with separate organisational units for security, production, platform services and developer sandboxes. Each customer received a separate AWS account, while logging and audit data went into a central account. Service Control Policies applied 43 consistent guardrails. Terraform modules covered repeatable infrastructure including VPCs, ECS clusters, RDS PostgreSQL, S3, KMS key management and Secrets Manager. API Gateway handled webhook ingress. Changes followed a GitOps flow: pull request, Terraform plan, security scan, manual approval and production apply. ## How was provisioning automated for a new customer? AWS Step Functions orchestrated the new-customer provisioning flow. Control Tower created the account with the right baseline. VPCs, Transit Gateway and PrivateLink provided networking, followed by GuardDuty, Security Hub and CloudTrail for security. ECS provided compute, while Multi-AZ RDS, S3 and DynamoDB supplied the data infrastructure. The entire flow took about 52 minutes instead of three to four days. ## How were application releases handled? GitHub held source control with branch protection, and GitHub Actions handled builds. Rolling deployments included automatic rollback. Grafana and New Relic monitored production. The platform was doing around 15 to 20 production deployments daily. Rollbacks took under a minute when needed, and deployment success was 99.9%. ## How did the setup address enterprise security and compliance? Network isolation used Transit Gateway and security groups, with WAF protecting public endpoints. Secrets were rotated every 30 days through AWS Secrets Manager. VPC Flow Logs and GuardDuty helped detect suspicious activity. The work supported SOC 2 Type II and ISO 27001 certification, including monthly penetration testing through approved vendors and security controls for S3 and application workloads. SOC 2 Type II was achieved in four months; both certifications were complete within six months. The ISO 27001 audit had zero critical findings. ## What changed for the business? Customer infrastructure could be provisioned in under an hour with 100% automation and zero manual steps. The team could onboard three times as many enterprise customers, while infrastructure costs fell 60%. Uptime across customer environments was 99.95%. New enterprise deals closed within 90 days of SOC 2 certification, and the sales cycle fell from four months to six weeks. --- # Docker Swarm to Amazon ECS migration Client: An education technology company Offerings: Platform Engineering, Reliability Engineering Canonical: https://www.infraspec.dev/case-studies/docker-swarm-to-ecs A six-person engineering team traded manual cluster upkeep for an easier-to-run AWS environment and roughly 25% lower infrastructure costs. An education technology company focused on students' reading skills had six engineers building the product and running the infrastructure behind it. As the product grew, the team wanted infrastructure to demand less of their time. We migrated container workloads from Docker Swarm to Amazon ECS and modernised the supporting AWS environment. ## Highlights - ~25%: lower direct infrastructure costs - 6: engineers on the client team - ECS: replaced Docker Swarm ## Why rethink the infrastructure setup? The application ran on AWS with Docker Swarm on EC2. Usage was concentrated around school hours and weekdays, but EC2 scaling still needed manual attention. Upgrades and configuration changes took time away from the six-person engineering team. Infrastructure as Code had drifted from the actual AWS environment. Custom scripts and manual changes meant the code no longer fully represented what was running. Docker Swarm needed regular patching, too, and cost optimisation was difficult. ## Where was the real scaling challenge? Docker Swarm could scale application workloads, but adding or removing the EC2 capacity beneath them still needed a person. Demand followed the school day, yet engineers adjusted capacity by hand. The replacement needed to stay on AWS, remove manual scaling and maintenance, remain approachable for a small team and avoid a significant cost increase. ## Why Amazon ECS with EC2? ECS fit naturally into the AWS environment and removed orchestration work without a steep learning curve. Keeping EC2 for compute made sense for this modest workload and allowed capacity changes to be automated at a sensible cost. ## What changed in the infrastructure? We moved the workloads from Docker Swarm to ECS and used Terraform to manage EC2, the Application Load Balancer, Route 53 domains and ACM certificates. This replaced the mix of outdated infrastructure code, scripts and manual changes. We replaced self-managed HAProxy with an AWS Application Load Balancer, moved manual SSL renewal to AWS Certificate Manager and used AWS Systems Manager for application configuration, reducing the need to SSH into systems. ## How did the team take ownership? We documented the solution and troubleshooting paths, then ran knowledge-transfer sessions covering the codebase and infrastructure. Engineers took on small hands-on tasks with pairing where useful. The handover continued until they were comfortable running the environment themselves. ## What changed after the migration? Direct infrastructure costs fell by approximately 25%. The new setup needed less ongoing attention and was easier for the six-person team to extend and upgrade alongside its product work. --- # Using DORA metrics to understand software delivery performance Client: An education technology company Offerings: Platform Engineering, Reliability Engineering Canonical: https://www.infraspec.dev/case-studies/dora-metrics-delivery A clearer delivery workflow and ongoing team-level metrics replaced fragmented tooling and one-off surveys. We worked with an education technology company whose engineers were running into friction in software delivery. Leadership lacked a consistent view of delivery performance and reliability across teams. Alongside the engineering and platform teams, we improved the delivery setup and established DORA metrics as a common way to see bottlenecks and decide what needed attention next. ## Highlights - 4: DORA measures tracked - 1: shared source control and CI platform - Ongoing: team-level delivery visibility ## What was getting in the way of delivery? Jenkins pipelines were managed by the infrastructure team, leaving application teams dependent on them for build changes. Jenkins was on a very old version, role-based access control was not properly set up, and the pipeline DSL was hard to use. Source control and CI lived in separate tools, so developers moved between systems for an everyday workflow. ## What could be fixed before DORA came in? Some issues were already obvious without metrics. We moved teams to GitLab and introduced GitLab runners for CI. Developers could own their build pipelines, with source control and CI in the same platform. GitLab's YAML-based pipeline configuration and documentation made changes easier for teams to understand and maintain. ## Where did DORA come in? Leadership still needed a consistent view of delivery across teams, including where reliability suffered and work slowed down. We used deployment frequency, lead time for changes, change failure rate and time to restore service. We began with a survey, checked the inputs with engineering teams, then built reports for each team's performance across the four measures. ## What did teams do with the data? Reports let teams compare their performance with one another and with broader DORA benchmarks. Platform engineers used the findings to prioritise work. We also worked with individual teams on tooling and platform changes aimed at the areas the metrics highlighted. ## How did the team move beyond surveys? The survey gave a starting point, not a sustainable source of fresh data. We connected the measures to deployment and incident-management tooling so they could feed dashboards without asking teams to fill in another survey. Engineering leadership gained an ongoing team-level picture of delivery performance instead of a snapshot from one point in time. --- # Infrastructure modernisation for a fast-growing hyperlocal platform Client: A large hyperlocal grocery delivery company Offerings: Reliability · Observability, Reliability Engineering, Platform Engineering Canonical: https://www.infraspec.dev/case-studies/hyperlocal-platform-modernization A proactive platform roadmap improved detection, delivery and cost control while the business kept growing. A large hyperlocal grocery delivery company in India was handling roughly 250,000 orders a day. With new funding and ambitious expansion plans, its CTO and architect wanted to know which parts of the platform would struggle as the business grew, before an incident forced the question. Infraspec assessed the setup, built a prioritised roadmap and embedded with the platform team to work through the highest-impact initiatives. ## Highlights - 58%: lower mean time to detect - 67%: shorter lead time to change - $161k: in infrastructure savings ## Why modernise when nothing was broken yet? The next phase of growth would put pressure on delivery speed and reliability. Without an active incident, the team had room to assess the platform before those pressures became harder to manage. We spent a week alongside the teams reviewing applications and infrastructure and gathering stakeholder input. The findings became an action plan with clear priorities. ## How did the team decide what to tackle first? The roadmap weighed impact, return on investment and ownership. Some initiatives addressed reliability and visibility; others addressed delivery speed, infrastructure cost or operational risk. Each priority needed a rationale stakeholders could support and a path the internal platform team could continue to own. Infraspec embedded with the platform organisation to execute those priorities transparently alongside the team. ## What ended up on the roadmap? From March 2023 to April 2024, work included a centralised observability platform, branch-based continuous delivery, FinOps adoption, API Gateway changes, Karpenter-based autoscaling and canary deployments with ArgoCD. API Gateway reduced the public API surface by roughly 60%. The newer autoscaling setup reduced recovery risk and helped optimise cloud spend. ## What changed with observability? A centralised observability platform was introduced between March and June 2023. Mean time to detect dropped by 58%, while telemetry gaps fell by 70%. ## What changed in the release process? Branch-based continuous delivery cut lead time to change by 67%. Canary deployments with ArgoCD halved the change failure rate, with a typical release affecting only about 5% of users. ## What changed about infrastructure cost? FinOps made infrastructure cost a shared responsibility across the organisation and contributed $161,000 in savings. Even as the business scaled, infrastructure spend grew more slowly than business volume. ## How did the changes stick? We remained embedded with the platform team throughout execution. Documentation, infrastructure-as-code and repeatable runbooks reduced dependency on any one person's knowledge and helped the internal team continue to own the work. The company kept growing around 10% month on month without reliability becoming a bottleneck. Developer productivity and release velocity improved, while automation and simpler workflows freed up engineering time for higher-value work. Starting before a major outage gave the team room to make lasting changes. --- # Exploring SPIFFE and SPIRE: How Workloads Prove Who They Are Without Secrets By Sreyas P Pradeep · 2026-11-25 Canonical: https://www.infraspec.dev/blog/exploring-spiffe-and-spire Take a small company running a `payments-api` service. It runs as pods in a Kubernetes cluster in the company's own data centre, and it has to: 1. **read invoices from an S3 bucket** in AWS, 1. **call an internal** `ledger` **service**, which must accept requests only from `payments-api`, and 1. **be called by a** `checkout` **service** that runs on a VM, not in Kubernetes. The setup, with the identity question each connection has to answer: ![checkout VM, payments-api pods and ledger in the company data centre, with an S3 bucket in AWS, each connection asking whether the caller is really who it claims to be.](https://www.infraspec.dev/lovable-assets/blog/spiffe/connections.png) Each of these needs the same thing: one side has to prove to the other that it is `payments-api` (or `checkout`). Here is how teams usually try to do that, and where each attempt breaks. ### Attempt 1: trust the network The `ledger` service allows requests from the subnet where `payments-api` runs, and the S3 bucket policy allows the data centre's public IP. This fails because network location isn't identity. Pod IPs change whenever a pod is replaced, and every other pod on the same nodes shares the same subnet and the same outbound IP. A firewall rule can say where a request came from, but not which service sent it. Any compromised pod in the cluster can call `ledger` and read the bucket. ### Attempt 2: give the service a secret Next, the team creates an IAM user for `payments-api`, puts its access key in a Kubernetes Secret, and gives `ledger` a shared API key. This works, and it creates new problems: - The AWS key never expires. Rotating it means updating the Secret, restarting pods and hoping nothing else uses the old key, so rotation gets postponed. - The key gets copied: into a CI variable to run integration tests, onto a laptop to debug, into a Helm values file by mistake. - Whoever has the key is `payments-api` as far as AWS and `ledger` can tell. The key proves possession, not identity. ### Attempt 3: put the secrets in a vault So the team moves the keys into a secrets manager such as HashiCorp Vault, which can even issue short-lived AWS credentials. That is a real improvement, but every workload now has to log in to Vault first. Inside Kubernetes, `payments-api` can log in with its service account token. The `checkout` VM has no such token, so it usually gets a static login credential (an AppRole secret ID, for example) that someone has to deliver to the machine. The team is back to one secret that gives access to all the others. This is the **secret zero** problem: somewhere, a first credential has to be handed to the workload. ### Attempt 4: use the cloud's own workload identity On EKS, the team would use IAM Roles for Service Accounts or EKS Pod Identity: pods get AWS credentials based on their Kubernetes service account, with no keys at all. GKE and Azure have similar features. But the cluster runs in the company's data centre, not on EKS. Even if it did run on EKS, that identity is only understood by AWS. It means nothing to the `ledger` service, and the `checkout` VM has no Kubernetes service account at all. Each platform has its own identity system, and none of them work across platforms. ## Four requirements no attempt met, and how SPIFFE meets them The four attempts add up to five requirements. `payments-api` needs an identity that: | Requirement | Why the earlier attempts fell short | | --- | --- | | Names the service, not its IP or host | Network rules can't tell services apart (attempt 1) | | Is issued automatically, with nothing pre-shared | Static keys and vault logins need a first secret (attempts 2 and 3) | | Is short-lived and rotated without anyone acting | Static keys live until someone rotates them (attempt 2) | | Works on Kubernetes, VMs and bare metal, in any data centre or cloud | Cloud identity only works inside one cloud (attempt 4) | | Is accepted by internal services and by AWS and other clouds | Cloud identity means nothing to internal services (attempt 4) | **SPIFFE** is an open standard built for these requirements, and **SPIRE** is the software that implements it. In the SPIFFE model: - `payments-api` gets a name, `spiffe://example.org/ns/payments/sa/api`, that doesn't depend on where it runs. - It gets proof of that name **without presenting any secret**: the system inspects the running process and the node it's on, and issues an identity document only if they match a registered rule. - Those documents last minutes to an hour and are renewed automatically. - The same identity works for mutual TLS with `ledger` and `checkout`, as a token for internal APIs, and, through standard OIDC federation, to get temporary AWS credentials with no AWS keys anywhere. ## SPIFFE: the specification for workload identity **SPIFFE** (Secure Production Identity Framework For Everyone) is a set of open specifications, graduated in the CNCF, that define how a workload is identified and how it proves that identity. SPIFFE is a standard, not a product. It defines four building blocks. ### SPIFFE ID A SPIFFE ID is a URI that uniquely identifies a workload, for example `spiffe://example.org/ns/payments/sa/api`. The authority part, `example.org`, is the **trust domain**: the trust boundary of one identity system, typically an organisation or an environment. The path identifies the workload within the trust domain; on Kubernetes the common convention is namespace plus service account. The ID describes what the workload is, not its IP or host. ### SVID (SPIFFE Verifiable Identity Document) An SVID is the cryptographically verifiable document a workload presents to prove its SPIFFE ID. There are two formats: | | X.509-SVID | JWT-SVID | | --- | --- | --- | | Format | X.509 certificate with the SPIFFE ID in the URI SAN | JWT signed by the trust domain, with the SPIFFE ID in the `sub` claim | | Typical use | Mutual TLS between services | Bearer token for APIs, cloud providers and Vault, scoped by the `aud` claim | | Lifetime | Short, typically an hour | Shorter, typically minutes | ### Trust bundle The trust bundle is the set of public keys (CA certificates for X.509-SVIDs and signing keys for JWT-SVIDs) for a trust domain. A relying party uses it to validate SVIDs locally, without calling the issuer. Exchanging bundles between trust domains is called **federation**, and lets workloads in different trust domains authenticate each other. ### Workload API The Workload API is a local API, exposed over a Unix domain socket on each node, through which a workload fetches its SVIDs and the trust bundle. The workload presents no credential when it calls it. The implementation identifies the caller by inspecting the calling process, a step called **workload attestation**. Requesting an identity without a pre-shared secret is what removes the secret zero problem. ## SPIRE: the reference implementation of SPIFFE **SPIRE** (the SPIFFE Runtime Environment) is the production-grade reference implementation of the SPIFFE specifications, also a graduated CNCF project. It issues SVIDs, attests nodes and workloads, and rotates keys and SVIDs automatically. A Kubernetes deployment typically consists of four components: ![SPIRE architecture: workloads call the SPIRE Agent on each node, which syncs with the SPIRE Server in the control plane alongside the OIDC Discovery Provider and the SPIRE Controller Manager, while relying parties fetch keys over HTTPS.](https://www.infraspec.dev/lovable-assets/blog/spiffe/architecture.png) ### SPIRE Server: the signing authority of the trust domain The SPIRE Server is the central authority of a trust domain. It: - **runs the signing CA** that issues X.509-SVIDs and signs JWT-SVIDs, and rotates its own signing keys. It can act as the root CA or chain to an existing PKI through an upstream authority. - **stores registration entries.** An entry maps a set of **selectors** (properties of a workload) and a parent ID (the agent or node it may run under) to a SPIFFE ID. For example: pods with `k8s:ns:payments` and `k8s:sa:api` receive `spiffe://example.org/ns/payments/sa/api`. - **performs node attestation** on the server side, verifying the evidence each agent presents before issuing the agent its own SVID. - **publishes the trust bundle** to agents, and optionally to external locations. Its state is a datastore (SQLite, or PostgreSQL/MySQL for high availability) and a key manager that holds the CA private keys (on disk, in memory, or in a KMS such as AWS KMS). ### SPIRE Agent: node attestation and workload attestation The SPIRE Agent runs on every node (a DaemonSet on Kubernetes) and serves the Workload API to local workloads. Workloads never talk to the server directly. - **Node attestation.** At startup the agent proves the node's identity to the server with platform-issued evidence: a projected Kubernetes service account token (`k8s_psat`), an AWS instance identity document (`aws_id`), GCP and Azure equivalents, a TPM, or a one-time join token. - **Workload attestation.** When a process calls the Workload API, the agent reads the caller's PID from the kernel and collects selectors about it through workload attester plugins: namespace, service account, labels and image from the kubelet (`k8s`), or UID and binary path (`unix`). It returns the SVIDs whose registration entries match those selectors. - **Caching and rotation.** The agent caches SVIDs and renews them before they expire. New X.509-SVIDs are pushed to workloads that hold an open Workload API stream, and JWT-SVIDs are minted on request, so rotation needs no restarts. On Kubernetes, the SPIFFE CSI driver mounts the Workload API socket into pods, so workloads don't need `hostPath` volumes. ### SPIRE Controller Manager: Kubernetes-native workload registration Pods are created and deleted continuously, so registration entries can't be maintained by hand. The SPIRE Controller Manager runs alongside the SPIRE Server and reconciles registration entries from Kubernetes custom resources: - `ClusterSPIFFEID`: a template that assigns SPIFFE IDs to every pod matching a pod and namespace selector - `ClusterStaticEntry`: a fixed entry, typically for workloads outside the cluster - `ClusterFederatedTrustDomain`: a federation relationship with another trust domain A single resource can cover the whole cluster: ``` apiVersion: spire.spiffe.io/v1alpha1 kind: ClusterSPIFFEID metadata: name: by-service-account spec: className: spire-mgmt-spire # must match the controller manager's class spiffeIDTemplate: "spiffe://{{ .TrustDomain }}/ns/{{ .PodMeta.Namespace }}/sa/{{ .PodSpec.ServiceAccountName }}" podSelector: {} ``` The `className` matters: the controller manager only processes resources whose class matches its own, and with the official Helm charts it ignores resources without a class by default. Those charts also ship a default `ClusterSPIFFEID` with this exact template, so a fresh install already gives every pod a namespace and service account based identity. The controller creates an entry when a matching pod appears and removes entries that no longer match, so a workload's identity follows its Kubernetes namespace and service account automatically. ### OIDC Discovery Provider: federating SPIRE with OIDC relying parties Token-exchange services such as AWS STS, GCP Workload Identity Federation and Azure federated credentials don't read SPIFFE trust bundles, but they do trust **OpenID Connect (OIDC)** identity providers. A JWT-SVID is a standard signed JWT, so SPIRE only needs to publish its signing keys the way OIDC expects. The OIDC Discovery Provider serves: - `/.well-known/openid-configuration`: the discovery document, containing the issuer and the JWKS URI - `/keys`: the **JWKS** (JSON Web Key Set), SPIRE's current public JWT signing keys It reads the keys from the SPIRE Server API or an agent's Workload API and picks up key rotation automatically. It must be reachable over public HTTPS with a publicly trusted certificate. The server's `jwt_issuer` setting must be set to the provider's URL, so the `iss` claim in every JWT-SVID matches the issuer the provider advertises, exactly. Any OIDC relying party (AWS IAM, GCP Workload Identity Federation, Azure federated credentials, HashiCorp Vault's JWT auth) can then validate SPIRE-issued JWT-SVIDs. ## Issuing an SVID, from pod creation to rotation Putting the components together, this is how `payments-api` receives its identity: ![Sequence diagram: the Kubernetes API, Controller Manager, SPIRE Server, SPIRE Agent and payments-api pod exchange messages from pod creation through workload attestation to SVID renewal.](https://www.infraspec.dev/lovable-assets/blog/spiffe/svid-issuance.png) The agent itself was attested once, when it started on the node. ## Authenticating the three connections with SPIFFE identities Each connection from the opening example now uses the same identity. **payments-api → ledger: mutual TLS with X.509-SVIDs.** Both sides present X.509-SVIDs during the TLS handshake and validate the peer's certificate against the trust bundle. **ledger** then authorises the caller by SPIFFE ID, accepting only `spiffe://example.org/ns/payments/sa/api`. This can be done in code with the SPIFFE libraries (go-spiffe, java-spiffe, py-spiffe). **checkout VM → payments-api: one trust domain across platforms.** The VM runs its own SPIRE agent, which joins the same SPIRE Server using a node attester suited to an on-prem machine, such as `join_token`, `x509pop` or `tpm_devid`. A registration entry on the server, parented to that agent and using `unix` selectors (for example the process's user ID), assigns `checkout` its SPIFFE ID. The VM workload then receives an X.509-SVID from the same trust domain, so `payments-api` validates it exactly as it would a pod's. **payments-api → S3: keyless AWS access with JWT-SVIDs.** SPIRE's issuer URL is registered in AWS as an IAM OIDC identity provider with audience `sts.amazonaws.com`. An IAM role's trust policy allows `sts:AssumeRoleWithWebIdentity` only for that provider, that audience and one subject: ``` "Condition": { "StringEquals": { "oidc.example.org:aud": "sts.amazonaws.com", "oidc.example.org:sub": "spiffe://example.org/ns/payments/sa/api" } } ``` The pod requests a JWT-SVID with that audience and exchanges it with AWS STS for temporary credentials. The AWS SDKs do this when `AWS_ROLE_ARN` and `AWS_WEB_IDENTITY_TOKEN_FILE` are set; the spiffe-helper sidecar keeps a fresh JWT-SVID in that file. ![payments-api exchanges a JWT-SVID with AWS STS, which validates the signature through the OIDC Discovery Provider's JWKS, then reads the S3 bucket with temporary credentials.](https://www.infraspec.dev/lovable-assets/blog/spiffe/aws-sts.png) No AWS access key exists in the cluster, in Git or in CI. The same pattern applies to GCP, Azure and Vault. ## Static secrets compared with SPIFFE identities How the two approaches compare: | | Static secrets | SPIFFE identities (SVIDs) | | --- | --- | --- | | Issuance | Created and distributed by a person | Issued automatically after node and workload attestation | | Lifetime | Until someone rotates it | Minutes to an hour | | Rotation | Manual | Automatic, handled by the agent | | If leaked | Valid until revoked | Expires on its own | | What it proves | Possession of the key | The workload's identity, attested by the platform | | Scope | One credential per system | One identity for mTLS, APIs and cloud federation | ## Operational considerations when running SPIRE - **Protect the SPIRE Server.** Its signing keys are the root of trust. Run it highly available with a shared datastore, back it up, and prefer a KMS-backed key manager. - **Keep the OIDC Discovery Provider available.** If it is unreachable or its certificate expires, relying parties can't fetch the keys and `AssumeRoleWithWebIdentity` calls start failing. - **Match SPIFFE IDs exactly.** Use `StringEquals` on the full ID in trust policies and authorisation rules; a wildcard such as `spiffe://example.org/*` admits every workload in the trust domain. - **Treat Kubernetes RBAC as part of identity.** If IDs derive from namespace and service account, anyone who can run a pod with that service account receives that identity. - **Use a distinct audience per relying party**, so a JWT-SVID issued for one service can't be replayed against another. ## SPIFFE defines the identity, SPIRE issues and proves it Every attempt in the opening example tied identity to a network location, a secret or a single platform. SPIFFE replaces all three with a SPIFFE ID and short-lived SVIDs that work anywhere. SPIRE implements it: the server signs SVIDs and holds registration entries, the agent performs node and workload attestation, the controller manager keeps entries in sync with Kubernetes, and the OIDC Discovery Provider lets cloud providers validate JWT-SVIDs. The result is one identity for mutual TLS, API authentication and keyless cloud access, with no long-lived secrets. ## References - SPIFFE overview and specifications: [https://spiffe.io/docs/latest/spiffe-about/overview/](https://spiffe.io/docs/latest/spiffe-about/overview/) - SPIRE concepts: [https://spiffe.io/docs/latest/spire-about/spire-concepts/](https://spiffe.io/docs/latest/spire-about/spire-concepts/) - SPIRE Controller Manager: [https://github.com/spiffe/spire-controller-manager](https://github.com/spiffe/spire-controller-manager) - OIDC Discovery Provider: [https://github.com/spiffe/spire/tree/main/support/oidc-discovery-provider](https://github.com/spiffe/spire/tree/main/support/oidc-discovery-provider) - spiffe-helper: [https://github.com/spiffe/spiffe-helper](https://github.com/spiffe/spiffe-helper) - AWS IAM OIDC identity providers: [https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html) --- # Which Logs Can You Delete? Deciding What's Necessary Before You Cut By Nimisha G J · 2026-11-17 Canonical: https://www.infraspec.dev/blog/which-logs-can-you-delete Every conversation about observability cost ends up in the same place: drop the unnecessary logs. It's good advice. It's also incomplete. Nobody disagrees that unnecessary logs should go. The hard part is knowing which ones they are. ## The Problem With "Unnecessary" Look at any log line in isolation and it seems useful. Someone added it for a reason. Maybe it helped debug an issue two years ago. Maybe it will help debug one next week. Nobody wants to be the person who deleted the one line that would have explained the outage. So the cleanup usually goes one of two ways. Either the team cuts conservatively, removes a few obvious debug lines, saves 5%, and moves on. Or someone sets a hard budget, drops whole services to `WARN`, and the next incident is investigated in the dark. Both happen for the same reason: there's no shared definition of what makes a log necessary. Here's the shift that makes the decision easier: **necessary isn't a property of the log line. It's a property of how the log is used.** The same line can be essential at ten per minute and pure waste of resources and become expensive at ten thousand per second. The question isn't "is this log useful?" It's "is this log worth what it costs, in this form, at this volume?" ## Start With Where the Volume Is Before judging individual lines, find out where the bytes go. Group your logs by message template, not by exact message. `User 4821 logged in` and `User 9310 logged in` are the same pattern. Most log backends can do this for you, and if yours can't, stripping numbers and IDs with a regex gets you most of the way. Then sort by volume. In almost every system, a handful of patterns account for most of the bill. The top twenty patterns are often 70-80% of total volume. That's where your effort goes. The long tail of rare lines costs almost nothing, and arguing over them is time you won't get back. ## Five Questions for Every Log Pattern Take each high-volume pattern and run it through these questions in order. ### 1. Who reads it, and when? Every log needs a reader. That reader can be a person during an incident, an alert rule, a dashboard, an audit, or a downstream pipeline. Check your query history. Most backends record which queries ran and what they matched. If a pattern hasn't appeared in a search, alert or dashboard in the last 90 days, it's a candidate. Not an automatic delete, a candidate. If you can't name a reader, the log is being written for no one. ### 2. Does it say something nothing else says? A lot of log volume is just duplicate signals. - **Request started / request completed** lines repeat what your traces already record, with less structure. - **"Processed 500 records"** every few seconds is a counter pretending to be a log. That's a metric. - **Logs that make up for a thin error log.** Either the same error gets logged at every layer it passes through, giving you five lines for one failure, or every step of every request gets logged as a breadcrumb in case something fails later. The second is the expensive one, because you pay for it on every successful request too. Let the trace show the path, and log the error once, with full context, where it's handled. If the information already exists in a span, a metric or another log, this copy is the one to drop. ### 3. What decision does it support? A useful log changes what you do next. An error with the order ID, the downstream service and the response code tells you where to look. `Something went wrong` tells you what you already inferred, that something went wrong. If reading the line doesn't help you decide anything, it isn't earning its place, no matter how often it fires. ### 4. What happens if it's gone during an incident? This is the question that protects you from cutting too deep. Some logs are rarely read because they're only needed when things break. Query history says nobody looked at them. The next outage says otherwise. Before dropping a pattern, imagine the worst incident in that service and ask whether this line would be part of the investigation. If the answer is yes, keep it. You might change its form, but don't lose it. ### 5. Is it required regardless? Audit trails, security events, access logs and anything under compliance retention aren't yours to optimise away. They don't need a reader this quarter. They need to exist when someone asks. These go in their own bucket with their own retention, and they stay out of the cost discussion. ## Keep, Transform or Drop The questions don't give you a yes or no. They give you one of three outcomes, and the middle one is where most of the savings are. **Keep as is.** Errors with context. State changes: a payment captured, a job failed, a config reloaded. Decisions the system made: a request was rate limited, a fallback kicked in, a feature flag routed a user. Audit and security events. These are low volume and high value. They're rarely the problem. **Transform.** The log is answering a real question, just in an expensive way. - **Turn counts into metrics.** If you only ever look at how many, you don't need every line. - **Move request context onto spans.** Attributes on a trace are cheaper than a parallel log stream saying the same thing. - **Sample the success path.** Keep every error, keep 1% of successful requests. You still see what normal looks like. - **Lower the level, not the line.** Move it to `DEBUG` and turn it on per service when you need it. - **Tier the retention.** Seven days hot, the rest in cheap storage. Most logs are only searched in the first few days. **Drop.** No reader, no decision, no incident value, no compliance need. Health check logs. Heartbeats. `Entering function` traces left from a debugging session. Library chatter logged at `INFO` by default. Full payload dumps. Stack traces repeated on every retry. Most of these are safe to drop because something else already does their job. A health check log can go once the orchestrator restarts failing instances and an alert fires when checks keep failing. Before you drop a pattern, make sure the alert or handler that replaces it actually exists. Then you can delete it with confidence, because you've checked. ## When a Log Should Be a Metric Think about how a developer actually uses a log like `User logged in`. They open the observability backend, search for the pattern, pick a time range, and look at the histogram. Did logins drop after the deploy? Is checkout slower than yesterday? Are orders following the usual daily curve? In most cases, they're not reading the lines. They're looking at the shape. And every time they do, the backend scans and counts millions of lines to draw a chart a metric would have drawn instantly. Of all the transforms, this one usually saves the most, and it's the easiest to miss. Look at lines like these: ``` User 4821 logged in User 9310 logged in Order 77120 placed Order 77121 placed Payment succeeded for order 77121 ``` Now ask what you actually do with them. Almost always, the answer is a count. How many logins per minute. How many orders were placed today. Whether payments dropped after the last deploy. Nobody reads the millionth `User logged in` line. They count them. If the question is "how many" or "how fast", the answer is a metric. Instead of writing a line for every login, increment a counter: ``` user_logins_total{method="password", result="success"} orders_placed_total{region="eu"} payment_duration_seconds{provider="stripe"} ``` A counter costs the same whether it's incremented ten times or ten million times. A log costs more with every event. At low traffic the difference is invisible. At scale, the log version of a business event can quietly become one of your biggest patterns. You also get a better answer. A metric is already aggregated, so dashboards and alerts on it are fast and cheap. The log version has to be scanned and counted every time someone asks the question. Two cases where the log still earns its place: - **You need the individual event.** Failed logins for security, or a specific order a customer is asking about. Keep the failures and the exceptions as logs. Count the successes. - **You need to drill into one occurrence.** That's what traces are for. The span for that request carries the IDs, so you don't need a log line to find it. Keep labels on the metric low-cardinality: method, region, result. User IDs and order IDs don't belong on a metric. They belong on the span or the log that's kept for the exceptions. A simple test: if the only thing you ever do with a log pattern is put it in a `count()` query, it was a metric all along. ## Make It a Habit, Not a Project A one-time cleanup decays. Six months later, new services have added new noise, and the bill is back where it started. Two small habits keep it in check: - **Review the top patterns monthly.** Ten minutes on the biggest movers. A new pattern in the top twenty is either a bug or a decision someone should have made on purpose. - **Ask the questions at write time.** When a log line goes into a pull request, ask who reads it and what it costs at production volume. It's much cheaper to not add a log than to find it and remove it later. ## Cut With Confidence Removing unnecessary logs is the right first step for reducing observability cost. But "unnecessary" is a decision, not a feeling, and it should be made against how logs are actually used. When you know which logs have a reader, which duplicate other signals, which only matter during an incident and which are required no matter what, the cut stops being a gamble. You spend less, and you still see everything you need when it matters. Put together, it looks something like this. The patterns worth keeping are rarely the ones driving the bill. ![Original log-volume chart comparing eleven message patterns, their ingestion volumes and monthly costs, with keep, transform and drop decisions. Illustrative figures, priced at $0.50 per GB.](https://www.infraspec.dev/lovable-assets/blog/log-cleanup/log-volume-by-pattern.png) --- # Exporting Langfuse LLM metrics to the OpenTelemetry Collector By Akshay Francis · 2026-11-04 Canonical: https://www.infraspec.dev/blog/exporting-langfuse-llm-metrics-to-opentelemetry-collector Teams building LLM applications often use Langfuse to trace model calls and track cost, latency, and quality. Their dashboards and alerts, however, usually live in a separate monitoring tool such as SigNoz, Grafana, or Prometheus. To track LLM behavior next to application and infrastructure metrics, they need to get Langfuse metrics into that tool. In this post, we explain why Langfuse metrics cannot reach these tools out of the box and how we solved it. ## What Langfuse is Langfuse is an observability platform for LLM applications. It captures each model call, including the input prompt, model output, latency, token usage, and cost. It is available as a managed service or can be self-hosted. Applications send data to Langfuse through its SDKs or via OpenTelemetry. The resulting traces and observations are available in the Langfuse UI and through its public API. ## Data model Langfuse organizes data into the following entities: | Entity | Description | | --- | --- | | Trace | A single end-to-end request, for example one user question and the response returned by a chatbot. | | Observation | A single step within a trace, such as a retrieval from a vector database or a model call. Observations can be nested. Langfuse supports several observation types, including span, agent and tool. | | Generation | The observation type for an LLM call. It records model details, prompt/completion data, token usage, cost, and timing. | | Score | An evaluation result attached to a trace or observation. Scores can come from user feedback, LLM-as-a-judge evaluators or manual review. | ## The problem Teams that run LLM applications in production usually already have a monitoring platform, such as SigNoz, Grafana, or Prometheus, for their services and infrastructure. In many of these setups, an OpenTelemetry Collector collects metrics from each source and forwards them to the platform over OTLP. Langfuse calculates the metrics that describe LLM behavior, such as model cost, token usage, latency, and evaluation scores. These metrics stay inside Langfuse. The OpenTelemetry Collector has no receiver for Langfuse, so it cannot collect them, and they never reach the monitoring platform where the rest of the system's metrics live. ![Original diagram showing the gap between Langfuse and the OpenTelemetry Collector](https://www.infraspec.dev/lovable-assets/blog/langfuse/collector-gap.jpeg) The OpenTelemetry Collector has no way to read metrics from Langfuse Our team ran into this gap with SigNoz, which we use for dashboards and alerts. We wanted LLM cost and latency on the same dashboards, and under the same alerting rules, as our service metrics. To get there, we first needed a way to read Langfuse metrics programmatically. Langfuse provides this through its Metrics API. ## How the Langfuse Metrics API works The Metrics API returns the same aggregated numbers that power the Langfuse dashboards. It has a single endpoint, GET /api/public/v2/metrics. Each request describes what to calculate in a JSON query, passed in the query parameter. A query has five parts: | Part | Purpose | Example | | --- | --- | --- | | view | The data to read from | observations | | dimensions | The fields to group results by | model name | | metrics | What to calculate, as a measure and an aggregation | sum of totalCost | | filters | Optional conditions to narrow the data | only LLM calls ( type = GENERATION ) | | fromTimestamp, toTimestamp | The time range to cover | one day | Requests are authenticated with the public and secret key of a Langfuse project. The following example requests the total LLM cost per model for one day: ``` curl -G -u "pk-lf-...:sk-lf-..." \ "https://cloud.langfuse.com/api/public/v2/metrics" \ --data-urlencode 'query={ "view": "observations", "dimensions": [{"field": "providedModelName"}], "metrics": [{"measure": "totalCost", "aggregation": "sum"}], "filters": [{"column": "type", "operator": "=", "value": "GENERATION", "type": "string"}], "fromTimestamp": "2026-10-15T00:00:00Z", "toTimestamp": "2026-10-16T00:00:00Z" }' ``` The API returns the result as a list of JSON rows. Each row contains the grouping values and one field for each calculated metric, named _, such as sum_totalCost: ``` { "data": [ {"providedModelName": "gpt-4o", "sum_totalCost": 0.4213}, {"providedModelName": "gpt-4o-mini", "sum_totalCost": 0.0388} ] } ``` This gives us the data we need. The next question is whether the OpenTelemetry Collector can read it. ## How the OpenTelemetry Collector collects metrics To collect metrics from a service over HTTP, the OpenTelemetry Collector uses the Prometheus receiver. The receiver scrapes a /metrics endpoint at a fixed interval with a plain GET request. It expects the response in the Prometheus text format, where each line has a metric name, a set of labels, and a value: ``` # HELP langfuse_total_cost_usd Total cost in USD in the window. # TYPE langfuse_total_cost_usd gauge langfuse_total_cost_usd{model="gpt-4o"} 0.4213 langfuse_total_cost_usd{model="gpt-4o-mini"} 0.0388 ``` This example holds the same data as the JSON response above, in the format the Collector can read. ## The gap The Metrics API and the Prometheus receiver expect different things: | | Langfuse Metrics API | Prometheus receiver | | --- | --- | --- | | Request | A JSON query in each request | A plain GET /metrics with no parameters | | Time range | Set by the caller in every request | Not used; the receiver reads current values | | Authentication | Basic auth with a key pair per Langfuse project | Usually none | | Response | JSON rows | Prometheus text format | As a result, the Collector cannot scrape the Metrics API directly, and Langfuse does not currently expose these metrics in Prometheus format. Native Prometheus support has been requested by the community in langfuse#2508 and langfuse#3551. To connect the two, we needed a service that sits between Langfuse and the Collector. The service has to: 1. Query the Metrics API on a schedule, using each project's API keys. 1. Convert the JSON rows into metrics with names, labels, and values. 1. Serve those metrics on a /metrics endpoint for the Collector to scrape. We built this service as a custom exporter. The next section explains how it works. ## How the exporter works The Langfuse Metrics API Prometheus Exporter is a small Python service with no third-party dependencies. It takes two inputs: a list of Langfuse projects with their API keys, and a list of queries that defines which metrics to export. The exporter queries the Langfuse Metrics API, caches the result and serves it to the OpenTelemetry Collector, which forwards it to SigNoz. ![Original exporter architecture from the PDF](https://www.infraspec.dev/lovable-assets/blog/langfuse/exporter-flow.jpeg) The exporter sits between the Langfuse Metrics API and the OpenTelemetry Collector The exporter works in three steps: 1. **Query Langfuse on a schedule.** Every 60 seconds by default, the exporter runs each configured query for each Langfuse project. Because the Metrics API always needs a time range, each query asks for a rolling window that ends at the current time, such as the last 24 hours. The result is a value such as "cost in the last 24 hours", refreshed every minute. 1. **Convert the results to metrics.** Each row in the response becomes one metric sample. The grouping fields, such as model or environment, become labels, and the aggregated number becomes the metric value. The example below shows this conversion. 1. **Serve the latest results.** The exporter keeps the latest results in memory and serves them on /metrics. When the Collector scrapes the endpoint, the exporter returns these cached results. For example, a Metrics API row for cost per environment, trace name, and model: ``` {"environment": "production", "traceName": "answer-question", "providedModelName": "gpt-4o", "sum_totalCost": 0.4213} ``` becomes this sample: ``` langfuse_total_cost_usd{project="chatbot",window="86400s",environment="production",trace_name="answer-question",model="gpt-4o"} 0.4213 ``` The metrics to export are defined in a configuration file, queries.json, rather than in code. Each query in the file describes one Metrics API request: what to group by, what to measure, and the metric name and labels to publish the result under. The exporter ships with a default set of queries that covers the most common LLM metrics: cost, token usage, latency, errors, and evaluation scores. To export a different metric, you add a query to the file. The exporter also publishes metrics about its own health. After each query, it records langfuse_exporter_query_success, set to 1 if the query succeeded and 0 if it failed. If one query fails, the others keep running, so you can alert on this metric to catch a failing query before its data goes missing from your dashboards. ## Results Once the Collector scrapes the exporter, Langfuse metrics show up in SigNoz like any other metric. The dashboard below is an example built from them. It shows request volume, latency, cost, and token usage for each application, along with the health of the exporter's own queries. ![SigNoz dashboard built from Langfuse metrics exported by the exporter](https://www.infraspec.dev/lovable-assets/blog/langfuse/dashboard.jpeg) A SigNoz dashboard built from Langfuse metrics exported by the exporter You can extend it by adding or modifying queries in `queries.json`, then build your own panels and alerts on the new metrics. ## Limitations The exporter has a few constraints. - **Up to 1,000 rows per query.** The Metrics API returns at most 1,000 rows per query, and each row represents one unique combination of the fields you group by. Grouping by a field with a few values, such as model or environment, keeps the result small. Grouping by a field with thousands of values, such as user ID or session ID, can exceed the limit. When that happens, the extra rows are dropped and the exporter logs a warning. Group by fields with a small, stable set of values. - **Fixed time windows.** Each value is an aggregate over a rolling window, such as the last 24 hours, and is exported as a gauge. You cannot apply rate() or increase() to these values, or re-aggregate them over a different time range in your backend. Configure each window you need in the exporter instead. - **API load grows with configuration.** Each refresh makes one API call per project, window, and query. With 7 queries, 2 projects, and 1 window, that is 14 calls per refresh. Adding windows or projects multiplies this number. ## Conclusion Langfuse calculates the metrics that matter for LLM applications: cost, token usage, latency, errors, and evaluation scores. However, it exposes them only through a JSON API that the OpenTelemetry Collector cannot scrape. Our exporter bridges this gap. It queries the Langfuse Metrics API on a schedule, converts the results into Prometheus metrics, and serves them for the Collector to scrape. With the exporter in place, LLM metrics sit in SigNoz next to our service and infrastructure metrics, on the same dashboards and under the same alerting rules. When an alert fires, SigNoz shows what changed, and Langfuse shows the traces behind it. The exporter is available on GitHub. The README covers setup, configuration, custom queries, and deployment with Docker and Kubernetes. ## References - [Langfuse Metrics API](https://langfuse.com/docs/metrics/features/metrics-api): the API the exporter queries - [Langfuse observability data model](https://langfuse.com/docs/observability/data-model): traces, observations, and generations - [Prometheus receiver for the OpenTelemetry Collector](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/prometheusreceiver): how the Collector scrapes the exporter - [Prometheus exposition formats](https://prometheus.io/docs/instrumenting/exposition_formats/): the text format the exporter produces - [Langfuse Metrics API Prometheus Exporter](https://github.com/infraspecdev/langfuse-metrics-api-prometheus-exporter): source code --- # Scaling OTel Collectors When Push and Pull Don't Scale the Same Way By Arihant Hirawat · 2026-10-17 Canonical: https://www.infraspec.dev/blog/scaling-otel-collectors-push-and-pull This came out of a conversation with one of our engineers about a production incident she'd just been through. It sounded small at first (a pod got evicted, came back in seconds) but the more we talked through it the more it looked like a problem anyone running OTel Collector at real scale eventually runs into. We've generalised the details below, but the architecture, the numbers, and the failure mode are all real. ## Push vs. Pull, quickly Push receivers are ones where the sender initiates the connection. For example, an app instruments itself with an OTel SDK and actively sends telemetry to the collector, the collector just listens and accepts what arrives. Pull receivers work the opposite way, the collector initiates the connection, reaching out to poll or scrape a target on its own schedule, whether that's a Prometheus-style metrics endpoint or a database connection. Who reaches out to whom is what ends up mattering for how each one scales. ## The incident It started as a non-event. A routine node replacement, initiated by GCP, rescheduled the pod, the pod came back up within seconds, and nothing in the dashboards showed sustained downtime. On paper, nothing worth writing up. Except the pod that got evicted was the gateway collector, the single point every trace, log line, and business metric passed through before reaching the backend. There was no second copy of it running anywhere. The obvious fix sounds simple: run more than one. It isn't, and figuring out why is really what this post is about. The recovery happened to be fast this time. Being fast recovery this time doesn't mean it will be so in the future. If that node had taken longer to come back, or the replacement had failed too, every span and log line in flight during that window would have been gone for good. With push, once the collector that received the data is gone, so is the data. There's no upstream system still holding a copy to resend, unlike pull, where the source itself retains its own state and a missed scrape just means scraping again next cycle. This wasn't really an availability incident. It only avoided being a data loss incident by luck. There was a PodDisruptionBudget sitting right there in the config, minAvailable: 1. It didn't help at all. Figuring out why is what turned a five minute non-incident into an actual redesign conversation. ## What the setup looked like Built on the upstream OpenTelemetry Collector chart, deployed as two tiers: ![Original two-tier collector architecture with a single gateway replica.](https://www.infraspec.dev/lovable-assets/blog/otel-scaling/architecture.png) - agent-collector runs one pod per node. It picks up OTLP push traffic from apps on that node and tails node level log files directly off disk, the approach this setup uses. That's the reason it has to be a DaemonSet in the first place, since with file-based tailing the logs are only visible locally on that node. - gateway-collector is where it gets interesting, and where the stakes flip. Every per-node agent forwards into it, so unlike the agent tier, this isn't one of several instances with a contained blast radius, it's the single point every trace, log line, and metric from the entire cluster converges through, all push traffic funnelled into one pipeline. Whatever happens here affects everything, not a fraction of it. On top of that, it also owns every pull based receiver: Kong, Puma, Redis, Postgres, the K8s API, GCP Monitoring. One process, one replica, doing two jobs that don't behave the same way under load, and carrying all of it at once. The same pattern is deployed across multiple environments, config layered as a base plus per-environment overrides. ## Why the PDB didn't catch anything Seeing a single-replica Deployment carrying this much weight, the first instinct is to check for a PodDisruptionBudget, and there was one: minAvailable: 1. It reads like a guarantee. It isn't. A PDB only constrains voluntary disruptions, the kind Kubernetes itself initiates and can therefore choose to delay: draining a node, a rolling update, a scale-down. On a Deployment with exactly one replica, minAvailable: 1 is close to a no-op, since evicting the only pod would violate the budget and gets blocked, but that's the only scenario it blocks. A node dying outright, hardware failure, an unresponsive kubelet, the instance getting terminated, is an external factor, something outside the Kubernetes control plane's own decision-making. A PDB doesn't act on external factors like this at all, it only governs disruptions the control plane itself chooses to make. The pod is gone either way. So the safety net everyone assumed was there was only ever covering the one failure mode that wasn't actually a threat. The thing that did happen, a node just disappearing, was never something a PDB could have stopped. ## Why "just add replicas" doesn't work The obvious next move is bumping replicas: 1 to something higher and spreading pods across nodes. It solves half the problem and creates a new one. For push, more replicas is genuinely good news. OTLP receivers don't care which replica handles which span (except if you are doing tail sampling), so any pod behind a load balancer works fine. That side is basically solved by scaling out. ![Push traffic balanced across three gateway collectors, with the tail-sampling exception.](https://www.infraspec.dev/lovable-assets/blog/otel-scaling/push-scaling.png) Without tail sampling, no coordination is needed between replicas, any one can handle any span. Pull doesn't behave the same way, and not even uniformly within itself, some of the pull receivers here would duplicate data under more replicas, others never needed more replicas to begin with. That distinction is worth its own section, below. ## How much traffic we're actually talking about A few numbers worth knowing before redesigning anything: push volume ran around 265 spans a second, about 23 million spans a day, plus roughly 11.5 million log records a day and around 60,000 metric data points a day from a handful of business metrics. Pull was smaller and uneven. Postgres alone accounted for 28,293 samples every 60 seconds, about 41 million a day, outpacing Kong (~525 samples across two pods every 15 seconds, about 6 million a day) and Puma (40 to 50 every 30 seconds, roughly 130,000 a day), against only 5 to 8 pull targets total. That asymmetry is why push was the bigger risk: if it's lost before export, there's nowhere else to get it from, while a missed pull scrape just means scraping again next cycle. Pull still turned out to be the harder engineering problem, not because of volume, but because of target ownership among multiple replicas of the same receiver. Both tiers ran a default in-memory sending queue: ``` exporters: otlp: sending_queue: queue_size: 1000 # in-memory by default retry_on_failure: max_elapsed_time: 300s ``` That's a quiet risk of its own, separate from replica count: anything queued when a pod gets killed, not gracefully stopped, killed, is gone regardless of how many replicas exist elsewhere. There's a second way to lose data here that has nothing to do with the pod dying at all: retry_on_failure.max_elapsed_time defaults to 300 seconds. If the backend is unreachable for longer than that, five minutes of retries, the collector gives up on that data and drops it, on purpose, even though the pod stayed healthy the whole time. ## The pull side isn't one problem, it's several It's tempting to treat "fix the pull side" as a single fix, and it isn't, because these receivers don't all behave the same way once you add replicas. ![Prometheus target allocation compared with single-endpoint polling.](https://www.infraspec.dev/lovable-assets/blog/otel-scaling/pull-receivers.png) Kong and Puma both expose metrics in Prometheus format, so assuming they're scraped through the standard prometheusreceiver , this is the case the OTel Operator's target allocator was built for, worth noting this means adopting the Operator's CRD-based deployment model, not just a config change: it shards a Prometheus-style scrape config across however many collector replicas you run, using consistent hashing so each target is owned by exactly one replica at a time, and reshuffles ownership if a replica disappears. This is genuinely a scaling mechanism, useful when there are enough targets that one collector can't handle the scrape and processing load alone. The honest reason to reach for the target allocator here isn't capacity, it's decoupling target ownership from the push tier's replica count. Redis, Postgres, the K8s API, and GCP Monitoring are a different shape of problem, assuming they're running through their usual native receivers (something like redisreceiver , postgresqlreceiver, k8sclusterreceiver ,and a GCP-specific equivalent). These work by polling a single fixed endpoint on an interval, whether that's Redis's INFO command, a Postgres connection for table and query stats, the K8s API for a cluster snapshot, or the GCP Monitoring API. There's no list of targets to split up, just one thing to ask, repeatedly, and one collector asking it isn't under any real load, even with Postgres being the single largest source of samples in the whole pipeline. Run this on multiple replicas anyway and each one independently polls the same endpoint on its own timer, there's no coordination, so you don't get more capacity or failover, you just get N full copies of the same data landing at the backend at slightly different times. That's not a harmless quirk, it directly inflates storage and ingestion volume for zero added value. Whether it's cleanly recoverable afterward depends on the backend: Cortex, for instance, can deduplicate HA-pair scrapes by label at ingest, electing one replica as leader and dropping samples from the others in real time, though that requires the HA tracker explicitly configured, not something you get by default. Insert-only, ClickHouse-backed stores don’t have that option, every scrape lands as a new row with no dedup on write, which is why the duplication is difficult to undo downstream for a setup like this. As far as I'm aware, receivers like this weren't built with running multiple concurrent instances in mind, since there's nothing for a second instance to usefully do. A target allocator doesn't help either, because there's no scrape config for it to shard against, just one receiver instance either polling or not. Kafka doesn't fit cleanly into either of these two buckets, which is worth flagging here even though it isn't part of this pipeline today. Kafka handles its own partitioning natively, so a kafkareceiver consuming from a topic scales more like the push side than like Redis or Postgres. It gets its own section further down, both because it deserves the fuller explanation and because, again, it isn't actually part of this setup yet. What these four (Redis, Postgres, K8s, GCP) actually need is availability, not scale: if the one pod handling Redis or Postgres polling dies, something else should pick it up quickly, not have multiple pods polling at once in the meantime. Two approaches apply here, static isolation and leader election: - Static isolation: Give each of these receivers its own small, dedicated single-replica deployment, isolated from both the push tier and each other. If one restarts, only that one source's data is briefly affected, nothing else. ![Separate singleton receiver deployments isolated from the push tier.](https://www.infraspec.dev/lovable-assets/blog/otel-scaling/static-isolation.png) No shared blast radius: a crash in one deployment never touches another source’s data, or the push tier at all. - Leader election: an extension or sidecar holds a lease, and if the active replica for a receiver goes down, a standby picks up scraping automatically, without both running at once, failover without duplication. For the K8s API source specifically, this is a real, documented option: the k8sleaderelector extension is wired into the receiver upstream, though it's still alpha stability, worth weighing against the added moving parts before relying on it in production. Redis and Postgres don't have this available today, their receivers have no equivalent support, so static isolation is what they run on regardless. Given how few targets are in this category, static isolation per source is probably the less complicated place to start, with leader election as something to reach for later if the number of singleton-style sources grows enough that manual isolation gets unmanageable. ## A separate case: Kafka Kafka doesn't fit cleanly into either of the two buckets above, so it gets its own treatment here rather than being forced into one. The reason it deserves its own section rather than a slot in the bucket above is that "the Kafka receiver" can mean two very different things depending on what it's pulling, and the two land in opposite categories: - Polling broker or topic level metrics on a schedule behaves exactly like Redis or Postgres above: one fixed thing to ask, no coordination between replicas, more replicas just means more duplicate copies. This would go in the same isolation-or-leader-election bucket as the rest of the polling receivers. - Consuming telemetry that's already been published onto a Kafka topic (traces, logs, or metrics pushed there upstream as a queue) is a genuinely different shape of problem, closer to push than pull. It rides on Kafka's own consumer group protocol, so multiple replicas sharing the same group ID automatically split the topic's partitions between them, and Kafka handles rebalancing on its own if a replica dies. No duplication, no manual sharding needed. The first question worth asking for any Kafka pull setup is which of these two cases actually applies, since that decides whether it needs the same isolation treatment as Redis and Postgres, or whether it scales cleanly on its own the way push does. ## The approach this points to Putting the pieces together, here's the direction that makes sense: - Back the sending queue with the file_storage extension, and set retry_on_failure.max_elapsed_time: 0 . Both are config changes, not architecture changes, and protect regardless of scale, worth doing first. - Split push and pull into actually separate tiers, so the push tier can scale freely without touching how scraping works. - Target allocator sharding for Kong and Puma. Static isolation for Redis, Postgres, K8s API, and GCP Monitoring, with leader election as an additional option for the K8s API source specifically, where it's documented and available today. - Revisit what protects the push tier from node failure: how many replicas actually tolerate one node going down, whether the queue needs to be persistent regardless of replica count, does the PDB config still matter once replicas > 1, and what data-loss window we're actually targeting. If you've solved this same push/pull scaling problem differently, we'd genuinely like to hear how. ## Takeaways A PodDisruptionBudget only protects against voluntary disruption. It says nothing about node failure, and minAvailable: N on an N replica Deployment barely does anything at all. Push and pull scale in opposite directions, and not all of "pull" is even a scaling question. Prometheus-shaped pull needs exclusive target ownership, which a target allocator solves as a genuine scaling mechanism. Single-endpoint polling receivers were never a capacity problem, they need availability, not more replicas. If you're designing this from scratch: decide up front whether push and pull belong in the same tier at all, and check which shape each of your pull sources actually is (Prometheus-style vs. single-endpoint) before assuming one fix covers all of them. --- # Taking Back Control: Observability as Reclaiming Agency By Nimisha G J · 2026-01-01 Canonical: https://www.infraspec.dev/blog/taking-back-control The story of every growing system is fundamentally a story about losing and regaining control. ## Act I: The Illusion of Control When the product is still in its inception and the team consists of a couple of engineers, If there is a CTO (at that point in the product’s journey) who is programming and contributing, to building systems. The team is in tight control of what is happening, The context is small enough that everyone knows every endpoint, every query and, integration that exists. Most likely, everything that is getting shipped and there is no environment segregation and code moves from the engineer’s development machine to production directly. If something breaks, engineers are aware where and what is breaking, and the team can reproduce them locally quickly and fix. Everyone knows what’s changed, who changed it and breaking production and quickly fixing it has become the way team works. This is what control is, and it’s natural because the system is still in the engineer’s cognitive capacity. This creates a dangerous illusion: you believe control comes from your knowledge of the code. But it doesn’t. Control is coming from the context being small and tight communications. ## Act II: The Gradual Loss Control doesn’t disappear suddenly. It erodes gradually, almost imperceptibly: ### Week 1 It’s a 2-person engineering team. You have to optimize some API response time, and as a default strategy for faster read operations teams add a caching layer. There is a new thing you have to worry about when the request is being served from cache and which one from the database. The team has to figure out what’s the right cache eviction strategy and when to update it. ### Month 2 The product is doing well, and there is good traction in the market and now your response time is critical for you. Immediately you figure out there is an operation happening in the customer facing flow which can be moved async, team jumped on this action and slashed your response time by 30 percent. Team is happy, and the engineering team is getting good recognition with so less turnaround time. It was a big win. But we can’t trace the end-to-end request easily but that concern is pushed for later. ### Month 4 The product team wants to take data based decisions and the roadmap is evolving towards experimentations, AB testing and more mature data-driven product decisions. For now engineering team adds a second database to unblock the analytics team and data is in two places and consistency is questionable, but this question goes under the carpet until it breaks ### Month 9 Your team has grown and the engineering team has around 20 people now.A single codebase is getting hard to manage, and as the codebase grows, architecture choices are becoming a bottleneck now. There are incidents every now and then but the product has good traction and customers really love it. This keeps fueling the team energy and everyone is very close to the customer and trying to solve for them. CTO takes a call of rearchitecting the systems while it is easy to change to enable the next phase of growth. Tech team decides to go towards the microservices route and identifies 5 services, 3 databases, and message queues with multiple deployment regions. ### Month 12 Team jumps in this, product development is halted because of this overhaul, and achieve this goal within 8 weeks as the team ends up copy pasting most of the things as timeline is tight. This goes to staging and is put under test. A lot of bugs and issues are reported but engineers figure it out and pushes the fix quickly by reading mostly logs on a single machine on staging. This goes to production but the reality is completely different from what the leadership has imagined. Uptime is a complex metric to come up with so many systems in place. It’s a distributed environment now. There are lot of issues coming up, while the team wants to maintain the delivery speed. No engineer has all the context which was normal 6 months back. Their deployment breaks, contract breaks often because the task which was simple sometime back now involves dependency of the context with other teams and availability. Incidents have become scarier, because you have grown on the business front and your customers expect more maturity from you. But every incident is like running in the dark as most of the time you are getting this information as an escalation from your operations or customers. Team is all reactive, running on manual checks of hitting production APIs to figure out whether the systems are working fine. More customers also means more escalations, your engineering bandwidth goes into fixing these issues most of the time. Engineers are pulling all-nighters and still things just looks out of control. ## Act III: The False Solutions Teams try different approaches to regain control: Let’s document everything : You write architecture diagrams, API specs, and deployment runbooks. They’re outdated within weeks. Documentation describes what the system should be, not what it is. Let’s hire tech operations : There will be a dedicated team who will keep an extra eye on your systems manually from cloud to customer tickets and report the issues back to the engineering team. This creates a false illusion that we’ll figure out the issue before our customer. Let’s be more careful : You add approval gates, slow down deployments, review every change, you’ve gained caution, not control. You’re still operating blind just more slowly. Let’s assign experts : You designate “the person who understands the auth service” and “the person who knows the database.” You’ve created knowledge silos. When they’re unavailable, you’re stuck. None of these are bad practices. But none of them restores your ability to understand what the system is actually doing right now. ## Act IV: Understanding Control Here’s the realization: you can’t control what you can’t see. Control isn’t about preventing all problems that’s impossible in complex systems. Control means: - Knowing what’s happening: When something goes wrong, you can see what actually failed, not a guess 1. Understanding why: You can trace cause and effect across the system 1. Predicting what’s next: You can see trends before they become crises - Acting with confidence: You can make changes knowing you’ll see their actual impact. - Reduced bus factor: You are not dependent on just a couple of engineers to really understand what’s going wrong. ## Act V: Observability as Agency Observability is about taking back control. But it’s not about returning to the simplicity you had, it’s about scaling your understanding to match your system’s complexity. ![Complexity vs Control](https://www.infraspec.dev/images/blog/taking-back-control/complexity-control-image.png) ### Scenario: Regaining Control of Deployment With observability: You deploy a change. You immediately see: - Request latency for the affected endpoints: no change - Error rates: flat at baseline - Database query times: unchanged - Resource utilization: normal - User-facing metrics: stable You know it’s working. You’re in control. ### Scenario: Regaining Control of Incidents User reports checkout is broken. You check the checkout service, It’s running. You check logs, no errors. You check the database, it’s up. You’re 20 minutes in and still don’t know what’s wrong. User is waiting. Pressure mounts. With observability: User reports checkout is broken. You pull up their trace. You see: - Checkout service called payment gateway - Payment gateway response time: 30 seconds (normally 200ms) - Gateway returned 503 - This started 15 minutes ago, affecting 12% of checkouts - Only affecting users in the EU region You understand the problem in 60 seconds. You’re in control of the investigation. ### Scenario: Regaining Control of Growth Without observability: Your system has been running fine for months. Suddenly, during a peak traffic event, everything falls apart. Database maxes out. Services crash. You spend hours firefighting. Post-mortem question: “How did we not see this coming?” With observability: You see database connection usage trending upward over 8 weeks: 40% → 55% → 70% → 85%. Traffic projections suggest you’ll hit 100% in two weeks during your product launch. You proactively optimize connection usage and plan for scaling. Launch goes smoothly. ## The Empowerment Here’s what makes this powerful: observability doesn’t just help you react, it changes what you can do. With proper observability, you can: Deploy with confidence : You’re not hoping changes work, you’re measuring their actual impact and can roll back immediately if needed. Debug efficiently : Investigation time drops from hours to minutes because you have the data to understand what happened. Optimize strategically : You’re not guessing which optimizations matter; You’re measuring actual bottlenecks and their impact. Scale proactively : You’re not reacting to outages; you’re seeing capacity limits before you hit them. Experiment safely : You can try new approaches and measure their real-world impact, not theoretical benefits. This is an agency. You’re not at the mercy of your system’s complexity. You’ve built the visibility to understand it, predict it, and shape it. Observability is the ability to maintain agency over increasingly complex systems. It’s how you ensure that growth doesn’t mean loss of understanding. It’s how you prove to yourself, your team, your users that you’re in control. --- # Pragmatism Over Perfection By Aleric Cusher · 2025-04-21 Canonical: https://www.infraspec.dev/blog/pragmatism-over-perfection We as Engineers often chase perfection. It fuels our curiosity, sharpens our skills, and makes us feel good about the things we build. But at the same time, it can be a double-edged sword, sometimes slowing us down or distracting us from what actually matters: delivering business value . That’s where pragmatism comes in. This is a story about that lesson being reinforced for me while working on a simple task: KYC Image Tagging. ## The Problem We had developed two models to classify KYC signature images as valid or invalid — one based on a CNN, the other on a Decision Tree. Once trained, I inferenced both the models on a dataset of around 1.2 lakh images , they disagreed on about 17% of them — and the only way to figure out which model was better was to manually tag those conflicting images. The ops team was ready to help. All we needed now was a simple interface for them to actually do the tagging. So I got to work exploring image tagging tools. ## Exploring the Right Tools for the Job We had a couple of requirements for this process: 1. Security and Access Control: The signature images were PII, so we needed secure login, proper access control, and audit logs. 1. Speed over Longevity: This was going to be mostly a one time activity, and there was some pressure to get this done as soon as possible. I quickly found a couple of open-source tagging tools available and started evaluating each one so that I could present viable options to the stakeholders. For each, I looked into pros, cons and how to get them up and running securely and so that only the Ops team could access them. However there were some constraints: 1. Missing Security Features: Most open-source tools lacked the security and access controls we needed, at least in their free versions. And buying licenses didn’t make sense for a one-off task, this meant that I would need to somehow implement security and access control. 1. Time pressure: The images were ready to be tagged. The stakeholders were waiting. And the Ops team was blocked on me to provide them with an interface. Setting up the infrastructure, securing it, and onboarding users would take time we did not have. These constraints made the “right” tools impractical for our needs. ## A Hack that Worked This is when the shift happened. I stepped back and looked at what we already had, and an idea struck. We were already using Databricks internally to ingest product data and run analytics and modeling jobs. What if it could be turned into a tagging tool? I pitched the idea to my manager. It was hacky, no doubt, but it was great. It ticked all our boxes: 1. Access control was sorted : Databricks had SSO and RBAC baked in. 1. Onboarding was simple : The process was documented and quick. 1. The KYC images were already available inside Databricks to people with the right access. 1. No new infrastructure was needed : We already had it running, hence saving time, setup overhead, and additional infrastructure costs. 1. Time to go live was minimal : I could get the Ops team started almost immediately, contributing to the time saved on the larger goal, model deployment. My manager signed off, and we presented the options to the stakeholders. They were happy that we could use an existing system to get the job done. So, we used Databricks as a tagging tool. It was in no way the “right” tool for the job, but it worked, and that made it the best one. And now it was time to implement this pragmatic solution. > What is Databricks? Databricks is an-all-in one platform for analysts, and engineers to manipulate, process and use data, read more [here](https://www.databricks.com/data-intelligence?scid=7018Y000001f8FIQAY&utm_medium=paid+search&utm_source=google&utm_campaign=20782149301&utm_adgroup=152953302702&utm_content=microsite&utm_offer=data-intelligence&utm_ad=724408738477&utm_term=what%20is%20databricks&gad_source=1&gclid=Cj0KCQjw2ZfABhDBARIsAHFTxGwAa41AMcCUzaTbsL60svmAaD4LReAsmqlwm_SMoJYbKgzcDWwEoGAaAi4wEALw_wcB) . ## Getting it up and Running I onboarded the Ops team onto Databricks and assigned them the right roles, which was quick and easy since I already had admin access. Then, I created a table containing the list of disagreed images along with some additional metadata. Finally, I created a simple notebook for them. Here is what the notebook did: 1. Fetched an image path at random from the table where the manual_tag field was Null . 1. Displayed the image to the user. 1. Asked the user for input. 1. Updated the manual_tag field in the table for the image, with the user input, tagging it valid or invalid. Here are some screenshots of the notebook, it contains some more information: ![Databricks Notebook Image 1](https://www.infraspec.dev/images/blog/pragmatism-over-perfection/Image_tagging_1.png) ![Databricks Notebook Image 2](https://www.infraspec.dev/images/blog/pragmatism-over-perfection/Image_tagging_2.png) ![Databricks Notebook Image 3](https://www.infraspec.dev/images/blog/pragmatism-over-perfection/Image_tagging_3.png) And after a short walkthrough, the Ops team was off tagging the images. ## The Outcome Using existing tools enabled us to get started quickly. It did introduce a few extra steps for the ops team, like running the notebook cells repeatedly, as compared to the right tools. However, the overhead was minimal, within acceptable limits, and the Ops team found the process simple. The tagging was completed within 3 weeks , which gave us the clarity we needed on the model performances. If I had used the “right” tools, the setup alone would have taken about a week. In the end, this approach saved us time, effort, complexity and additional costs while keeping the stakeholders happy. P.S. The CNN model won. ## The Takeaway The right tools for the job are great, and I now know which ones to use for tagging images, videos, audio, etc., and what their limitations are. This is valuable knowledge to have, for the future, when a similar problem statement comes along. But what matters more is driving business value . My solution was pragmatic, and it let us do exactly that, within the constraints we had. And that is the mindset we, as engineers, need to prioritize. This doesn’t mean we shouldn’t explore new or better tools; we absolutely should. But when solving a problem under real-world constraints, you have to ask: What kind of solution does this situation really need? More often than not, the best solution isn’t perfect — it’s pragmatic . --- # Apache Spark: Unleashing Big Data with RDDs, DataFrames and Beyond By Shivani Banke · 2024-11-24 Canonical: https://www.infraspec.dev/blog/apache-spark-unleashing-big-data-with-rdds-dataframes-and-beyond ## My Journey with Spark Before I knew Spark, I mostly used only Pandas and NumPy for data processing. They worked well for small datasets, and I never really had any issues—until I had to process a really large dataset—millions of rows. The processing slowed down, and eventually, I ran into an out of memory error. I tried splitting the data into chunks and tweaking my code, but nothing really worked well. On top of that, if my process failed due to a network issue, I had to start over. Running these jobs was expensive(long-running EC2 instances), and the time wasted on reruns was frustrating. That’s when I started looking for a better solution. That’s when I came across Apache Spark. It handles large datasets by distributing the work across multiple machines. When I ran my first Spark job, I was honestly amazed. It processed my data way faster than Pandas. The coolest part? The driver-executor model. The driver assigns tasks, and the executors do the heavy lifting. If something goes wrong, Spark retries only the failed tasks instead of starting over, offering fault tolerance, and efficient distribution. Plus, it works well with cluster managers like YARN and Kubernetes , making it easy to scale up. Now, let’s take a closer look at what Spark is and its key components. Apache Spark is a unified, multi-language (supports Python, Java, Scala, and R) computing engine for executing data engineering, data science, and machine learning on single-node machines or clusters and a set of libraries for parallel data processing. Let’s break down our description: Unified : It is designed to handle a wide range of data analytics tasks, from simple SQL queries to machine learning and streaming, all within a single engine using APIs. Computing Engine : It focuses on computation rather than storage, allowing it to work with various storage systems like Hadoop, Amazon S3, and Apache Cassandra. Libraries : Spark comes with built-in libraries for diverse use cases, including Spark SQL for database CRUD operations, Structured Streaming for real-time data processing in applications like fraud detection, MLlib for machine learning, and GraphX for graph analytics. It also supports third-party libraries from the open-source community. ## Spark Components ![Spark Components](https://www.infraspec.dev/images/blog/apache-spark-unleashing-big-data-with-rdds-dataframes-and-beyond/spark-components.png) ## High-Level Components (Spark Applications) At a high level, Spark provides several libraries that extend its functionality and are used in specialized data processing tasks. 1. Spark SQL : Spark SQL allows users to run SQL queries on large datasets using Spark’s distributed infrastructure. Whether interacting with structured or semi-structured data, SparkSQL makes querying data easy, using either SQL syntax or the DataFrame API (for now imagine dataframe is just a table of data, like what you see in Excel, more about dataframe is discussed [here](#dataframe) ). 1. MLlib : It provides distributed algorithms for a variety of machine learning tasks such as classification, regression, clustering, recommendation systems, etc. 1. GraphX : GraphX is Spark’s API for graph-based computations. Whether you’re working with social networks or recommendation systems, GraphX allows you to process and analyze graph data efficiently using distributed processing. 1. Spark Streaming : It enables the processing of live data streams from sources like Kafka, or TCP sockets, turning streaming data into real-time analytics. ## Spark Core At the heart of all these specialized libraries is Spark Core . Spark Core is responsible for basic functionalities like task scheduling, memory management, fault tolerance, and interactions with storage systems. ### RDDs RDDs (Resilient Distributed Datasets) are the fundamental building blocks of Spark Core. They represent an immutable, distributed collection of objects that can be processed in parallel across a cluster. More about RDDs is discussed [here](#rdd) . ### DAG Scheduler and Task Scheduler - DAG Scheduler : Spark breaks down complex workflows into smaller stages by creating a Directed Acyclic Graph (DAG). The DAG Scheduler optimizes this execution plan by determining which operations can be performed in parallel and orchestrating how the tasks should be executed. - Task Scheduler : After the DAG is scheduled, the Task Scheduler assigns tasks to worker nodes in the cluster. It interacts with the Cluster Manager to distribute tasks across the available resources. ### Cluster Managers and Storage Systems Apache Spark can run on multiple cluster managers like, Standalone which is Spark’s built-in resource manager for small to medium-sized clusters, Hadoop YARN (Yet another resource navigator), Apache Mesos, Kubernetes for orchestrating Spark workloads in containerized environments. For data storage, Spark integrates with a variety of systems like HDFS (Hadoop Distributed File System), Amazon S3, Cassandra, HBase, etc. Spark’s ability to interact with these diverse storage systems allows users to work with data wherever it resides. ## Spark’s Basic Architecture ![Spark Basic Architecture](https://www.infraspec.dev/images/blog/apache-spark-unleashing-big-data-with-rdds-dataframes-and-beyond/spark-architecture.png) ### 1. Spark Driver The Spark driver (process) is like the “brain” of your Spark application. It’s responsible for controlling everything. The driver makes decisions about what tasks to run, keeps track of the application’s progress, and talks to the cluster manager to get the computing power needed. Essentially, it manages the entire process and checks on the tasks being handled by worker nodes (executors). So basically it manages the lifecycle of the spark application. ### 2. Spark Executors Executors (process) are the “workers” that actually do the processing. They take instructions from the driver, execute the tasks, and send back the results. Every Spark application gets its own set of executors, which run on different machines. They are responsible for completing the tasks, saving data, reporting results, and re-running any tasks that fail. ### 3. Cluster Manager The cluster manager is like a “resource manager.” It manages the machines that make up your cluster and ensures that the Spark driver and executors have enough resources (like CPU and memory) to do their jobs. Spark can work with several types of cluster managers, such as YARN, Mesos, or Kubernetes, or it can use its built-in manager. ### 4. Execution Modes Spark can run in different ways, depending on how you want to set it up: - Cluster Mode : In this mode, both the driver and executors run on the cluster. This is the most common way to run Spark in production. - Client Mode : The driver runs on your local machine (the client) from where the spark application is submitted, but the executors run on the cluster. This is often used when you’re testing or developing. - Local Mode : Everything runs on a single machine. Spark uses multiple threads for parallel processing to simulate a cluster. This is useful for learning, testing, or development, but not for big production jobs. ## Spark’s Low-Level APIs ## RDDs (Resilient Distributed Datasets) They are the fundamental building block of Spark’s older API, introduced in the Spark 1.x series. While RDDs are still available in Spark 2.x and beyond, they are no longer the default API due to the introduction of higher-level abstractions like DataFrames and Datasets. However, every operation in Spark ultimately gets compiled down to RDDs, making it important to understand their basics. The Spark UI also displays job execution details in terms of RDDs, so having a working knowledge of them is essential for debugging and optimization. An RDD represents a distributed collection of immutable records that can be processed in parallel across a cluster. Unlike DataFrames (High-Level API), where records are structured and organized into rows with known schemas, RDDs are more flexible. They allow developers to store and manipulate data in any format—whether Java, Scala, or Python objects. This flexibility gives you a lot of control but requires more manual effort compared to using higher-level APIs like DataFrames. ### Key properties of RDDs - Fault Tolerance: RDDs maintain a lineage graph that tracks the transformations applied to the data. If a partition is lost due to a node failure, Spark can recompute that partition by reapplying the transformations from the original dataset. - In-Memory Computation: RDDs are designed for in-memory computation, which allows Spark to process data much faster than traditional disk-based systems. By keeping data in memory, Spark minimizes disk I/O and reduces latency. ### Creating RDDs Now that we discussed some key RDD properties, let’s begin applying them so that you can better understand how to use them. ``` from pyspark import SparkContext # Create a SparkContext sc = SparkContext("local", "RDD Example") # Create an RDD directly from a list numbers = [1, 2, 3, 4, 5] rdd = sc.parallelize(numbers) # Now we can perform operations on this RDD squared = rdd.map(lambda x: x * x) print(squared.collect()) # [1, 4, 9, 16, 25] ``` Here think of RDDs like taking a list of numbers and splitting it up so different computers can work on different parts at the same time. ## Spark’s Structured APIs ![Spark DataFrame](https://www.infraspec.dev/images/blog/apache-spark-unleashing-big-data-with-rdds-dataframes-and-beyond/spark-dataframe.png) DataFrame The Spark DataFrame is one of the most widely used APIs in Spark, offering a high-level abstraction for structured data processing. It is a powerful Structured API that represents data in a tabular format, similar to a spreadsheet, with named columns defined by a schema. Unlike a traditional spreadsheet, which exists on a single machine, a Spark DataFrame can be distributed across thousands of computers. This distribution is essential for handling large datasets that cannot fit on one machine or for speeding up computations. While the DataFrame concept is not unique to Spark; R and Python also include DataFrames—these are typically limited to a single machine’s resources. Fortunately, Spark’s language interfaces allow for easy conversion of Pandas DataFrames in Python and R DataFrames to Spark DataFrames, enabling users to leverage distributed computing for enhanced performance. Below is a comparison of distributed versus single-machine analysis. ### Creating a Dataframe ``` from pyspark.sql import SparkSession # Initialize Spark session spark = SparkSession.builder.appName("DF_from_List").getOrCreate() data = [1, 2, 3, 4, 5] # Convert list to DataFrame df = spark.createDataFrame([(x,) for x in data], ["Numbers"]) # Show DataFrame df.show() ``` When you have huge amounts of data, Spark splits it into smaller chunks (which we’ll learn about as “partitions”) so different computers can process different parts at the same time. ## Partitions Spark breaks up data into chunks called partitions, allowing executors (workers) to work in parallel. A partition is a collection of rows that reside on a single machine in the cluster. By default, partitions are sized at 128 MB, though this can be adjusted. The number of partitions affects parallelism—fewer partitions can limit performance, even with many executors, and vice versa. ## Transformations In Spark DataFrames, partitions are usually not managed directly. Instead, high-level transformations are defined, and Spark handles the execution details. Lower-level APIs like RDDs are available for more granular control. In Spark, the core data structures are immutable, meaning once they’re created, they cannot be changed. This may seem odd at first, but you modify a DataFrame by instructing Spark on how you want to transform it. These instructions are called transformations . For example, to filter out even numbers from a dataframe, you would use: ``` divBy2 = myRange.where("number % 2 = 0") # myRange is a dataframe ``` This code performs a transformation but produces no immediate output. That’s because they are lazy , meaning they do not execute immediately; instead, Spark builds a Directed Acyclic Graph (DAG) of transformations that will be executed only when an action is triggered. Transformations are the heart of Spark’s business logic and can be of two types: narrow and wide . ### Narrow Transformations In a narrow transformation , each partition of the parent RDD/DataFrame contributes to only one partition of the child RDD/DataFrame. Data does not move across partitions, so the operation is local to the same worker node. These are efficient because they avoid shuffling (data transfer between nodes). Examples: map , filter ![Spark Narrow Transformation](https://www.infraspec.dev/images/blog/apache-spark-unleashing-big-data-with-rdds-dataframes-and-beyond/narrow-transformation.png) ### Wide Transformations In a wide transformation , data from multiple parent RDD/DataFrame partitions must be shuffled (redistributed) to form new partitions. These operations involve network communication , making them more expensive. Examples: groupByKey , reduceByKey , join ![Spark Wide Transformation](https://www.infraspec.dev/images/blog/apache-spark-unleashing-big-data-with-rdds-dataframes-and-beyond/wide-transformation.png) In Spark, transformations are lazy, meaning they don’t execute immediately. Instead, they build a logical plan that outlines how data should be processed. However, to actually compute and retrieve results, we need actions. ## Actions They are operations that trigger the execution of transformations and return results to the driver program. Actions are the point where Spark evaluates the lazy transformations applied to an RDD, DataFrame, or Dataset. Examples: collect , count When an action is invoked, Spark builds a DAG (Directed Acyclic Graph) of all preceding transformations and executes the optimized plan. Key Differences Between Transformations and Actions | Transformations | Actions | | --- | --- | | Execution | Lazy (no immediate execution) | Eager (triggers computation) | | Output | New RDD/DataFrame | Result or persisted output | | Examples | map, filter, groupBy | collect, count, take | | Purpose | Defines the computation logic | Finalizes and executes the logic | Now that we’ve covered some key Spark concepts, Let’s explore the different ways to install and execute Spark. ### Run Spark Locally - Install Java (required as Spark is written in Scala and runs on the JVM) and Python (if using the Python API). - Visit [Spark's download page](http://spark.apache.org/downloads.html) , choose "Pre-built for Hadoop 2.7 and later," and download the TAR file. - Extract the TAR file and navigate to the directory. - Launch consoles in the preferred language: Python: ./bin/pyspark Scala: ./bin/spark-shell SQL: ./bin/spark-sql ### Run Spark in the Cloud - No installation required; provides a web-based interactive notebook environment. - Option : Use Databricks Community Edition [free] ### Building Spark from Source - Source : Download the source code from the [Apache Spark download page](http://spark.apache.org/downloads.html) . - Instructions : Follow the README file in the source package for building Spark. ## Conclusion Apache Spark has revolutionized the way we handle large-scale data processing, providing speed, fault tolerance, and scalability. From my initial struggles with Pandas and NumPy to embracing Spark’s powerful distributed computing capabilities, the journey has been eye-opening. Whether you’re dealing with batch processing, real-time streaming, or machine learning workloads, Spark offers the flexibility and efficiency required to tackle complex data challenges. Thanks for reading this blog! We’ve covered an overview of Spark’s components and architecture. In the next blog, we’ll explore its functionality in depth and understand how it handles large-scale data processing efficiently. Stay tuned! --- # Building Scalable Multi-Tenant Systems with AWS CDK By Mufaddal Shakir · 2024-11-22 Canonical: https://www.infraspec.dev/blog/multi-tenant-system-with-aws-cdk In this blog, I will be taking you on a journey of building the scalable and efficient IAC solution that we build for our multi-tenant system. Here we are not going to debate why we chose the CDK; that will be another discussion that can be highlighted in another blog. Instead, how we approached solving using AWS CDK is going to be discussed in this blog. Even if you are not very familiar with CDK, this blog can help to build a mental model of how we can think while writing the code for the infrastructure of such a complex system. ## What are Multi-tenant Systems? A multi-tenancy architecture uses a single instance of a software application to serve multiple customers. Each customer is referred to as a tenant. Tenants can customize certain aspects of the application, such as the color of the user interface or business rules, but they cannot change the application’s code. There are three main types of multi-tenant architecture. 1. One Application, One Database: All tenants share a single database. 1. One Application, Multiple Databases: Each tenant has its own database that shares the same application instance. 1. Multiple Applications and Databases: This is the most complex architecture, where multiple services and databases are deployed for each tenant. In this blog, we will focus on the third architecture, which provides greater flexibility and isolation. ## What is AWS CDK? The AWS Cloud Development Kit (CDK) is an open-source software development framework that allows us to define and provision cloud infrastructure resources with a variety of programming languages. AWS CDK, which is built on TypeScript, is tightly integrated with AWS CloudFormation, allowing it to leverage its strengths in infrastructure state management. In fact, CDK handles state management in the same way that CloudFormation does, making it easier to manage cloud resources. ## Understanding Our Requirements Our use case involves the linear growth of services alongside the exponential growth of tenants. A critical requirement is that each tenant must have database isolation to ensure robust tenant data integrity and confidentiality. This leads us to choose an architecture where services and databases for each tenant are deployed in isolation. Key requirements include: 1. Quick Tenant Onboarding: The onboarding process for new tenants should be streamlined. 1. Service Types: We will differentiate between internal platform services (used internally) and product services (used by end-users), ensuring that platform services can communicate with product services across all tenants. ## Architectural Overview ![multi-tenant-architecture](https://www.infraspec.dev/images/blog/multi-tenant-system-with-aws-cdk/multi-tenant-architecture.png) To visualize our architecture, consider the following components: 1. Platform Services: These are internal services that interact with product services across all tenants. For example, if SVC 1 is deployed for three tenants, User1, User2, and User3, platform services will connect with these isolated instances. 1. Product Services: These services address specific business needs and are deployed individually for each tenant, complete with their own databases. 1. Tenants: The end-users who utilize these services, ensuring they only access their own data due to database isolation. ## What do we know? Now let’s briefly see what all things we have in our bucket and what is expected from IAC. As we were using AWS as our cloud provider, we started looking into finalizing the architecture that we were going to use for our system. After all the R&D, we decided to go with the Multi-VPC architecture that is one of the recommendations from AWS, and yes, this was written in AWS CDK. And hence, taking recommendations from this CDK solution, we were able to achieve a single VPC for a single tenant, which then solved our complete isolation problem along with the platform VPC connectivity with the tenant VPCs. We will be looking at this in detail in this blog too. Considering we have what we wanted for our networking infrastructure, then for applications we are going to use Fargate ECS services, RDS for databases, SSM for application environment variables, Secret Manager for application secrets, and Route 53 for maintaining the DNS records. And for continuous integration and continuous deployment, we are going to use GitHub Actions. From all this decision, you might realize that we are avoiding anything self-hosted for now. Before we start looking into CDK code, let me tell you I will only be going through the configuration file with you, not the actual code, because CDK only differs from other IAC tools in that it is written in imperative form, which means we make the configuration file public-facing and the actual code an abstraction, which then helps each member of the org to just learn how to manipulate the configuration file and not the actual code, which helps the infrastructure manipulation be very easy, quick, and scalable. ## IAC of Networking Let’s first start looking into how we break down the [recommended](https://github.com/aws-samples/aws-vpc-builder-cdk/tree/main) networking architecture to fit our solution. We took the reference from this [config](https://github.com/aws-samples/aws-vpc-builder-cdk/blob/main/config/sample-firewall-blog.vpcBuilder.yaml) file. Let’s see how we can visualize this configuration file and how the actual output will look, which can be understood by the below diagram. ![multi-vpc](https://www.infraspec.dev/images/blog/multi-tenant-system-with-aws-cdk/multi-vpc.png) Let’s discuss in a bit what the components are. Although most of the components are self-explanatory, first start with Transit Gateway: I haven’t mentioned it in the diagram, but to communicate between VPCs, we used the central transit gateway and added the required routes to the dynamicRoutes and defaultRoutes ``` transitGateways: central: style: transitGateway tgwDescription: Central Transit Gateway dynamicRoutes: - vpcName: CentralIngress routesTo: PlatformVpc inspectedBy: inspectionVpc - vpcName: CentralIngress routesTo: TenantVpcA inspectedBy: inspectionVpc - vpcName: CentralIngress routesTo: TenantVpcB inspectedBy: inspectionVpc - vpcName: PlatformVpc routesTo: TenantVpcA inspectedBy: inspectionVpc - vpcName: PlatformVpc routesTo: TenantVpcB inspectedBy: inspectionVpc defaultRoutes: - vpcName: inspectionVpc routesTo: centralEgress - vpcName: PlatformVpc routesTo: centralEgress inspectedBy: inspectionVpc - vpcName: TenantVpcA routesTo: centralEgress inspectedBy: inspectionVpc - vpcName: TenantVpcB routesTo: centralEgress inspectedBy: inspectionVpc ``` Inspection VPC: This is our firewall VPC, which is going to be middleware between each communication between cross VPC. ``` providers: firewall: inspectionVpc: vpcCidr: 100.64.0.0/16 useTransit: central style: awsNetworkFirewall firewallDescription: For Inspection Vpc firewallName: InspectionEgress ``` For incoming traffic from the internet, Central ingress is considered the ingress VPC, and similarly, central egress is the VPC from where all traffic will go out to the internet. ``` providers: internet: centralEgress: vpcCidr: 10.10.0.0/16 useTransit: central style: natEgress vpcs: CentralIngress: style: workloadPublic vpcCidr: 10.1.0.0/19 subnets: loadBalancerSubnet: cidrMask: 22 PlatformVpc: style: workloadIsolated vpcCidr: 10.3.0.0/16 providerInternet: centralEgress subnets: workloadSubnet: cidrMask: 24 databaseSubnet: cidrMask: 24 loadBalancerSubnet: cidrMask: 24 ``` Platform VPC has connectivity with tenants VPCs, and tenants are not having cross-connectivity, as we can verify this with dynamicRoutes. This setup was the first milestone as a part of the infrastructure, as now to onboard any new tenants we just need to add a small block of code and the routes, like below. ``` vpcs: TenantVpcC: style: workloadIsolated vpcCidr: 10.9.0.0/16 providerInternet: centralEgress subnets: workloadSubnet: cidrMask: 24 databaseSubnet: cidrMask: 24 loadBalancerSubnet: cidrMask: 24 transitGateways: central: style: transitGateway tgwDescription: Central Transit Gateway dynamicRoutes: - vpcName: CentralIngress routesTo: TenantVpcC inspectedBy: inspectionVpc - vpcName: PlatformVpc routesTo: TenantVpcC inspectedBy: inspectionVpc defaultRoutes: - vpcName: TenantVpcC routesTo: centralEgress inspectedBy: inspectionVpc ``` Moving forward from networking to application was going to be a little tricky because, considering this networking setup using CDK, we have to be sure that we maintain the consistency across networking and application code for infrastructure. So we had two options: either edit the same code to add another support for the application or create a new CDK project that will only care about the application, considering the networking part is already set up. We chose to go with the second approach because 1. Changes in application-related configuration will be more aggressive than networking. 1. To make application configuration manipulated by developers, we have to keep the unusual data, according to developers, as little as possible in the same place. 1. Changes in networking configuration can impact the entire ecosystem, and hence maintenance of that should only come under specific teams like SRE/DevOps and should not be available to manipulate so easily by any member of the organization. 1. By keeping application IAC separate, it also helps in automating the CI/CD, which is also another topic we can discuss in a further blog. ## IAC of Application The basic idea of writing AWS CDK code is to bundle the unit of deployment into the same stack. CDK Stack represents a single CloudFormation stack, which is a collection of resources that are deployed together. So here, I have created the stack with a collection of resources that are going to be deployed together and are linked. This is the most important thing to identify upfront: how much power you want to give on manipulation from the configuration file, because if you try to write the CDK code very generically, then it will, at the end, be going to become like a CloudFormation template, and if you keep everything very coupled, then it will also be going to be a challenge if you want to decouple that. For example, here I created one type of service stack by identifying the business need: ecsWithAlbNlbEfs , in which the ECS service, along with the log group, ALB, EFS, and NLB, is also going to be deployed. ``` services: servicea: type: ecsWithAlbNlbEfs image: 123456789012.dkr.ecr.ap-south-1.amazonaws.com/servicea:v1.0.0 desiredCount: 2 memoryLimitMiB: 512 cpu: 1024 ephemeralStorageGiB: 10 ``` From the angle, if you see this, it will help you quickly deploy a similar kind of service, but what if service requirements come like it doesn’t want EFS or NLB? Then what? Either you will update that stack and make the creation of NLB and EFS dynamic, or you can create another stack. AWS CDK is imperative, and making it dynamic can break in the future if you want to update a single type of service, and the impact will be on all the services with entire tenants, so to avoid such an incident, I must suggest creating a different bundle of stack for different types of services use cases, and when a new type of service requirement comes, just create a new service stack instead of updating the existing one. ``` services: servicea: type: ecsWithAlbNlbEfs image: 123456789012.dkr.ecr.ap-south-1.amazonaws.com/servicea:v1.0.0 desiredCount: 2 memoryLimitMiB: 512 cpu: 1024 ephemeralStorageGiB: 10 serviceb: type: ecsWithAlbNlbWithoutEfs image: 123456789012.dkr.ecr.ap-south-1.amazonaws.com/serviceb:v1.0.0 desiredCount: 2 memoryLimitMiB: 512 cpu: 1024 ephemeralStorageGiB: 10 ``` So identifying the boundary of what to keep together and what to do differently with respect to the stack should be identified carefully; else there will be some efforts required to move resources from a stack to another. ![cdk-application-infra](https://www.infraspec.dev/images/blog/multi-tenant-system-with-aws-cdk/cdk-application-infra.png) This above is the architecture overview of application infrastructure written in AWS CDK. From configuration file to visualization, it will help us understand how to write the CDK stacks to make tenants and service onboarding easier. We created a bunch of stacks by identifying the problems. ### Common Infrastructure Stack This is the first stack that we have written to create common IAM roles that are going to be used globally, such as the ECS task execution role and the GitHub Actions role. ### ECS Service Stack (with EFS) The stack creates the ECS service for the tenant cluster by identifying via the configuration file alongside the ALB, NLB, EFS, and security groups. ### RDS Stack Keeping the stateful resources separate is one of the best practices that we followed, and hence the creation of the RDS stack is kept in a different stack along with the KMS key, security groups, and updating the secret manager with RDS credentials. ### Public ALB This is one of the common stacks we identified to create a public-facing application load balancer separately by following the practices of attaching ACM and proper security groups. ### Internal ALB CDK Stack that is used to create a separate internal ALB, such as in the platform VPC, to communicate with the tenants VPC services ## Conclusion In conclusion, building a scalable and efficient multi-tenant system on AWS requires careful planning and design. By using AWS CDK, we were able to define and provision our cloud infrastructure resources in a flexible and scalable way. Our approach to separating IAC code for networking and applications allowed us to maintain consistency and make changes more easily. We hope that this blog post has provided a useful example of how to use AWS CDK to build a multi-tenant system. We look forward to sharing more of our experiences in future blog posts, with follow-up questions like below. 1. How to automate CDK infrastructure provisioning with GitHub Actions? 1. When to choose CDK over Terraform? 1. What are the downsides of choosing a multi-VPC AWS architecture? 1. How do you design a scalable deployment pipeline for multiple services and tenants? 1. How do you plan for disaster recovery? 1. How to optimize multi-VPC architecture to reduce costs? --- # Efficient Data Migration: Hive Metastore to Unity Catalog By Arihant Hirawat · 2024-11-09 Canonical: https://www.infraspec.dev/blog/hive-to-unity-catalog-data-migration-databricks ![Hive Metastore to Unity Catalog Data Migration in Databricks](https://www.infraspec.dev/images/blog/hive-to-unity-catalog-data-migration-databricks/cover.png) ## TL;DR We had to migrate extensive data from Hive Metastore to Unity Catalog in a regulated large-scale enterprise environment. This task required precise planning, synchronization across teams, and expertise to ensure zero downtime and no data loss. By removing outdated jobs, cutting costs, and streamlining data workflows, we optimized the data infrastructure and achieved a robust governance framework. This migration gave us a deep understanding of complex data systems and the nuances of managing dependencies, aligning stakeholders, and ensuring regulatory compliance. ## Project Background: Migrating Enterprise-Scale Data We recently undertook the task to upgrade data management from Hive Metastore to Unity Catalog within Databricks. The Hive Metastore system posed challenges in data governance, access control, and lineage tracking. Unity Catalog, with its advanced security and governance features, was the natural choice to address these limitations and to meet our standards for compliance and operational efficiency. ## Initial Setup and Core Challenges ### Hive Metastore Constraints Existing reliance on Hive Metastore introduced numerous constraints: - Limited Security and Governance: Lack of native auditing, inadequate access controls, and missing lineage tracking created compliance challenges. - Environment Restrictions: Hive did not allow sharing schemas across separate environments, complicating the setup of development, staging, and production. Unity Catalog, by contrast, supports schema sharing across environments with detailed access controls, essential for regulated enterprises. ### Migration Requirements With around 87 schemas and 1,920-1,950 tables totaling ~22 TB to migrate, our objective was clear: migrate active data to Unity Catalog while maintaining zero downtime and safeguarding against data divergence. This meant not only handling the transfer but also ensuring no production jobs were disrupted. ## Strategy and Planning ### Assessing Existing Data and Stakeholder Engagement Our first steps included a thorough data assessment and stakeholder outreach. We leveraged the Databricks utility tools to catalog and assess tables within the Hive Metastore. This enabled us to filter out obsolete tables and prioritize essential data. We collaborated with multiple stakeholders, from schema owners to data engineers, for input on which tables were critical and required for daily operations. This information-gathering stage identified schemas for migration and non-essential ones for removal, enhancing the organization’s data efficiency. ## Execution Phase ### Detailed Migration Workflow ![Sample slack message requesting schema owners to update the hive schema details](https://www.infraspec.dev/images/blog/hive-to-unity-catalog-data-migration-databricks/sample_slack_message.png) - Schema and Table Identification: Using scripts, we generated a comprehensive list of schemas and tables, detailing table size, last update time, and owner feedback on necessity for migration. This streamlined our focus on only essential data, avoiding the migration of dead jobs and outdated test schemas. To gather this information efficiently, we reached out to schema owners for their inputs. Here’s an example of a Slack message we sent to one of the Hive schema owners requesting the necessary details for the migration: - Scheduling and Timing: Migrating tables with read-only operations was straightforward, as both Hive and Unity Catalog could be accessed simultaneously. However, tables with active write operations presented a challenge. If a job continued to write to Hive after migration, the data in Hive and Unity Catalog would diverge, potentially requiring a re-migration—a costly and complex task given the volume of tables. To avoid this, we scheduled migrations during job downtime to ensure data consistency. - Automation and Scalability: We automated and streamlined a significant part of the migration process by identifying ideal times when jobs were inactive and initiating migrations with minimal manual intervention. Our scripts were versatile, handling different scenarios based on table types and data sizes, ensuring efficient transfers. This automated approach allowed us to manage both large and small datasets with ease, scaling resources as needed to maintain optimal performance. Note: The jobs in this migration were primarily batch-oriented, which allowed us to perform migrations during scheduled downtimes without impacting production workloads. ### Data Consistency and Rollback Strategy To ensure data consistency and allow for a smooth rollback if needed, we followed these steps: - User Preparation: Before migration, we shared the new Unity Catalog table paths with users and asked them to prepare GitHub pull requests (PRs) for updating their jobs to refer to Unity Catalog. - Migration Process: Once the migration to Unity Catalog was successful, we merged the PRs, ensuring that jobs now referred to Unity Catalog tables. - Rollback Option: If the migration had failed, active jobs would have continued referring to the Hive tables, ensuring no disruption or data loss. ## Results and Key Improvements ### Enhanced Query Performance and Data Visibility Post-migration, we observed significant improvements in query performance due to more efficient data organization and optimized access controls within Unity Catalog. Additionally, the enhanced visibility provided by Unity Catalog’s lineage tracking allowed us to easily identify upstream and downstream tables, as well as access audit history. This improved visibility contributed to better management and faster troubleshooting of data workflows. ### Data and Cost Efficiency Gains #### Data Migration: Successfully transferred ~22 TB to Unity Catalog, with ~75 TB of deprecated data removed from Hive. #### Cost Savings: By removing 75 TB of deprecated data, we reduced both storage costs and data handling overheads. Here’s a rough breakdown of cost savings: | Cost Type | Details | Annual Cost | | --- | --- | --- | | EC2 Compute | 20 x i3.xlarge instances, 1 hour/day at $0.252/hour per instance | $1,840.56 | | Databricks Compute | 20 instances, 1 hour/day at $0.55/DBU/hour per instance | $4,015 | | Storage Cost | 75 TB of data stored on AWS S3 at $0.025/GB/month | $23,040 | | Total Annual Cost | Sum of all costs | $28,895.56 | Note: Additional costs are incurred for reading data from upstream sources like Redshift and writing to S3. These read/write operations are not included in the above cost breakdown but contribute to the overall data processing costs. ### Enhanced Governance and Operational Efficiency - Improved Data Governance: Unity Catalog introduced clear data lineage and granular access control, essential for maintaining regulatory compliance. Unity Catalog’s centralized governance model also provided the ability to enforce consistent access controls across environments, significantly improving both security and compliance management. - Operational Efficiency: Before the migration, engineers spent significant time maintaining outdated or unnecessary jobs. Considering ~10 unused jobs required about 1 hour per week to manage, removing those jobs saved approximately 10 hours of engineering effort each week. This freed up valuable time for engineers to focus on core operational tasks, accelerating product delivery and reducing maintenance overheads. ### Key Migration Metrics | Total Schemas | Tables Migrated | Data Migrated | Data Deleted | Job Optimizations | | --- | --- | --- | --- | --- | | 87 | 1,920-1,950 | ~22 TB | ~75 TB | Significant cost savings | ## Unseen Challenges: Key Insights We Gained During the Migration As with any large-scale project, there were a few unexpected challenges along the way. One critical lesson we learned was the importance of removing migrated tables from Hive immediately after the successful migration. Initially, we delayed this step, which led to users continuing to write to the old tables in Hive, causing data divergence. The takeaway? Don’t wait to delete migrated tables from Hive —doing so ensures data consistency and streamlines the transition to Unity Catalog. This small adjustment made a huge difference in the overall process. ## Conclusion: Strategic Impact and Future Roadmap This large-scale migration for a regulated enterprise required meticulous planning and execution to ensure zero downtime and maintain data integrity. Every piece of data and workload was critical to operations. Our top priority was safeguarding production workloads and preventing any data loss. This careful approach required significant effort, but it was crucial for ensuring operational continuity and preserving data accuracy. The migration optimized the governance model, reduced costs, and enhanced operational focus. Stay tuned for an upcoming series of blog posts where we’ll dive deep into the technical processes and scripts used, including enabling Unity Catalog for an existing production Databricks setup. 🚀 --- # ClickHouse Performance Benchmarking on ECS By Rohit Nagmoti · 2024-10-21 Canonical: https://www.infraspec.dev/blog/clickhouse-benchmarking Imagine being a Formula One driver, racing at breakneck speeds, but without any telemetry data to guide you. It’s a thrilling ride, but one wrong turn or an overheating engine could lead to disaster. Just like a pit crew relies on performance metrics to optimize the car’s speed and handling, we rely on observability in ClickHouse to monitor the health of our data systems for storing and querying logs. These metrics provide crucial insights, allowing us to identify bottlenecks, prevent outages, and fine-tune performance, ensuring our data engine runs as smoothly and efficiently as a championship-winning race car. In this blog, we’ll focus on performance benchmarking ClickHouse on AWS ECS in the context of log storage and querying, analyzing key system metrics like CPU usage, memory consumption, disk I/O, and row insertion rates across varying data ingestion volumes. For setting up the ClickHouse cluster, we followed the [ClickHouse replication architecture guide](https://clickhouse.com/docs/en/architecture/replication) and the [AWS CloudFormation ClickHouse cluster setup](https://aws-ia.github.io/cfn-ps-clickhouse-cluster/) . Using these resources, we replicated the setup on ECS, allowing us to run performance benchmarking tests on the environment. > For this benchmarking, we deployed ClickHouse version 24.3.12.75 for both clickhouse-server and clickhouse-keeper . Our ECS cluster configuration included a fault-tolerant setup with 1 shard and 2 replicas , composed of 2 ClickHouse server nodes and 3 ClickHouse Keeper nodes . Each node was provisioned on m5.xlarge instances, ensuring the necessary resources to handle our high-ingestion and query-intensive workloads. By examining performance metrics during the ingestion of 1 million, 5 million, 10 million, and 66 million logs, we aim to provide a quantitative analysis of how system behavior changes as the load increases. ![clickhouse-cluster-ingestion](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/clickhouse-cluster-ingestion.png) For more details on the schema and test queries used, you can [download the SQL file here](/images/blog/clickhouse-benchmarking/clickhouse_benchmark_queries.sql) . ## Performance Comparison of Key Metrics Across Ingestion Volumes | Logs Ingested | CPU Usage (Cores) | Selected Bytes per Second (MB/s) | IO Wait (s) | CPU Wait (s) | Read from Disk (MB) | Read from Filesystem (MB) | Memory Tracked (MB) | Selected Rows per Second | Inserted Rows per Second | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 1 Million (10 Lakh) | 0.103 | 0.026 | 0.000 | 0.0217 | 0.000 | 0.42 | 714 | 256.88 | 238,666.67 | | 5 Million (50 Lakh) | 0.111 | 0.036 | 0.000 | 0.0058 | 0.000 | 0.51 | 738 | 256.88 | 238,666.67 | | 10 Million (1 Crore) | 0.433 | 36.26 | 0.000 | 0.3297 | 1.84 | 3.17 | 983 | 146,848.98 | 140,193.58 | | 66 Million (6.6 Crore) | 1.179 | 122 | 0.750 | 4.4276 | 17.33 | 13.63 | 1,971 | 365,589.00 | 365,589.00 | ### Key Insights from the Data #### 1. CPU Usage (avg_cpu_usage_cores) ![clickhouse-cluster-ingestion](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/write-op-cpu-usage.png) - At 1 million logs , CPU usage was low, increasing slightly with 5 million logs , reflecting an 8% rise. - At 10 million logs , CPU usage jumped by 290% , showing significant processing demand. - At 66 million logs , CPU surged by 173% over the previous level, indicating much higher CPU load as ingestion scaled. #### 2. Selected Bytes per Second (avg_selected_bytes_per_second) ![clickhouse-cluster-ingestion](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/write-op-selected-bytes.png) - For 1 million logs , throughput was 0.026 MB/sec , increasing to 0.036 MB/sec for 5 million logs , a 38% increase. - At 10 million logs , throughput reached 36.26 MB/sec , up 1000% from 5 million logs . - At 66 million logs , throughput hit 122 MB/sec , a 3.4x increase, demonstrating strong scalability. #### 3. I/O Wait (avg_io_wait) ![clickhouse-cluster-ingestion](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/write-op-io-wait.png) - I/O wait was negligible at 1 and 5 million logs with 0 seconds . - For 66 million logs , I/O wait spiked to 0.75 seconds , a notable bottleneck as ingestion volume increased. #### 4. CPU Wait (avg_cpu_wait) ![clickhouse-cluster-ingestion](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/write-op-cpu-wait.png) - CPU wait time was 0.0217 seconds for 1 million logs , decreasing to 0.0058 seconds for 5 million logs , a 73% improvement. - At 10 million logs , it rose to 0.3297 seconds , a 56x increase. - At 66 million logs , CPU wait reached 4.4276 seconds , reflecting high contention for CPU. #### 5. Disk Reads (avg_read_from_disk) ![clickhouse-cluster-ingestion](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/write-op-disk-reads.png) - Disk reads were 0 bytes at 1 and 5 million logs . - At 10 million logs , disk reads spiked to 1.843 MB , and at 66 million logs , they rose to 17.33 MB , showing a 10x increase. #### 6. Filesystem Reads (avg_read_from_filesystem) ![clickhouse-cluster-ingestion](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/write-op-filesystem-reads.png) - Filesystem reads began at 0.42 MB for 1 million logs , rising to 0.51 MB for 5 million logs , a 21% increase. - At 10 million logs , it jumped to 3.17 MB , a 5x increase. - At 66 million logs , filesystem reads reached 13.63 MB , a 4.3x increase from the previous level. #### 7. Memory Usage (avg_memory_tracked) ![clickhouse-cluster-ingestion](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/write-op-memory-tracked.png) - Memory usage was 714 MB for 1 million logs , increasing to 738 MB for 5 million logs , a 3% rise. - At 10 million logs , memory usage reached 983 MB , a 36% increase. - At 66 million logs , it peaked at 1.9 GB , a doubling from 10 million logs . #### 8. Selected Rows per Second (avg_selected_rows_per_second) ![clickhouse-cluster-ingestion](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/write-op-selected-rows.png) - At 1 and 5 million logs , 256 rows/sec were selected. - At 10 million logs , selected rows per second rose to 146,849 rows/sec , a 570x increase. - At 66 million logs , selected rows reached 365,589 rows/sec , a 2.5x rise over 10 million logs . #### 9. Inserted Rows per Second (avg_inserted_rows_per_second) ![clickhouse-cluster-ingestion](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/write-op-inserted-rows.png) - Inserted rows per second were consistent at 238,666 rows/sec for 1 and 5 million logs . - At 10 million logs , the insertion rate was 140,193 rows/sec , a 41% increase. - At 66 million logs , it rose to 365,589 rows/sec , reflecting efficient scaling for high ingestion volumes. ## Performance in Read-Heavy Operations ClickHouse’s performance during read-heavy operations, including SELECT , aggregate, and JOIN queries, is critical for applications relying on fast data retrieval. Here, we analyze key system metrics across different configurations: two-node replicas under load balancing and a single-node configuration due to failover. ![clickhouse-cluster-ingestion](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/clickhouse-cluster-read.png) ### Performance Comparison of Key Metrics Across Configurations | Configuration | CPU Usage (milli-cores) | Selected Bytes per Second (MB/s) | IO Wait (milli-seconds) | CPU Wait (s) | Read from Disk (MB) | Read from Filesystem (MB) | Memory Tracked (MB) | Selected Rows per Second | Inserted Rows per Second | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | Two Nodes (Node-1) | 574 – 875 | 143 – 224 | 0.2 – 7.7 | 1.045 – 1.9356 | 13 – 21 | 14 – 22 | 694 – 912 | 412,713.28 – 648,431.85 | 246.08 – 2,006 | | Two Nodes (Node-2) | 122 – 493 | 0.022 - 80 | 4.7 | 1.0964 – 0.0039 | 0 – 7 | 1 - 8 | 781 – 692 | 232,168.82 – 238.1 | 253.93 – 238.1 | | Single Node (Node-2 Down) | 529 – 883 | 158 – 283 | 0.2 | 1.8338 – 9.1992 | 3 – 11 | 30 – 32 | 837 – 861 | 458,760 – 9,742,907.23 | 214.92 – 222.00 | ### Key Performance Insights from System Metrics #### 1. CPU Usage (avg_cpu_usage_cores) ![clickhouse-benchmarking](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/read-op-cpu-usage.png) - Two-Node Setup : Node-1 utilized between 574 to 875 milli-cores during query processing, handling most of the workload. Node-2 had lower CPU usage, ranging from 122 to 493 milli-cores , indicating that load distribution wasn’t entirely balanced across nodes. - Single-Node Setup : CPU usage ranged from 529 to 883 milli-cores as it handled all queries independently, highlighting increased CPU demands without load balancing. #### 2. Selected Bytes per Second (avg_selected_bytes_per_second) ![clickhouse-benchmarking](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/read-op-selected-bytes.png) - Two-Node Setup : Node-1 processed data at speeds between 143 MB/s to 224 MB/s , while Node-2 managed much lower speeds, ranging from 22 KB/s to 80 MB/s , showing an uneven data split. - Single-Node Setup : Data selection rates reached 158 MB/s to 283 MB/s , indicating strong throughput even with just one node handling queries. #### 3. I/O Wait (avg_io_wait) ![clickhouse-benchmarking](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/read-op-io-wait.png) - Two-Node Setup : I/O wait times were minimal, with Node-1 recording only 0.2 to 7.7 milliseconds , and Node-2’s wait times was 4.7 milliseconds . - Single-Node Setup : Maintained efficient I/O performance, with an I/O wait of 0.2 milliseconds , even under higher loads. #### 4. CPU Wait (avg_cpu_wait) ![clickhouse-benchmarking](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/read-op-cpu-wait.png) - Two-Node Setup : Node-1’s CPU wait time was low, peaking at 1.94 seconds during complex queries. - Single-Node Setup : CPU wait times were significantly higher, ranging from 1.8 to 9.2 seconds , showing CPU contention under a high query load when only one node was active. #### 5. Disk Reads (avg_read_from_disk) ![clickhouse-benchmarking](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/read-op-disk-reads.png) - Two-Node Setup : Disk reads on Node-1 ranged between 13 MB and 21 MB , while Node-2 saw reduced reads (0 to 7 MB). - Single-Node Setup : Disk reads increased to 3 MB to 11 MB , reflecting the added reliance on disk I/O without load balancing. #### 6. Filesystem Reads (avg_read_from_filesystem) ![clickhouse-benchmarking](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/read-op-filesystem-reads.png) - Two-Node Setup : Node-1 had filesystem reads ranging from 14 MB to 22 MB . - Single-Node Setup : Reads increased to 30 MB to 32 MB , illustrating higher filesystem demand with all queries processed on one node. #### 7. Memory Usage (avg_memory_tracked) ![clickhouse-benchmarking](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/read-op-memory-tracked.png) - Two-Node Setup : Node-1’s memory usage ranged from 694 MB – 912 MB . - Single-Node Setup : Memory usage rose slightly to 831 MB to 861 MB , reflecting the additional memory load for standalone query handling. #### 8. Selected Rows per Second (avg_selected_rows_per_second) ![clickhouse-benchmarking](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/read-op-selected-rows.png) - Two-Node Setup : Node-1 retrieved data at 412,000 to 648,000 rows per second , while Node-2 retrieved 232,000 to 238,000 rows per second . - Single-Node Setup : Retrieval rate spiked to 9.7 million rows per second , demonstrating the node’s capacity to handle increased retrieval demands on its own. #### 9. Inserted Rows per Second (avg_inserted_rows_per_second) ![clickhouse-benchmarking](https://www.infraspec.dev/images/blog/clickhouse-benchmarking/read-op-inserted-rows.png) - Two-Node Setup : Node-1 showed stable insertion rates at 246 to 2,006 rows per second , while Node-2 remained consistent at 254 to 238 rows per second . - Single-Node Setup : Insertion rates remained consistent at 215 to 222 rows per second , suggesting that query load minimally affected insertion performance when only one node was handling the workload. ### Conclusion This benchmarking study highlights ClickHouse’s ability to handle both high-ingestion and read-intensive workloads on ECS. For ingestion, ClickHouse efficiently managed small data loads, but higher volumes (10M and 66M logs) led to significant increases in CPU, memory, and I/O wait, indicating the need for resource scaling. For read operations, a two-node setup provided balanced CPU and I/O distribution, while a single-node setup led to increased CPU wait and resource contention under full query load. To optimize performance, monitoring key metrics like CPU usage , I/O wait , and memory is essential, and leveraging multi-node configurations can help maintain efficient performance under heavy workloads. --- # Cache Strategies By Sanjay Singh · 2024-09-25 Canonical: https://www.infraspec.dev/blog/cache-strategies ## What is Caching? Caching is a technique that enhances application performance by temporarily storing frequently accessed data in high-speed data storage hardware like RAM. This temporary storage is called a Cache. Instead of repeatedly retrieving data from the original/primary Data source, the application can quickly access it from the Cache. This reduces response time and improves the overall throughput of the application. ## Why do we need Caching? There are various benefits of Caching the frequently accessed data at different layers in caching: - Reduced Latency: It helps reduce the latency by storing the frequently accessed data in high-speed data storage hardware making the data retrieval faster. - Reduced Load on Backend Systems: It helps reduce the backend system load by serving the frequently accessed data from the Cache. - Cost Efficiency: It reduces the no. of requests made to the original/primary data source or some external services hence lowering the operating cost. - Better User Experience: It reduces the application’s load time, makes it user-friendly, and increases engagement. - Improved Scalability: As it reduces the response time of the request, the caching allows the application to handle more requests simultaneously, improving the overall throughput of the system(read-throughput). ## Various Layers of Caching Caching can be applied at various levels of an application stack, each serving a specific purpose and enhancing the performance in its way. Understanding these various types of cache and their use cases is essential to design an efficient system. CDN(Content Delivery Network) Cache: A CDN cache is used to store copies of static assets (e.g., images, videos, CSS, JavaScript files) closer to the end users across geographically distributed servers. The goal is to reduce latency and reduce traffic from the origin server by serving cached content directly from the nearest CDN server. Imagine a car factory where all cars are produced. If you have to buy directly from the factory, you need to travel far, which takes time and effort. If everyone does this, the factory gets crowded, slowing things down. Now, instead of going to the factory, local showrooms are set up nearby with popular car models ready to go. This saves time for customers and reduces the load on the factory, as fewer people need to go there directly. Similarly, a CDN brings content closer to users, improving speed and reducing strain on the origin server. Applications with high volumes of static content or media use CDN caching to reduce response time and improve performance for delivering static assets globally. Examples include streaming services, news platforms, and shopping applications. ![CDN Cache](https://www.infraspec.dev/images/blog/cache-strategies/cdn-cache.png) Browser or Client Side Cache: The browser or client cache involves storing frequently accessed resources, such as images, scripts, or API responses, locally on the user’s device. This helps avoid repeated network requests for the same resources, improving page load times. By setting expiration times for cached items, developers can control how long the data remains valid, ensuring that users receive fresh content while minimizing redundant requests. As a result, pages load faster for users, and server load is reduced. ![Client Side Cache](https://www.infraspec.dev/images/blog/cache-strategies/browser-cache.png) Database Cache(Query Cache): Database caching involves storing frequently queried data to reduce the load on the database and speed up query execution. The cache can be managed by the database management system (DBMS), exist within the application, or function as a standalone layer. When a query is executed, the DBMS checks the cache first; if the results are found, they are returned without querying the database. This approach is especially beneficial for high-traffic applications, as it leads to faster query results and improved overall performance. Examples include e-commerce platforms and social media sites, with solutions like MySQL Query Cache or ORM tools like Hibernate for Java that support caching. Application/Server Side Cache: In application-side (server-side) caching, data is cached directly by the server or application layer, either in memory or using external caching systems like Redis or Memcached. This strategy enhances performance by quickly serving frequently accessed data. It is particularly beneficial for backend systems or microservices that often fetch the same data, such as API responses or user profiles. The result is faster access to commonly used data, reduced external API or database calls, and improved application responsiveness. This makes it one of the most commonly used caching layers. ![Server Side Cache](https://www.infraspec.dev/images/blog/cache-strategies/server-cache.png) Distributed Cache: A distributed cache works across multiple nodes or servers, making it accessible to different parts of the system in a scalable and fault-tolerant way. It’s often used in large applications to ensure high availability and consistent data. Common tools for distributed caching include Redis and Apache Ignite. This approach is useful for microservices architectures, cloud-based applications, and systems that need to share data across instances. The main benefits are scalability, fault tolerance, and having a single source of truth for cached data. ![Distributed Cache](https://www.infraspec.dev/images/blog/cache-strategies/distributed-cache.png) ## Cache Strategies(Server Side Caching) Cache-Aside: In this strategy, the application code is responsible for managing the Cache. It handles when to read from the cache or fetch data from the underlying data source. The sequence of actions followed in the Cache-Aside strategy is as follows: - Check cache for data(Cache-Hit): When a request is made, the application first queries the data in the Cache. If the requested data is found(Cache-Hit), it is directly returned. - Fetch from Data Source(Cache-Miss): If the data is not found in the Cache(Cache-Miss), the application retrieves the required data from the underlying data source(e.g., Database or API). - Update Cache with Fresh Data: After fetching the data from the primary data source, the application updates the cache with fresh data for future requests. - Return the data to the client/caller: Finally, the application returns the data to the client/caller, whether from the cache or after being fetched from the data source. ![Cache Aside Cache Strategy](https://www.infraspec.dev/images/blog/cache-strategies/cache-aside.png) Read Through: In this strategy, the responsibility for managing the cache lies with the cache layer rather than the application code. The application layer calls the cache layer to request data, and the cache layer handles whether to read from the cache or fetch data from the underlying data source. The sequence of actions followed in the Read-Through strategy is as follows: - Check cache for Data (Cache-Hit): When a request is made, the cache layer first checks for the requested data in the cache. If the data is found (Cache Hit), it is directly returned from the cache. - Fetch from Data Source (Cache-Miss): If the data is not found in the cache (Cache Miss), the cache layer automatically fetches the data from the underlying data source (e.g., a database or API). - Update Cache with Fresh Data: Once the data is retrieved from the primary data source, the cache layer updates the cache with the fresh data for future requests. - Return the Data to the Client/Caller: Finally, the data is returned to the client/caller, whether it was retrieved from the cache or fetched from the data source. ![Read Through Cache Strategy](https://www.infraspec.dev/images/blog/cache-strategies/read-through.png) Write Around: In this strategy, the application code is responsible for managing the Cache. When data is written or updated, it is directly sent to the primary data source, and the corresponding cache entry is cleared if present. - On the next read request, the process follows the same as the Cache-Aside strategy. The sequence of actions followed in the Write Around strategy is as follows: - Write/Update to Data Source and Clear Cache: When new data is written or existing data is updated, the application stores it in the primary data source and clears the relevant cache entry, if present. - Check Cache for Data (Cache-Hit on Read): When a read request is made, the application first checks the cache. If the data is available (Cache-Hit), it is returned immediately. - Fetch from Data Source (Cache-Miss on Read): If the requested data is not found in the cache (Cache-Miss), the application retrieves it from the underlying data source (e.g., database, API). - Update Cache with Fresh Data: After fetching the data, the application updates the cache for quicker future access. - Return the Data to the Client/Caller: The fetched data, whether from the cache or the primary data source, is returned to the client/caller. ![Write Around Cache Strategy](https://www.infraspec.dev/images/blog/cache-strategies/write-around.png) Write Through: In this strategy, the cache layer manages the data in the cache and the underlying data source. When data is written or updated, the cache layer ensures the changes are synchronized in both locations. The sequence of actions followed in the Write-Through strategy is as follows: - Write/Update to Cache: When new data is written or existing data is updated, the application layer calls the cache layer, which first writes or updates the data in the cache. - Synchronously Write/Update to Data Source: After updating the cache, the cache layer immediately writes or updates the data in the underlying data source (e.g., a database or API) in a synchronous manner to ensure consistency between the cache and the data source. ![Write Through Cache Strategy](https://www.infraspec.dev/images/blog/cache-strategies/write-through.png) Write Behind: In this strategy, the cache layer manages data updates asynchronously. When data is written or updated, the application layer calls the cache layer, which immediately updates the cache while delaying the write to the primary data source. The data is then written to the underlying data source after a specified interval, with the cache maintaining a buffer of changes until the update occurs. The sequence of actions followed in the Write-Behind strategy is as follows: - Write/Update to Cache: When new data is written or existing data is updated, the application layer calls the cache layer, which immediately updates the data in the cache. - Buffer Data in Cache: The cache layer maintains a buffer of the updated data in the cache, temporarily holding the changes before committing them to the primary data source. - Asynchronously Write/Update to Data Source: After a specified interval, the cache layer writes or updates the buffered data in the primary data source (e.g., a database or API), ensuring eventual consistency between the cache and the data source. ![Write Behind Cache Strategy](https://www.infraspec.dev/images/blog/cache-strategies/write-behind.png) ## Conclusion In this article, we discussed what is caching, why we need caching, different levels of caching, and various caching strategies that we use for server-side caching. Finally, I would say where to cache the data and what strategy to use for caching entirely depends on the application’s requirements. That was all for this article. I hope you found it useful! ## References [Oracle Documentation](https://docs.oracle.com/cd/E16459_01/coh.350/e14510/readthrough.htm) [Other Resource](https://www.alachisoft.com/resources/articles/readthru-writethru-writebehind.html) --- # Managing Environments with Terragrunt By Nimisha G J · 2024-09-10 Canonical: https://www.infraspec.dev/blog/terragrunt-envs-management Managing multiple environments was a never-ending headache for me. Like many others in the DevOps world, I was responsible for deploying applications across various environments—production, staging, and development. Each of these environments required the same infrastructure, but I found myself writing the same Terraform code over and over again in different folders. The repetition felt inefficient, and the potential for human error only grew with each tweak I had to make for a specific environment. ## The Repetition Trap At first, my solution was simple: copy-paste. I created three separate folders: one for production, one for staging, and one for development. Each folder contained the same Terraform files with minor tweaks, such as different variables or configurations for each environment. It worked, but I soon found myself dealing with the chaos of managing three sets of nearly identical infrastructure code. Let’s say I needed to update a configuration for my database service. This meant opening each folder, making the same change in three different places, and running Terraform multiple times for each environment. It was a tedious and error-prone process, and as my infrastructure grew, so did the complexity. I knew there had to be a better way. > My Initial Setup was like this ``` . ├── production │   ├── app.tf │   ├── database.tf │   └── redis.tf ├── qa │   ├── app.tf │   ├── database.tf │   └── redis.tf └── staging ├── app.tf ├── database.tf └── redis.tf ``` The Terraform files contain identical resources across different environments, with the only variation being the values assigned to the variables. That is lot of repeated code. ## The Terragrunt Revelation That’s when I discovered Terragrunt. Terragrunt is a thin wrapper for Terraform that provides extra tools for keeping your Terraform code DRY (Don’t Repeat Yourself). It allows you to manage multiple Terraform modules in a single repository and reuse code across different environments. Terragrunt’s ability to manage remote state, generate configurations, and apply configurations across multiple environments made it the perfect solution for my environment management woes. How we reduce the repeated code using Terragrunt: First step was to make a module of the resources with all the changeable variables exposed, Next was to use them in each environment. > The new folder structure using Terragrunt ``` . ├── terragrunt.hcl ├── production │   ├── app │   │ └── terragrunt.hcl │   ├── database │   │ └── terragrunt.hcl │   └── redis │   └── terragrunt.hcl ├── staging │   ├── app │   │ └── terragrunt.hcl │   ├── database │   │ └── terragrunt.hcl │   └── redis │   └── terragrunt.hcl └── qa    ├── app    │ └── terragrunt.hcl    ├── database    │ └── terragrunt.hcl    └── redis    └── terragrunt.hcl ``` In the terragrunt.hcl file, we define the module to use and the variables to pass to the module. ``` # terragrunt.hcl terraform { source = "gittfr:///exampleorg/app/aws?version=5.8.1" } inputs = { app_name = "my-app" environment = "production" } ``` Similarly, in the other terragrunt files, we define the module to use and the variables to pass to the module. And now for the storing the state file we can use the remote state file. ``` # terragrunt.hcl generate "backend" { path = "backend.tf" if_exists = "overwrite_terragrunt" contents = < This would look like this ``` include "root" { path = find_in_parent_folders() } ``` Here the find_in_parent_folders returns the absolute path to the first terragrunt.hcl file it finds in the parent folders above the current terragrunt.hcl file. and the include block tells terragrunt to include all the cofigurations from the file with the path returned by the find_in_parent_folders function. ## The Terragrunt Workflow Here is a high-level overview of the terragrunt workflow: > We run the command terragrunt run-all plan in the root directory. Output ``` 22:03:23.710 INFO The stack at . will be processed in the following order for command plan: Group 1 - Module . - Module ./production/app - Module ./production/database - Module ./production/redis - Module ./qa/app - Module ./qa/database - Module ./qa/redis - Module ./staging/app - Module ./staging/database - Module ./staging/redis ``` This will run the terragrunt plan in each sub directory it finds, Then it reads the terragrunt.hcl file in the current directory and does the following: 1. Terragrunt reads the terraform block and downloads the specified Terraform module 1. Terragrunt reads the inputs block and passes the variables to the Terraform module 1. Terragrunt reads the generate block and creates the backend.tf file 1. Terragrunt runs Terraform with the specified configurations 1. Terragrunt stores the Terraform state in the remote state file 1. Terragrunt returns the output of the Terraform run This workflow allows me to manage multiple environments with ease. I am able to make changes to my infrastructure code in one place and then apply those changes across all environments with just one command. Terragrunt’s capability to keep my Terraform code DRY has saved me time and effort, eliminating the need to manage multiple sets of nearly identical infrastructure code. ## How Terragrunt worked for me 1. Centralized Modules : I now have a shared repository of modules that are environment-agnostic. The modules are reusable and cover things like VPCs, ECS clusters, RDS instances, and IAM roles. I no longer need to maintain three different sets of Terraform code. 1. Per-Environment Configurations : For each environment, I have a terragrunt.hcl file that passes environment-specific configurations like the number of instances or database types. These configurations override default values in the shared modules, ensuring that each environment gets what it needs without redundant code. 1. Automated Initialization : Running Terraform in multiple environments is now a breeze. Terragrunt automatically handles running terraform init, terraform plan, and terraform apply for each environment. No more manually navigating into each folder and executing commands multiple times. Terragrunt takes care of initializing each environment’s backend configuration (e.g., for state storage in S3 and locking with DynamoDB). 1. Dependency Management : Another Terragrunt superpower is managing dependencies between infrastructure components. For example, my ECS service depends on the VPC and subnets being provisioned first. Terragrunt’s dependencies block ensures that I deploy resources in the correct order, so my ECS service doesn’t attempt to launch before the network is ready. ## Obvious Question: Why to use terragrunt instead of directly using terraform modules or terraform workspaces? While terraform workspaces can be used for multiple environments , [hashicorp does not recommend it](https://developer.hashicorp.com/terraform/cli/workspaces) > CLI workspaces within a working directory use the same backend, so they are not a suitable isolation mechanism for this scenario. Even with Terraform modules, you can simply pass the variable and use it. However, this adds more boilerplate, making it more complex to maintain in the long run. I’m not suggesting that you should use Terragrunt; I’m just pointing out the facts. Ultimately, the decision depends on the type of project you are working on. ## Wrapping Up Terragrunt goes beyond just making Terraform easier, it’s about scaling your infrastructure management without much hassle. It keeps your configurations DRY, handles dependencies, and automates workflows, so you don’t have to worry about misconfigurations or tedious manual updates. If you’re frustrated with managing repetitive Terraform code across multiple environments, Terragrunt might just be the tool that simplifies your workflow and brings order to your infrastructure management. Give it a try; it’s been a game-changer for me, and it could be for you too. --- # NFS Filesystem as Docker Volumes By Nimisha G J · 2024-08-19 Canonical: https://www.infraspec.dev/blog/nfs-fs-as-docker-volume As an Infrastructure engineer, I’ve had my fair share of experiences with containerized environments and the challenges of managing data persistence. One of the most significant problems I’ve faced is ensuring that data generated by Docker containers persists even when the container is stopped or deleted. That’s when I discovered the power of leveraging the Network File System (NFS) as volumes in Docker. It all started while working on a complex, multi-container application that required efficient data management. I knew that Docker volumes were the way to go, but I still needed a solution that would provide centralised storage management, scalability, and seamless file sharing across different containers and hosts. That’s when I turned to NFS. ## Let’s understand what is a Docker Volume In containerised environments, Docker volumes enable the persistent storage of data generated by Docker containers. Within the Docker context, a volume is considered a specially designated directory within one or more containers outside the typical Union File System. This means that data stored in volumes persists even when the container is stopped or deleted, making volumes indispensable for scenarios where data persistence is required. ## What does Network File System mean? NFS, also known as Network File System, is a distributed file system protocol that allows clients to access files and directories stored on remote servers as if they were local. Operated over a network, NFS provides a shared file system that can be accessed by multiple clients simultaneously. NFS offers benefits such as centralised storage management, improved data availability, and seamless file sharing across heterogeneous environments. ## Prerequisites We need the following tools preinstalled before proceeding forward. - NFS server - Docker and Docker-compose My journey began with setting up an NFS server. I created a directory at /srv/nfs where the NFS server would store the shared files. I then added an entry to the /etc/exports file, specifying that the directory /srv/nfs could be accessed by any client with read-write permissions. I also set the permissions for the NFS directory to 755, ensuring that the owner had full read-write-execute permissions while others had read-and-execute permissions. > Use the following script to install the NFS server. ``` #!/bin/bash # Step 1: Create a directory for NFS NFS_DIR="/srv/nfs" echo "Creating NFS directory at $NFS_DIR..." sudo mkdir -p $NFS_DIR # Step 2: Add export entry to /etc/exports EXPORTS_ENTRY="$NFS_DIR *(rw,sync,no_subtree_check)" echo "Adding the following entry to /etc/exports:" echo "$EXPORTS_ENTRY" echo "$EXPORTS_ENTRY" | sudo tee -a /etc/exports # Step 3: Grant necessary permissions to the NFS directory echo "Setting permissions for $NFS_DIR..." sudo chmod 755 -R $NFS_DIR # Step 4: Restart the NFS service to apply changes echo "Restarting NFS service..." sudo exportfs -ra sudo systemctl restart nfs-kernel-server echo "NFS server setup complete!" ``` > Run the above script using the following commands ``` chmod +x setup_nfs.sh ``` ``` sudo ./setup_nfs.sh ``` With the NFS server setup complete, I created an NFS Docker volume using the docker volume create command. I specified the NFS server’s IP address, the mount point, and the device path. > To create a docker volume with nfs configuration, you can use following command: ``` docker volume create --driver local --opt type=nfs --opt o=addr=,rw --opt device=:/srv/nfs nfs-volume ``` Output: ``` $ docker volume create --driver local \ --opt type=nfs --opt o=addr=192.168.1.7,rw \ --opt device=:/srv/nfs nfs-volume nfs volume ``` > To verify that the volume was created successfully, I used this command. ``` docker volume ls ``` Output: ``` $ docker volume ls DRIVER VOLUME NAME local nfs-volume ``` ## Mounting NFS in a Container: A Moment of Truth Next, I mounted the NFS volume in a container using the docker run command. I specified the NFS volume and the mount point in the –mount section. > To mount the NFS volume in a container, you can use the following command: ``` docker run --name nfs_mounted_node_container \ --mount source=nfs-volume,target=/opt node ``` Output: ``` $ docker run --name nfs_mounted_node_container \ --mount source=nfs-volume,target=/opt \ alpine Unable to find image 'alphine:latest' locally latest: Pulling from library/alphine 5e6ec7f28fbf: Pull complete Digest: sha256:185518070891758909c9f839cf4ca393ee977ac378609f700f60a6718c2b6d6a Status: Downloaded newer image for alphine:latest 1d7e2e2b8e2e0d1 ``` > To verify, we can use the following command with docker exec: ``` docker exec -it nfs_mounted_node_container sh ``` ``` mount | grep /opt ``` It will display something similar to this ``` $ docker exec -it nfs_mounted_node_container sh # mount | grep /opt :/ on /opt type nfs4 (rw,relatime,vers=4.0,risze=104348,wsize=1932432) ``` ## Docker Compose and NFS: Expanding Horizons But the journey didn’t stop there. I needed to ensure that my NFS volumes could be easily managed across multiple containers. This is where Docker Compose came into play. By creating a docker-compose.yml file, I could define services that utilised NFS volumes: > Use the below command to create a new file ``` nano docker-compose.yml ``` Write the following contents inside the Docker Compose file. ``` version: '3.8' services: mongo: image: mongo container_name: nfs_mounted_container volumes: - mongo_data:/data/db volumes: mongo_data: driver_opts: type: nfs4 o: addr=,rw device: ":/srv/nfs" ``` ## Advantages I Discovered with NFS for Docker Storage Looking back at this, the benefits of using NFS for persistent volumes in Docker are clear: 1. Centralized Storage Management: NFS provides a centralised storage solution where files and directories are stored on remote servers. This centralised approach simplifies storage management as administrators can manage and maintain data from a single location. 1. Scalability: NFS allows for seamless scaling of storage capacity by adding more NFS servers or expanding existing ones. This scalability ensures that Docker containers can access sufficient storage resources as application demands grow. 1. Improved Data Availability: With NFS, data stored on remote servers is readily available to Docker containers across the network. This improved availability ensures that applications have continuous access to critical data, minimising downtime and improving overall reliability. 1. Seamless File Sharing: NFS enables seamless file sharing across multiple Docker containers and hosts. Containers can mount NFS volumes and access shared files and directories, facilitating collaboration and data sharing among different application parts. 1. Data Consistency and Reliability: NFS ensures data consistency and reliability by maintaining a single version of truth for files and directories stored on remote servers. This reliability ensures that Docker containers retrieve accurate and up-to-date information from NFS volumes, enhancing application stability. However, using this setup for database containers would be a bad idea. 1. Compatibility and Interoperability: NFS is supported by a wide range of operating systems and platforms, making it highly compatible and interoperable with various Docker environments. This compatibility allows Docker containers running on different systems to access NFS volumes seamlessly. ## Conclusion In short, using NFS with Docker offers many benefits; it helps manage storage in one place, scales easily, ensures data is always available, allows easy file sharing, maintains data accuracy, and works well with different systems. Overall, it boosts application performance and reliability by handling data efficiently across different setups. This makes it a strong choice for managing data effectively in modern applications. ## Question Have you tried using NFS with Docker yet? If you have, what did you like, and what didn’t you like? --- # AWS ECS: FARGATE vs self-managed EC2 By Saumitra Topinkatti · 2024-08-13 Canonical: https://www.infraspec.dev/blog/aws-ecs-fargate-vs-self-managed-ec2 Cooking Up Cloud: Fargate or EC2—Which Kitchen Suits You? The Amazon Elastic Container Service (ECS) from Amazon deploys and manages containerised applications in two distinct modes of operation: Fargate and self-managed EC2. Each offering has its strengths and is different from the other, making the choice between them a critical decision for businesses. This blog discusses some of the more prominent differences between AWS ECS Fargate and EC2: architectures, advantages, challenges, and cost implications of running workloads in ECS Fargate versus ECS EC2. Whether you’re looking for operational simplicity or maximum control over infrastructure, this guide will help you navigate the differences between these two powerful container orchestration modes. ## FARGATE: A Chef At The Restaurant [AWS Fargate](https://aws.amazon.com/fargate/) is a serverless compute engine for containers that abstracts the complexities of managing the underlying infrastructure. With Fargate, you can focus solely on building and deploying your containerised applications without worrying about provisioning, configuring, or scaling virtual machines. This fully managed service automatically handles scaling, load balancing, and networking, allowing you to allocate resources precisely based on your application’s needs. Whether running microservices, batch jobs, or other containerised workloads, Fargate provides a simplified, efficient, and secure environment that adapts to dynamic demands, just like a Chef at a restaurant who cooks everything for you. The only input they need is what you will eat. ![FARGATE Chef Analogy](https://www.infraspec.dev/images/blog/aws-ecs-fargate-vs-self-managed-ec2/fargate-chef-analogy.webp) ## EC2: A Home’s Kitchen [Amazon Elastic Compute Cloud (EC2)](https://aws.amazon.com/ec2/) is a flexible and scalable cloud computing service that provides virtual servers, known as instances, for various applications. With EC2, you have complete control over the operating system, instance types, and configurations, allowing you to customise your environment to meet specific needs. Whether hosting web applications, running batch processes, or managing complex workflows, EC2 offers a robust and adaptable infrastructure tailored to your performance and cost requirements. By choosing from various instance types and sizes, you can optimise resource allocation and scale your infrastructure as needed, all while maintaining control over the underlying hardware and software, just like a typical Home Kitchen where you decide what you will cook with complete granular control over everything. ![EC2 Home Kitchen Analogy](https://www.infraspec.dev/images/blog/aws-ecs-fargate-vs-self-managed-ec2/ec2-home-kitchen-analogy.webp) ## FARGATE vs EC2: What are the differences? Understanding their fundamental differences is crucial when choosing between AWS Fargate and EC2 for your containerised applications. Each mode offers unique advantages and trade-offs across various deployment, management, and cost aspects. Here’s a brief comparison to help you identify which option best suits your needs. | FARGATE | EC2 | | --- | --- | | Infrastructure Management | Serverless; abstracts infrastructure management, allowing you to focus solely on your containers. | Requires manual management of virtual machines, including provisioning, configuration, and scaling. | | Resource Allocation | Pay-per-task based on vCPU and memory; dynamically allocates resources based on task requirements. | Fixed costs based on instance type; you pay for the entire instance regardless of how much its capacity is used. | | Scalability | Automatically scales based on task requirements; no need for manual intervention. | Requires manual scaling or configuration of auto-scaling groups to adjust capacity. | | Operational Overhead | Low operational overhead; AWS handles server management, patching, and scaling. | Higher operational overhead; you manage server maintenance, patching, and scaling. | | Customization | Limited customisation of underlying infrastructure; focuses on container management. | High customisation; you have full control over instance types, storage options, and network configurations. | | Cost Efficiency | Ideal for unpredictable workloads with variable resource needs; pay only for the resources used. | More cost-effective for consistent, high-utilization workloads; offers various pricing plans like Savings Plans and Reserved Instances. | | Performance Optimization | Resource limits are predefined; require monitoring and adjustment to optimise performance. | Allows for detailed benchmarking and tuning of resources to match specific performance needs. | ## ECS w/ FARGATE When using ECS with Fargate, you define your application’s requirements, such as CPU and memory, and Fargate handles the rest. This includes provisioning, scaling, and managing server infrastructure, allowing you to focus solely on developing and deploying your applications ( [read more](https://aws.amazon.com/blogs/compute/building-deploying-and-operating-containerized-applications-with-aws-fargate/) ). ![ECS with FARGATE](https://www.infraspec.dev/images/blog/aws-ecs-fargate-vs-self-managed-ec2/ecs-with-fargate.png) ## ECS w/ EC2 When using ECS with EC2, you have complete control over the underlying infrastructure that runs your containerised applications. This approach allows you to provision and manage EC2 instances, selecting specific instance types, sizes, and configurations that best meet your application’s needs. With ECS on EC2, you manage the cluster’s capacity, including scaling, patching, and maintaining the instances. This offers greater flexibility for performance tuning, custom networking setups, and the ability to use GPUs ( [read more](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_container_instance.html) ). ![ECS with EC2](https://www.infraspec.dev/images/blog/aws-ecs-fargate-vs-self-managed-ec2/ecs-with-ec2.png) However, it also comes with increased operational overhead, as you need to ensure the infrastructure is managed correctly and optimised for your workload. This mode is ideal for scenarios requiring detailed control and customisation of the computing environment. ## FARGATE vs EC2: Cost Analysis When deciding between AWS Fargate and EC2, understanding the cost difference can make or break your decision. Let’s compare the costs for our specific setup. Please note that the following cost estimates for the services fall in the [ap-south-1 region](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-regions) (i.e., Mumbai). | Resource | Allocation | | --- | --- | | vCPU | 2 | | Memory | 4 GB | | Storage | 20 GB | | Operating System | Linux | | CPU Architecture | x86 | ### Fargate Costs With Fargate, you’re paying directly for the resources your tasks use. In our case, running a task continuously for a month raises a bill of about $75.73. This includes everything from vCPU and memory charges, with storage thrown in for free (thanks to the 20 GB free tier). The selling point of Fargate is that you don’t have to worry about managing the infrastructure, but that convenience comes with a higher price tag, especially if your workload is always on. 1 task × 2 vCPU × 730 hours × $0.04256 per hour = $62.14 for vCPU hours 1 task × 4.00 GB × 730 hours × $0.004655 per GB per hour = $13.59 for GB hours 20 GB - 20 GB (no additional charge) = $0.00 billable ephemeral storage per task Total Fargate cost (monthly): $75.73 ### EC2 Costs Running the same workload on EC2 gives you a few pricing paths: - On-Demand Pricing If you go the on-demand route, the monthly cost is about $18.17. This covers both the instance and storage costs. It’s the most flexible option, but you’re paying more per hour. On-Demand Hourly cost: $0.0224 1 instance × $0.0224 × 730 hours in a month = $16.35 20 GB × 1 instance months × $0.0912 = $1.82 (EBS Storage Cost) Total On-Demand cost (monthly): $18.17 - Compute Savings Plan With a 1-year commitment and no upfront cost, this drops the monthly price to $13.65, 25% cheaper than On-Demand instances. It’s a solid choice if your workload is predictable, offering decent savings over on-demand pricing. Hourly cost: $0.0162 1 instance × $0.0162 × 730 hours in a month = $11.83 20 GB × 1 instance months × $0.0912 = $1.82 (EBS Storage Cost) Total Compute Savings Plan cost (monthly): $13.65 - EC2 Instance Savings Plan This is the cheapest option, costing around $12.19 per month, about 33% cheaper than On-Demand. You’ll need to commit to a specific instance type, but if that fits your needs, it’s the way to go for maximum savings. Hourly cost: $0.0142 1 instance × $0.0142 × 730 hours in a month = $10.37 20 GB × 1 instance months × $0.0912 = $1.82 (EBS Storage Cost) Total EC2 Instance Savings Plan cost (monthly): $12.19 #### The Point Is Fargate’s higher price includes reduced operational hassle, automatic scaling, and simplicity—big perks if your workload is dynamic or unpredictable. Conversely, if your workload is steady and you like having more control, EC2 could be your better bet. So, choosing EC2 could save you up to 84% compared to Fargate, depending on your pricing plan. That’s some serious savings to consider when making your choice! ## Conclusion In conclusion, choosing between AWS Fargate and EC2 involves balancing your specific needs with the strengths and trade-offs each mode offers. Fargate simplifies container management with a fully managed, serverless environment, making it ideal for dynamic workloads and teams focused on reducing operational overhead. On the other hand, EC2 offers more control and cost efficiency, especially with Savings Plans, making it a better fit for steady, predictable workloads where performance tuning and customization are key. Ultimately, the best choice depends on your workload’s demands and your team’s priorities—whether it’s simplicity and flexibility or control and cost savings. Until next time, Happy Coding. --- # Managing Credentials and Secrets in Terraform By Rahul Patil · 2024-08-06 Canonical: https://www.infraspec.dev/blog/terraform_secrets_management_guide Imagine you’re working on a project where you need to deploy resources to aws using terraform. In a rush to get things done, you decide to hard-code your AWS credentials directly into your Terraform files. Everything works fine at first, and your resources are successfully deployed. But a few weeks later, you discover that your Terraform repository was accidentally made public. Suddenly, your AWS credentials are exposed to the entire internet. Exposing your credentials can lead to unauthorized access to your AWS account, leading to serious security problems. This scenario highlights why it’s essential to manage secrets and credentials securely. Hard-coding sensitive information in your codebase is risky. To avoid such issues, it’s crucial to explore secure methods for managing secrets and credentials in Terraform. In this blog, we’ll explore several methods for managing secrets and credentials securely, including environment variables, GitHub Secrets, encrypted files with AWS KMS, and AWS Secrets Manager. We’ll also compare these methods to help you choose the best approach for your needs. ## Method 1: Environment Variables Using environment variables to manage secrets in Terraform is straightforward and commonly used. This approach keeps sensitive data like usernames and passwords out of your codebase and allows for easy integration with your CI/CD pipelines. Imagine you need to create an AWS RDS instance, and you want to keep the database username and password secure. 1. Define Sensitive Variables in Terraform: First, define your sensitive variables in your Terraform configuration file. Marking them as sensitive ensures that Terraform treats them securely. ``` variable "db_password" { type = string sensitive = true } variable "db_username" { type = string sensitive = true } ``` 2. Use Variables in Resource Definitions: Use these variables in your resource definitions. Here’s an example of an AWS RDS instance where the database username and password are sourced from the defined variables. ``` resource "aws_db_instance" "example" { identifier = "mydbinstance" engine = "mysql" instance_class = "db.t3.micro" allocated_storage = 10 publicly_accessible = true skip_final_snapshot = true username = var.db_username password = var.db_password } ``` 3. Set Environment Variables: Before applying your Terraform configuration, set the environment variables for the database username and password. This can be done in your shell or CI/CD pipeline configuration. ``` export TF_VAR_db_username="my_db_username" export TF_VAR_db_password="my_db_password" ``` 4. Apply Terraform Configuration: Finally, run your Terraform commands as usual. Terraform will read the environment variables and use them to configure your resources. ``` terraform init terraform plan terraform apply ``` ## Method 2: Encrypted Files (KMS) Using encrypted files to manage secrets in Terraform is a robust approach that enhances security by leveraging AWS Key Management Service (KMS). This method ensures that sensitive information is stored in an encrypted format and decrypted only when needed by Terraform. ![Encrypted Files (KMS)](https://www.infraspec.dev/images/blog/terraform-secrets-management/encrypted-files-kms.webp) Imagine you need to create an AWS RDS instance, and you want to keep the database username and password secure by storing them in an encrypted file. 1. Create a YAML File with Credentials: First, create a YAML file (db-creds.yml) that contains your database credentials: ``` db_username: my_db_username db_password: my_db_password ``` 2. Encrypt the YAML File Using AWS KMS: Alternative 1: Using AWS CLI You can use the AWS CLI to manually encrypt your YAML file: ``` aws kms encrypt --key-id --region --plaintext fileb://db-creds.yml --output text --query CiphertextBlob > db-creds.yml.encrypted ``` Replace and with your KMS key ID and AWS region, respectively. Alternative 2: Using Terraform You can also handle encryption through Terraform: ``` variable "db_username" { type = string sensitive = true } variable "db_password" { type = string sensitive = true } resource "aws_kms_key" "db_creds_key" { description = "KMS key for encrypting database credentials" tags = { Name = "db_creds_key" } } resource "aws_kms_ciphertext" "db_creds" { key_id = aws_kms_key.db_creds_key.id plaintext = jsonencode({ db_username = var.db_username db_password = var.db_password }) context = { "Purpose" = "Encrypting database credentials" } } resource "aws_secretsmanager_secret" "db_creds" { name = "db-credentials" } resource "aws_secretsmanager_secret_version" "db_creds_version" { secret_id = aws_secretsmanager_secret.db_creds.id secret_string = aws_kms_ciphertext.db_creds.ciphertext_blob } ``` Note: Store your secrets in a terraform.tfvars file or pass them as environment variables: ``` # terraform.tfvars db_username = "my_db_username" db_password = "my_db_password" ``` Alternatively, set environment variables before running Terraform commands: ``` export TF_VAR_db_username="my_db_username" export TF_VAR_db_password="my_db_password" ``` 3. Define KMS Data Source in Terraform: Use the aws_secretsmanager_secret_version data source in your Terraform configuration to retrieve and decrypt the encrypted file: ``` data "aws_secretsmanager_secret_version" "creds" { secret_id = aws_secretsmanager_secret.db_creds.id depends_on = [aws_secretsmanager_secret.db_creds, aws_secretsmanager_secret_version.db_creds_version] } locals { db_cred = jsondecode(data.aws_secretsmanager_secret_version.creds.secret_string) } ``` 4. Use Decrypted Credentials in Resource Definitions: Use the decrypted credentials in your resource definitions. Here’s an example of an AWS RDS instance where the database username and password are sourced from the decrypted file: ``` resource "aws_db_instance" "example" { identifier = "mydbinstance" engine = "mysql" instance_class = "db.t3.micro" allocated_storage = 10 publicly_accessible = true skip_final_snapshot = true username = var.db_username password = var.db_password } ``` 5. Apply Terraform Configuration: Finally, run your Terraform commands as usual. Terraform will decrypt the file using AWS KMS and use the credentials to configure your resources: ``` terraform init terraform plan terraform apply ``` ## Method 3: AWS Secrets Manager AWS Secrets Manager provides a secure way to store and manage sensitive information such as database credentials, API keys, and other secrets. This method allows you to retrieve secrets dynamically within your Terraform configuration, ensuring that sensitive data is never hard-coded in your Terraform files. ![AWS Secrets Manager](https://www.infraspec.dev/images/blog/terraform-secrets-management/secrets-manager.webp) Here’s how you can manage your database credentials using AWS Secrets Manager: 1. Store Your Secrets in AWS Secrets Manager using Terraform: First, use Terraform to create a secret in AWS Secrets Manager. Define the secret in your Terraform configuration, using variables to keep sensitive information secure: ``` variable "db_username" { type = string sensitive = true } variable "db_password" { type = string sensitive = true } resource "aws_secretsmanager_secret" "mysql_cred" { name = "mysql-cred" } resource "aws_secretsmanager_secret_version" "mysql_cred_version" { secret_id = aws_secretsmanager_secret.mysql_cred.id secret_string = jsonencode({ db_username = var.db_username db_password = var.db_password }) } ``` Note: Store your secrets in a terraform.tfvars file or pass them as environment variables: ``` # terraform.tfvars db_username = "my_db_username" db_password = "my_db_password" ``` Alternatively, set environment variables before running Terraform commands: ``` export TF_VAR_db_username="my_db_username" export TF_VAR_db_password="my_db_password" ``` 2. Retrieve Secrets in Terraform: Use the aws_secretsmanager_secret_version data source to fetch the secret from AWS Secrets Manager: ``` data "aws_secretsmanager_secret_version" "creds" { secret_id = aws_secretsmanager_secret.mysql_cred.id depends_on = [aws_secretsmanager_secret.mysql_cred, aws_secretsmanager_secret_version.mysql_cred_version] } locals { db_cred = jsondecode(data.aws_secretsmanager_secret_version.creds.secret_string) } ``` 3. Use Retrieved Secrets in Resource Definitions: Use the retrieved credentials in your resource definitions. Here’s an example of an AWS RDS instance where the database username and password are sourced from AWS Secrets Manager: ``` resource "aws_db_instance" "example" { identifier = "mydbinstance" engine = "mysql" instance_class = "db.t3.micro" allocated_storage = 10 publicly_accessible = true skip_final_snapshot = true username = var.db_username password = var.db_password } ``` Alternative: Store Secrets Using AWS CLI: If you prefer, you can also store your secrets in AWS Secrets Manager using the AWS CLI. This can be an alternative to storing secrets directly via Terraform: ``` aws secretsmanager create-secret --name mysql-cred --secret-string '{"db_username":"my_db_username","db_password":"my_db_password"}' ``` 4. Apply Terraform Configuration: Run your Terraform commands as usual. Terraform will retrieve the secret values from AWS Secrets Manager and use them to configure your resources: ``` terraform init terraform plan terraform apply ``` ## Method 4: GitHub Secrets For projects managed with GitHub, using GitHub Secrets is a convenient way to store and manage secrets securely within GitHub Actions workflows. This method is particularly useful for CI/CD pipelines where you need to keep sensitive data safe while automating deployments. ![GitHub Secrets](https://www.infraspec.dev/images/blog/terraform-secrets-management/github-actions-workflow.png) Here’s how you can manage your database credentials using GitHub Secrets: 1. Add Secrets to GitHub Repository: Navigate to your GitHub repository, go to Settings > Secrets and variables > Actions , and add your secrets. Use names like DB_USERNAME and DB_PASSWORD . 2. Access Secrets in GitHub Actions Workflow: In your GitHub Actions workflow file ( .github/workflows/your-workflow.yml ), you can access these secrets as environment variables: ``` name: Deploy on: push: branches: - main jobs: deploy: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v3 - name: Set up Terraform uses: hashicorp/setup-terraform@v2 with: terraform_version: - name: Terraform Init run: terraform init - name: Terraform Apply env: TF_VAR_db_username: ${{ secrets.DB_USERNAME }} TF_VAR_db_password: ${{ secrets.DB_PASSWORD }} run: terraform apply -auto-approve ``` 3. Use Secrets in Terraform Configuration: Your Terraform configuration file remains unchanged, as it relies on the environment variables provided by GitHub Actions. ### Comparison of Methods | Method | Pros | Cons | Use Case | | --- | --- | --- | --- | | Environment Variables | Simple to set up and use. | Secrets are exposed in environment variables. | Suitable for quick setups or local development. | | Encrypted Files (KMS) | High security with encryption at rest. | Requires additional steps for encryption/decryption. | Ideal for scenarios where KMS is already used. | | AWS Secrets Manager | Secure storage with automatic rotation. | Costs associated with Secrets Manager. | Best for production environments needing dynamic secrets. | | GitHub Secrets | Convenient for CI/CD workflows. | Limited to GitHub Actions. | Good for managing secrets in CI/CD pipelines. | ## Recommendations - Development Environments: Environment variables or encrypted files (KMS) can be sufficient and are easier to set up. - Production Environments: AWS Secrets Manager provides robust security features and is recommended for managing secrets in production. By understanding and applying these methods, you can ensure that your sensitive information remains secure and your Terraform configurations are well-managed. --- # Essential AWS Tagging Strategies By Rohit Nagmoti · 2024-07-29 Canonical: https://www.infraspec.dev/blog/tag-strat-blog ## Introduction Managing cloud resources efficiently in AWS requires a robust tagging strategy. Tags are key-value pairs attached to resources, providing crucial metadata for resource management, cost allocation, security, and automation. This blog will guide you through defining mandatory and discretionary tags and establishing detection and enforcement mechanisms to ensure compliance across your AWS environment. ## The Problem: Untracked Resources and Rising Costs At Infraspec, we started noticing some major issues with how we were managing our AWS resources. We had several AWS accounts in use, but no tagging standards were enforced. This meant that anyone could create resources, and sometimes, these resources were left running long after they were needed. As a result, our cloud costs were steadily increasing each month, and we had no clear way to track who was responsible for which resources. Without any tags, it was impossible to tie costs back to specific teams or projects, leaving us in the dark about where our budget was really going. This lack of accountability was causing both operational and financial headaches. ## Our Approach: Structuring AWS Accounts and Enforcing a Tagging Policy Realizing that we needed a way to get things under control, we started exploring how AWS tags could help. By enforcing a tagging policy across all our AWS accounts, we could ensure that every resource was labeled with essential information like the owner, team, and environment. But we didn’t stop there. To make sure everyone followed the rules, we implemented Service Control Policies (SCPs) that would block the creation of any resources that didn’t have the necessary tags. This added a layer of enforcement that gave us confidence that our tagging strategy would actually be used. ![AWS Organization](https://www.infraspec.dev/images/blog/tag-strat-aws/aws-organization.png) ### Step 1: Organizing Accounts Our first step was to create an AWS Organizations structure that mirrored our operational needs. We separated our accounts into two main Organizational Units (OUs): Infraspec OU and Core OU . The Infraspec OU contains all the accounts related to our primary operations, including Dev , Staging , and Prod . The Core OU contains our Core Account , which handles shared services such as networking and also handles policy management instead of root account. This structure allowed us to clearly distinguish between different environments and core services, making it easier to enforce policies and manage resources. ### Step 2: Implementing Tagging Policy With our accounts organized, we moved on to enforce a tagging policy across all our AWS accounts. We established a set of mandatory tags that would be required for specific resource, ensuring that resources were labeled with essential information like the owner, management of the rescource etc. To ensure compliance, we implemented Service Control Policies (SCPs) that blocked the creation of any resources without the necessary tags. This enforcement layer gave us the confidence that our tagging strategy would be consistently applied across all environments. We defined the following tags as mandatory across our AWS environment and implemented them using AWS Organizations Tag Policies. Below is an example of how these tags were structured and enforced: ``` { "tags": { "Owner": { "tag_key": { "@@assign": "Owner" }, "enforced_for": { "@@assign": [ "ec2:instance", "ec2:vpc", "ec2:subnet", "ec2:natgateway", "ec2:security-group", "ec2:route-table", "ec2:internet-gateway" ] } }, "ManagedBy": { "tag_key": { "@@assign": "ManagedBy" }, "tag_value": { "@@assign": [ "Terraform", "Manual" ] }, "enforced_for": { "@@assign": [ "ec2:instance", "ec2:vpc", "ec2:subnet", "ec2:natgateway", "ec2:security-group", "ec2:route-table", "ec2:internet-gateway" ] } } } } ``` ### Step 2: Implementing Service Control Policy We created SCPs in AWS Organizations to prevent the creation of resources without mandatory tags. For example, the following SCP blocks the creation of EC2 instances and other resources if the Owner and ManagedBy tag is missing: ``` { "Version": "2012-10-17", "Statement": [ { "Sid": "DenyEC2CreationWithNoOwnerTag", "Effect": "Deny", "Action": [ "ec2:RunInstances", "ec2:CreateVpc", "ec2:CreateSubnet", "ec2:CreateNatGateway", "ec2:CreateSecurityGroup", "ec2:CreateRouteTable", "ec2:CreateInternetGateway" ], "Resource": [ "arn:aws:ec2:*:*:vpc/*", "arn:aws:ec2:*:*:subnet/*", "arn:aws:ec2:*:*:natgateway/*", "arn:aws:ec2:*:*:security-group/*", "arn:aws:ec2:*:*:route-table/*", "arn:aws:ec2:*:*:internet-gateway/*", "arn:aws:ec2:*:*:instance/*" ], "Condition": { "Null": { "aws:RequestTag/Owner": "true" } } }, { "Sid": "DenyEC2CreationWithNoManagedByTag", "Effect": "Deny", "Action": [ "ec2:RunInstances", "ec2:CreateVpc", "ec2:CreateSubnet", "ec2:CreateNatGateway", "ec2:CreateSecurityGroup", "ec2:CreateRouteTable", "ec2:CreateInternetGateway" ], "Resource": [ "arn:aws:ec2:*:*:vpc/*", "arn:aws:ec2:*:*:subnet/*", "arn:aws:ec2:*:*:natgateway/*", "arn:aws:ec2:*:*:security-group/*", "arn:aws:ec2:*:*:route-table/*", "arn:aws:ec2:*:*:internet-gateway/*", "arn:aws:ec2:*:*:instance/*" ], "Condition": { "Null": { "aws:RequestTag/ManagedBy": "true" } } } ] } ``` ### Step 3: Attaching the Service Control Policy and Tag Policy After defining the policies, the next crucial step is to attach them to the appropriate Organizational Units (OUs) within AWS Organizations. By attaching both the Service Control Policy (SCP) and Tag Policy to the Infraspec OU , you ensure that all accounts under this OU enforce the mandatory tagging policy. #### Attaching the Service Control Policy (SCP) to an OU - Navigate to the SCP Policy Section: Sign in to the AWS Management Console and go to the AWS Organizations console at [https://console.aws.amazon.com/organizations](https://console.aws.amazon.com/organizations) . - Attach the SCP: Go to the Service control policies tab and click Create policy to define your SCP. After creating the policy, click on Targets to attach it to the desired OU. #### Attaching the Tag Policy to an OU - Navigate to the Tag Policy Section: Sign in to the AWS Management Console and go to the AWS Organizations console at https://console.aws.amazon.com/organizations . - Attach the Tag Policy: Go to the Tag policies tab and click Create policy to define your Tag Policy. After creating the policy, click on Targets to attach it to the desired OU. ## Handling Existing Resources Without Tags Addressing the challenge of existing resources that were created before implementing the tagging policy was crucial. To bring these resources into compliance without causing any unexpected downtime, we followed a structured approach: - Tagging Existing Resources : We utilized the AWS Tag Editor to identify all untagged resources. This tool enabled us to efficiently apply the necessary tags to multiple resources across various regions and accounts, ensuring consistency and compliance. ## Testing the Policy After implementing the tagging and scp policies, we conducted rigorous testing to ensure compliance across our EC2 resources. We deployed several EC2 instances with and without the mandatory tags to verify the enforcement mechanisms. - Success Case : When an EC2 instance was launched with all mandatory tags ( Owner , ManagedBy ), the instance creation proceeded without any issues. - Failure Case : When an attempt was made to launch an EC2 instance without the ManagedBy tag, the operation was denied, demonstrating the effectiveness of our SCP in enforcing tag compliance. ## The Impact of Tags in Our Organization ### Resource Identification and Ownership - Owner Tag : By tagging each resource with an Owner , we could quickly identify who was responsible for any given resource. This became critical when tracking down resources that were running unexpectedly or were no longer needed. The Owner tag provided clear accountability, making it easier to manage and decommission resources no longer in use. ### Operational Efficiency and Automation - ManagedBy Tag : The ManagedBy tag helped us distinguish between resources managed by Terraform and those managed manually. This was particularly useful for automating resource management and ensuring that Terraform-managed resources were consistent with our infrastructure-as-code policies. ## Tag Naming and Usage Conventions To ensure consistency and avoid conflicts, adhere to the following conventions: 1. Tag Limits : Each resource can have a maximum of 50 tags. 1. Unique Tags : Each tag key must be unique per resource, and each tag key can have only one value. 1. Length Limits : The maximum tag key length is 128 Unicode characters in UTF-8. The maximum tag value length is 256 Unicode characters in UTF-8. 1. Allowed Characters : Allowed characters are letters, numbers, spaces representable in UTF-8, and the following characters: . : + = @ _ / - (hyphen). Amazon EC2 resources allow any characters. 1. Case Sensitivity : Tag keys and values are case sensitive. Decide on a strategy for capitalizing tags and consistently implement that strategy across all resource types. For example, decide whether to use Costcenter , costcenter , or CostCenter , and use the same convention for all tags. 1. AWS Prefix : The aws: prefix is prohibited for tags; it’s reserved for AWS use. You can’t edit or delete tag keys or values with this prefix. Tags with this prefix do not count against your tags per resource quota. ## Best Practices for Tagging 1. Consistency : Use a standardized format for tags to avoid discrepancies. Decide on conventions for capitalization and delimiters and stick to them. 1. Automation : Automate tagging to reduce manual errors and ensure compliance. 1. Documentation : Maintain comprehensive documentation of your tagging strategy and dictionary for reference. 1. Stakeholder Involvement : Involve all relevant stakeholders in defining and reviewing the tagging strategy to ensure it meets organizational needs. ## Conclusion A well-defined tagging strategy is essential for effective cloud resource management. By distinguishing between mandatory and discretionary tags and implementing robust enforcement mechanisms, you can achieve better visibility, cost control, and security in your AWS environment. Start by establishing a clear tagging dictionary and ensure compliance through automation and regular audits. ## Additional Resources For further reading and deeper insights into AWS tagging strategies, consider the following resources: - [AWS Tagging Best Practices and Strategies](https://docs.aws.amazon.com/tag-editor/latest/userguide/best-practices-and-strats.html) – Comprehensive guide on best practices and strategies for tagging in AWS. - [AWS Organizations Tag Policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies.html) – Details on implementing and managing tag policies across accounts. - [AWS Service Control Policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scp.html) – Guide on using SCPs to enforce tagging standards. --- # GenAI Dictionary: Part 1 - LLM By Nandhitha Kamal · 2024-06-21 Canonical: https://www.infraspec.dev/blog/genai-dictionary-part1-llm We bring to you this weekly series of articles, to help understand and demystify the lexicon in the GenAI space. Here is part 1 - Large Language Model. ## Large Language Model A Large Language Model (LLM) is a deep learning model that has been trained on a massive amount of textual data, hence the name ’large’. Among other capabilities, they can understand and generate text. To put it very, very simply - an LLM has been fed enough examples as part of the training to be able to recognize and interpret human languages. This is why talking to ChatGPT feels so natural, like talking to a human. By virtue of the vast training data, it can also take on various personalities and tones, allowing us to use them in a wide array of contexts. An LLM is specifically trained on language data. Its inherent strength is that it has an enhanced ‘understanding’ of human languages. To be fair, LLMs are incapable of understanding language the way humans do. But… what an LLM knows is this: given a stream of text, which word should follow such that it makes the most sense in this context. It knows this by virtue of the vast patterns and contexts it has seen in the training data. To summarize, LLMs work by predicting the next token based on the patterns it has seen in its training data. This is what makes up for its conversational abilities. LLMs are trained on vast amounts of data collected (typically) from the Internet. GPT-3.5, for example, has been trained on 17 gigabytes of data from the following sources. ![gpt3.5-dataset](https://www.infraspec.dev/images/blog/genai-dictionary-part1-llm/gpt3.5-dataset.png) Source - [Language Models are Few-Shot Learners](https://arxiv.org/abs/2005.14165) ### Tokenization LLMs break down words into tokens when processing and generating text. A ’token’ is the smallest unit of text in the LLM world. A word is made up of one or more tokens. A simple rule of thumb - a token can be considered to be approximately 4 characters in length (this is not true all the time, but on average it works out to be this number). Complex words are composed of multiple tokens; punctuation marks are separate tokens by themselves. As an example, consider the following sentence. > “Hello! I am a bot.” Using the [OpenAI tokenizer](https://platform.openai.com/tokenizer) , this text can be broken down into 7 tokens as follows - “Hello”, “!”, " I", " am", " a", " bot", “.” ![simple-word-tokenization.png](https://www.infraspec.dev/images/blog/genai-dictionary-part1-llm/simple-word-tokenization.png) Now consider a sentence with more complex words. > “Renaissance faires are all the rage these days.” Using the same [OpenAI tokenizer](https://platform.openai.com/tokenizer) , this can be broken down into tokens as “R”, “ena”, “issance”, " f", “aires”, " are", " all", " the", " rage", " these", " days", “.” ![complex-word-tokenization.png](https://www.infraspec.dev/images/blog/genai-dictionary-part1-llm/complex-word-tokenization.png) Notice how the words “Renaissance” and “faires” are split into multiple tokens? But why tokenize? Tokenizing helps to represent the original text in a form that the model can process. Every token is mapped to a unique integer ID based on the model’s vocabulary. This allows the model to use the tokens to process and generate text. The exact logic of tokenizing varies across the different tokenizers. So it’s important to use the right tokenizer for the chosen LLM. To programmatically count the number of tokens, use the [tiktoken](https://github.com/openai/tiktoken) OpenAI tokenizer library. ### Parameters Parameters are the weights and biases that the model learns during training. A model with 70 billion parameters (70B model) has a very large capacity to learn complex patterns and representations from the data when compared against a model that has 8 billion parameters (8B model). The larger the parameters, the longer it takes the model to make inferences. ## It’s not all rosy… Despite how versatile LLMs can be, it is not all rosy. There exist some concerning, yet common problems with using LLMs - Hallucination - Hallucination is when LLMs make up answers that are factually incorrect. It can be difficult to spot when it is hallucinating, especially when the user is not familiar with the subject matter. - Can carry biases - It is possible for the model to carry biases. This stems from the training data. If the training data had had biases, they could be transferred to the model as well. - Can be discriminatory - This is also typically a function of the training data. If the training data contained much discriminatory content, the discriminations can pass on to the model-generated text as well. - It cannot possibly know information it was not trained on. This can cause them to become outdated if used solely in scenarios where the information is updated quickly. ### Choosing an LLM When choosing LLMs, it is important to choose the most suitable LLM for the use case. If you will ultimately be using it in the medical domain, it makes more sense to use an LLM that is built specifically for the medical domain (e.g., Med-PaLM). Similarly, choose models that are trained on and for the language that you’re building for. An LLM trained specifically on Indian languages (e.g., indicLLM) would be better than GPT’s Indian language text generation capabilities. Tools like [LMSys Arena](https://chat.lmsys.org/) Leaderboard also provide information on how a model ranks against another. ## In conclusion… 1. Large Language Models (LLMs) are deep learning models trained on vast textual data, enabling them to generate human-like text and adapt to various contexts by predicting the next token. 1. LLMs process text by breaking it into tokens, which are essential for handling text. The number of parameters in an LLM determines its learning capacity and complexity. 1. LLMs can suffer from hallucination, bias, and outdated information. Selecting the right LLM for a specific domain or language is crucial. --- # Building a Discord GPT Bot By Nandhitha Kamal · 2024-05-31 Canonical: https://www.infraspec.dev/blog/building-a-discord-gpt-bot Amidst the excitement surrounding AI, we were eager to delve into this field ourselves. As engineers, we wanted more than just a casual conversation with ChatGPT—we aimed to understand the intricacies of building AI applications. From the beginning, our goal was clear: to build muscle in this space while creating something practical for daily use that could provide real-world feedback. We envisioned integrating a ChatGPT-like experience within our messaging platform. Internally, we rely heavily on Discord, which holds a vast amount of information about our daily activities - the mundane, the exciting and everything in between. Incorporating ChatGPT into Discord would allow us to centralize our conversations and potentially develop operational tools around it. Unlike Slack, which has a ready-to-use solution, we couldn’t find a seemless Discord ChatGPT integration. This challenge seemed like the perfect project for us. Thus, our first project was born: building a ChatGPT bot for Discord from scratch. ## Step 1 -Setting up a python virtual environment (optional, but recommended): - Setup a python virtual environment - why should you this? This warrants a whole conversation by itself. But the tl;dr is that it helps you manage different python versions and project dependencies in a cleaner way. - I use conda . venv is a good alternative; regardless of whichever tool you use, remember to install dependencies only inside the virtual environment. ## Step 2 - Create a simple discord bot ![bot-settings](https://www.infraspec.dev/images/blog/building-a-discord-gpt-bot/bot-settings.png) - Goto https://www.discord.com/developers - Click on New Application; provide a name for it (e.g. - infraspec-gpt-bot) - Navigate to Settings -> Bot and disable Public Bot - this restricts the bot from being publicly discovered enable Message Content Intent . This allows the bot to read the message_content field of a message object ### Add bot to your discord server ![oauth2-app-scope](https://www.infraspec.dev/images/blog/building-a-discord-gpt-bot/oauth2-app-scope.png) ![oauth2-bot-permissions](https://www.infraspec.dev/images/blog/building-a-discord-gpt-bot/oauth2-bot-permission.png) ![add-to-server.png](https://www.infraspec.dev/images/blog/building-a-discord-gpt-bot/add-to-server.png) - Under Scopes, choose Bot - In the ensuing checklist that opens up, select the necessary bot permissions - Open the generated URL in your browser and add the bot to your discord server ### Coding a Python script to respond - Install python dependency discord.py with conda install discord.py - Create main.py with the following code - this responds only to messages beginning with $hello only ``` import discord import os discord_client = discord.Client() @discord_client.event async def on_ready(): print('We have logged in as {0.user}'.format(discord_client)) @discord_client.event async def on_message(message): if message.author == discord_client.user: return if message.content.startswith('$hello'): await message.channel.send('Hello!') discord_client.run(os.getenv('DISCORD_BOT_TOKEN')) ``` - Run the bot ``` export DISCORD_BOT_TOKEN= python main.py ``` ## Step 3 - Setup OpenAI API keys Now that we have a basic discord bot placeholder out of the way, let’s get onto making it work like chatgpt - for this we use the openAI APIs that have been made available. Before we get onto that though, let us pause here for a minute to understand the difference between chatgpt and openAI. OpenAI is the company that created ChatGPT. ChatGPT is an end user application that is powered by the underlying GPT models (gpt-3.5-turbo, gpt-4, gpt-4o, etc.); whereas the OpenAI APIs allow for us to directly use these models for our usecase. I suspect that ChatGPT might also have been fed some tailored prompts to make it slightly more end user amenable, the open AI APIs allow us to access the models in their more uncensored, raw forms. Let us create project API keys on platform.openai.com/api-keys. Make a note of the key somewhere secure as it won’t be possible to be view it later. To ensure that the API keys work as expected ``` export OPENAI_API_KEY= ``` ``` curl https://api.openai.com/v1/chat/completions -H "Content-Type: application/json" -H "Authorization: Bearer $OPENAI_API_KEY" -d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair." }, { "role": "user", "content": "Compose a poem that explains the concept of recursion in programming." } ] }' ``` You should see a valid response like below. ``` { "id": "chatcmpl-9UajPtC932k5XPjIelFg6Z2U4jV8g", "object": "chat.completion", "created": 1717078063, "model": "gpt-3.5-turbo-0125", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "In the realm of code, a concept profound,\nLies the technique of recursion, so truly renowned.\nA function calls itself, like echoes in the night,\nUnraveling mysteries, layer by layer, in its sight.\n\nLike a dance of shadows, recursive steps unfold,\nRepeating patterns, a story retold.\nEach iteration a journey, a loop in disguise,\nUnraveling problems, reaching for the skies.\n\nThrough the looking glass of recursive delight,\nWe traverse the depths of code, shining bright.\nA self-referential loop, a loop within a loop,\nA powerful tool, a programmer's scoop.\n\nOh recursion, elegant and grand,\nA concept so beautiful, at our command.\nInfinite possibilities, a journey unknown,\nIn the world of programming, a concept firmly honed." }, "logprobs": null, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 39, "completion_tokens": 162, "total_tokens": 201 }, "system_fingerprint": null } ``` ## Step 4 - Tying it all together Let’s now put it all together. We now have a discord bot and we have openAI API keys working as expected. Let’s now build our very own chatgpt, but on discord. At the simplest level, we want to pass on the message from the user to the model and return the API response to the user. Let’s modify the event handler for this - upon receiving a message, we will forward it to the [chat completion](https://platform.openai.com/docs/api-reference/chat) API and relay the API response back on the bot Install the python openai dependency with conda install openai Your modified event handler should look something like this ``` import discord import os from openai import OpenAI discord_client = discord.Client() openAI_client = OpenAI() GPT_MODEL = 'gpt-3.5-turbo' @discord_client.event async def on_ready(): print('We have logged in as {0.user}'.format(discord_client)) @discord_client.event async def on_message(user_message): if user_message.author == discord_client.user: return completion_response = openAI_client.chat.completions.create( model=GPT_MODEL, messages=user_message.content ) assistant_message = completion_response.choices[0].message.content await user_message.channel.send(assistant_message) discord_client.run(os.getenv('DISCORD_BOT_TOKEN')) ``` And… voila! A simple discord bot that lets you talk to GPT. The models do not have memory of the past requests and so at present, it just works as a relay layer. But we want more from it. We want to have a conversation with it, and not just use it for one-off fact checking. And to have a conversation, both parties need to be able to retain earlier parts of the conversation (at least within reasonable limits). We humans can do that naturally, but how would GPT do that? For this, we would need to do a little extra to make it ‘remember’. GPT’s chat completion API works by treating whatever you pass in the messages field of the request as context. It is, by design, allowed to pass (an optional) system message and a series of exchanges between the user and the GPT(assistant). You can use this either for few-shot prompting, or you could also use this to pass relevant bits of the conversation history so that GPT has access to past conversation and can reference that information as needed. Below is a sample of what the messages field would look like. ``` from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "When did the first world war start?"}, {"role": "assistant", "content": "The First World War, also known as World War I, began on July 28, 1914, and lasted until November 11, 1918. It was a global conflict primarily centered in Europe involving many of the world's great powers at the time."}, {"role": "user", "content": "Why did it start?"} ] ) ``` To help the model remember, add every turn of the conversation to the messages list field. Something to be cognisant of here is that the request has a limit of 4096 token. If the request is larger than 4096 tokens, it would be rejected. Ensure that your request is always under 4096 tokens. The API response also typically tells you how many tokens were used for the prompt and the completion. However, relying only on that to understand your token usage can be expensive. It’s recommended to calculate the number of tokens in your request before you send it out. You can use the [tiktoken](https://github.com/openai/tiktoken) library for this. And what do we do when we exceed the token limit? There are multiple ways you could approach this - drop off the earliest messages in the conversation - the caveat is that you never know if you might need it - summarize the conversation to reduce it to one conversational turn - this would incur an additional API call, but it would still retain important information, even if in a condensed form. Another discord specific challenge we faced was that discord has a character limit of 2000 characters. This meant that we had to check that our user message and API response were within limit and we had to handle for scenarios when they were beyond 2000 characters. So there you have it! This should hopefully be enough to give you an idea of how to get started. We hope to add more information and guides as we come across them. --- # Argo Rollout & AWS ALB 502 fix By Mufaddal Shakir · 2024-05-27 Canonical: https://www.infraspec.dev/blog/argo-rollout-aws-alb The blog discusses resolving a deployment issue with 502 errors on AWS EKS using AWS ALB and Argo Rollouts. It details the root cause, attempted solutions, and resulting trade-offs. ## Context We encountered a 502 at the AWS load balancer level during the deployment of one of our client’s service. This resulted in 1-2 minutes of downtime, which was unexpected even if the deployment was carried out during the day (during peak traffic). Nearly 15,000 requests were made to the high-throughput service every minute. Over 10 percent of requests resulted in 502 errors. Even during peak hours, the new version of the service was supposed to be rolled out without interfering with users’ individual requests. ## The Deployment Strategy Presently, all of our client’s services are hosted on AWS EKS using Kubernetes, and all Kubernetes manifests are managed in org, one of which is a GitHub repository that is synchronised with ArgoCD. Since Argo-Rollout Canary offers us the benefit of automated progressive delivery, we have chosen it as our deployment strategy. ![Current Deployment Setup](https://www.infraspec.dev/images/blog/header-Based-traffic-routing-using-argo-rollouts/deployment-workflow.png) We were using the AWS ALB to route traffic, and it was managing the instructions from the Argo Rollout to move traffic to a new service by using the canary steps specified in the rollout manifests. ## Initial Findings Upon analysing the ALB logs, we discovered that the 502 errors were originating from the older pods. ## Theory We were Considering The way the ALB manages traffic is the main source of the issue. Traffic is directed by the ALB to the specified targets—in this case, pods—when it is received. A termination state is reached by the older pods during a new deployment. Pods should not accept new requests and should, by default, process older ones during the 30-second termination grace period. Nevertheless, the ALB keeps sending requests to pods that are in the termination state during this time, which causes 502 errors to occur. ## Solutions We Tried 1. As far as we know, Kubernetes uses probes to identify unhealthy pods and removes them from the list of service endpoints. Thus, the probes are required. In order for Kubelet to properly communicate with Kubepoxy and remove the endpoint in the event of a failure, we have confirmed the intervals of checks once more. - To give Kube proxy enough time to remove the endpoint from service endpoint lists, we must add an extra delay. Pre-stop hooks were added to allow for a 60-second container-level sleep before pod termination. Following this, the system will send the SIGTERM signal to complete shutdown. ``` spec: containers: lifecycle: preStop: exec: command: - /bin/sh - '-c' - sleep 60 ``` - We have included a GraceFullShutdown of 90 seconds so that the application can process the existing requests. Upon receiving a SIGTERM signal, the application will no longer accept new ones and will take some time to process them. We also need to add some code to the application to make it understand that it should gracefully shut down before calling SIGKILL to end the application entirely in order to handle GraceFullShutdown. ``` spec: terminationGracePeriodSeconds: 90 ``` 1. Current configurations are the most important thing that can help us manage requests on older pods from the Kubernetes side, but we also need to consider things from the standpoint of AWS-ALB, since all traffic is routed through AWS-ALB and needs to be routed if the pods are in the termination state. - We increased the interval seconds from 15 to 10 seconds in order to more aggressively check the targets’ health. By doing this, the load balancer won’t send traffic to pods that are in termination state. ``` metadata: annotations: alb.ingress.kubernetes.io/healthcheck-interval-seconds: "10" ``` - Additionally, we want ALB to wait a suitable amount of time before eliminating targets that Kubernetes has labeled as unhealthy or terminated. To account for this, we have included a 30-second deregistration delay. ``` metadata: annotations: alb.ingress.kubernetes.io/target-group-attributes: deregistration_delay.timeout_seconds=30 ``` ## Do These Solutions Prove to be Beneficial? Congratulations! All above configuration was necessary and greatly helped us to reduce the 502s during the deployment but it was not completely removed. ## Actual Findings Interestingly, during our careful observation of the canary deployment steps, we noticed that the problem occurred specifically when we shifted traffic from 90% to 100% in the final canary step. ### What Definition Did This Canary Step Have? ``` canary: steps: - setCanaryScale: weight: 20 - setWeight: 0 - pause: { duration: 60 } - setCanaryScale: matchTrafficWeight: true - setWeight: 10 - pause: { duration: 60 } - setWeight: 60 - pause: { duration: 60 } - setWeight: 80 - pause: { duration: 60 } - setWeight: 90 - pause: { duration: 60 } - setWeight: 100 - pause: { duration: 60 } ``` The Argo Rollout canary configurations mentioned above appear to be normal, but the problem only surfaced during the final phase of increasing traffic from 90% to 100%. To be sure, we slightly adjusted the final configuration steps as shown below, which has assisted in bringing down the request count from 10% to 1%. ``` - setWeight: 90 - pause: { duration: 60 } - setWeight: 99 - pause: { duration: 60 } - setWeight: 100 - pause: { duration: 60 } ``` ## Root Cause When we analyse the AWS ALB controller logs, we get to know that an update operation request was received at almost the same time. However, the actual ModifyRule action to change weight was triggered only after about 1 minute and 10 seconds. Ultimately, the problem seems to be that there is a time difference between the lb-controller’s update operation request for weight change and the actual lb-listener rule modification API. We discovered that our use of dynamicStableScale caused older replica sets to scale down before the traffic shift from the load balancer. This created a lag between the canary weight change and the actual traffic switch from the load balancer, leading to problems. Similar to this, one issue is raised [here](https://github.com/kubernetes-sigs/aws-load-balancer-controller/issues/3588) . To address this, we disabled dynamicStableScale and increased the scaleDownDelaySeconds from 30 seconds (default) to 60 seconds, which will wait for 60 seconds before scaling down the older replicaset pods. ``` spec: strategy: canary: dynamicStableScale: false scaleDownDelaySeconds: 60 ``` This solved the 502 errors entirely, but it came with a trade-off. Although we resolved the issue, we lost the benefit of downsizing the older ReplicaSets during deployment, resulting in doubled CPU, memory, and pod usage temporarily. ## Conclusion Whenever we think of using AWS ALB as traffic routing with Argo Rollout as a deployment strategy, we explicitly need to configure multiple things, which makes it difficult to set up the rollout specs as configurations can vary from application to application. As the limitation of the AWS ALB controller with the Argo Rollout dynamicStableScale while making it true. We lost the advantage of downscaling the pods during the deployment, which then led to doubling the infrastructure, which became the same as the blue and green deployment strategies. As one of the main purposes of using the canary strategy was to not double the infra from a resource and cost perspective, it got lost. --- # Header-Based Traffic Routing with Argo Rollouts By Mufaddal Shakir · 2024-05-27 Canonical: https://www.infraspec.dev/blog/header-based-traffic-routing-using-argo-rollouts This blog explores how to use Argo Rollouts for deploying software updates smoothly. It covers the challenges faced when rolling back updates and introduces header-based routing to manage traffic during deployments. ## Scenario Following the deployment of one of our client-critical services, we saw an application bug after we rolled out a service to 100% of users, so the only option left for us is to quickly rollback to the older version. But that also took some time, as the rollback process was not fast in the older setup. ### Why was the rollback the only option we had? Our new feature led to an incident, and unfortunately, disabling it wasn’t feasible. Without feature flags in place, executing a full rollback was the sole method available to us for recovery. ### Why is the rollback process very slow? To comprehend this, let’s delve into the current setup of our organizational services. Essentially, all our client services are hosted in Kubernetes (K8s) via AWS EKS. The Kubernetes manifests are managed within our organization, with one such repository residing on GitHub, which is then synchronized with ArgoCD. In terms of deployment strategy, we’ve embraced Argo-Rollout Canary as it empowers us with automated progressive delivery. ![Current Deployment Setup](https://www.infraspec.dev/images/blog/header-Based-traffic-routing-using-argo-rollouts/deployment-workflow.png) Still, you didn’t get the answer to the question, correct? Hold on! Argo Rollout has the quick feature of rollback from their dashboard, but here is the limitation. Argo Rollout while doing rollback, it doesn’t update the k8s manifest stored in the Github repo, which is synced with ArgoCD. As a result, ArgoCD goes into OutOfSync and again updates the container image from the older version to the current version. So then, how did we do the rollback? It was the same as the new deployment, just with older code. We reverted the PR of the feature being added again and ran the deployment pipeline, which was setup in Jenkins, which then went through testing, building an image, pushing it to ECR, and then deploying by updating the container image, which then updated the K8S manifests stored in the Github repo, which were then synced by the ArgoCD. Hence, the rollback procedure was just a new deployment, although with the previous codebase. ## What were the action items? We acknowledged that responsibility for the incident wasn’t solely on the Dev & QA teams for missing the bug during testing and not having the feature flag. The SRE team was also called out for the slow or lack of rollback process. Additionally, there was a demand for enhancing the deployment process to verify critical features, especially those likely to behave differently in production, either before any traffic hits or on a minimal percentage of real traffic, perhaps around 1%. ### Proposed Solutions - Improving Rollback Process: We updated our Jenkins pipeline to include a new step called “Promotion.” This addition allows the pipeline to pause for a maximum of 30 minutes, awaiting a decision on the success of the deployment. Depending on this decision, an automated rollback operation is initiated, reverting to the previous container image by updating the Kubernetes manifest stored in our GitHub repository, subsequently synced by ArgoCD. - Exploring Routing Techniques: In addressing the need for enhanced routing during deployment, we investigated options and found that Argo Rollout supports header-based routing for the alb controller, although in its alpha stage. We’re considering testing this feature to see if it meets our requirements. ## Argo Rollout header-based routing ### How does the Argo Rollout work? ![Argo Rollout Pre Deployment](https://www.infraspec.dev/images/blog/header-Based-traffic-routing-using-argo-rollouts/argo-rollout-1.png) Argo Rollout manages two services: the active service and the canary service, if utilizing the canary strategy. These services are represented as target groups on the AWS ALB console. The active service typically starts with a 100% weight, while the canary service begins with a 0% weight. During each deployment, the weight distribution between the active and canary services changes. Think of them as different phases of deployment, similar to a “blue” or “green” deployment approach. However, the canary deployment offers a progressive strategy, allowing for gradual traffic shifting through defined steps outlined in the rollout manifest. These steps may include various analysis checks, pauses, or adjustments in traffic distribution, ensuring a smooth deployment process while minimizing disruptions. ### How does the Argo Rollout deployment flow work? ![Argo Rollout During Deployment](https://www.infraspec.dev/images/blog/header-Based-traffic-routing-using-argo-rollouts/argo-rollout-2.png) - Initial State: The active service is initially responsible for serving all incoming traffic. - Start of New Deployment: When a new deployment begins, traffic gradually starts shifting to another service known as the Canary service. The Canary service directs traffic to the pods of the new deployment. - Progressive Traffic Shifting: Over time, as the deployment progresses, more and more traffic is directed to the Canary service. This shift continues until the entirety of the traffic is directed to the Canary service. - Completion of Deployment: Once all traffic has been shifted to the Canary service, it becomes the active service. At this point, the previous active service becomes the Canary service, ready for future deployments. ### How does Argo Rollout header-based routing work then? #### Routing Traffic with Specific Headers 1. With header-based routing, all traffic containing a specific header key and value is directed to the Canary service. 1. Previously, this Canary service wasn’t serving traffic, but now it ensures that requests during deployment hit the new pods, and responses are received from them. #### Managing Canary Steps 1. Within the canary steps, we have the option to specify the duration of pauses between stages to validate the deployment. 1. This allows for careful monitoring and testing of the new deployment before fully transitioning traffic to it. ### On implementing header-based routing, how will things look? Suppose below are the canary steps if we were using: ``` steps: - setCanaryScale: weight: 10 - setHeaderRoute: match: - headerName: version headerValue: exact: "2" name: canary-header-route-new - pause: duration: 60s - setWeight: 1 - pause: {} - setCanaryScale: matchTrafficWeight: true - pause: duration: 20 - setWeight: 80 - pause: duration: 20 ``` setCanaryScale : It will tell us how much of a percentage of new pods to scale up. setHeaderRoute : It will set the key-value pair to header, which will then create a new alb listener that will always point to canary-service. pause : It will give a finite or indefinite pause to your deployment process so that it will take some time on each percentage of traffic shift to verify the new pods, metrics, and monitoring that we have set up. In case of indefinite pause, we manually need to do promotion (Argo Rollout has this feature to promote). setWeight : It will tell us how much percentage of traffic is to be shifted to new pods. matchTrafficWeight : By marking it true, it will tell the Argo Rollout to scale up the pods based on the traffic shift. The default value is true. ### Let’s look in detail at how we can visualize this configuration ![Argo Rollout 10% Canary Pods](https://www.infraspec.dev/images/blog/header-Based-traffic-routing-using-argo-rollouts/argo-rollout-after-10percent-pod-up.png) ![Argo Rollout 1% Traffic](https://www.infraspec.dev/images/blog/header-Based-traffic-routing-using-argo-rollouts/argo-rollout-after-1percent-traffic.png) - Step 1: We will scale the 10% of pods in the total replica pods; consider that the total replica pods are 10; then, 1 new pod will be up after the 1st step. - Step 2: It will create a new listener in AWS ALB with the same host and path but an additional header with lower priority, so that requests with a specific header should go to new pods instead of older pods by the existing listener. - Step 3: Deployment will be paused for 60 seconds so that you can perform testing by hitting the same endpoint with the header, whether the requests are going to newer pods or not. - Step 4: Here we will be shifting 1% of production traffic to newer pods, which will come from the existing listener, but now you have some percentage of traffic on newer pods, and hence you can perform more comprehensive testing by using the same technique of header-based testing to hit new pods. - Step 5: This step will put your deployment into an indefinite pause such that until you perform the Promote manually, deployment will not move. This type of step is really helpful when you need to run some long tests to get the critical features tested. Similarly, it will perform all the steps, and after the complete deployment, or in the case of abortion, it will delete the additional listener added by the Argo Rollout. Great! We achieved the solution to our problem, right? Yes, but it is not working! ## Why won’t header-based routing work? So, as I said earlier, also, our K8s manifest files are synced from the Github repo. Due to header-based routing, it will add some additional paths to ingress that will point to specific services (which will serve the traffic in the next deployment). And again, we faced an OutOfSync Error. Let’s see how the ingress will look after Step 2 (considering the same rollout steps configuration as shown above). If there is ArgoCD, auto-sync is off. ![Argo Rollout Header Based Ingress](https://www.infraspec.dev/images/blog/header-Based-traffic-routing-using-argo-rollouts/header-based-ingress.png) ``` spec: ingressClassName: alb rules: - host: qa-domain.com http: paths: - backend: service: name: canary-header-route-new port: name: use-annotation path: /* pathType: ImplementationSpecific - backend: service: name: service-rollout-active port: name: use-annotation path: /* pathType: ImplementationSpecific ``` Consider that we have one path in ingress that will point to our service, Canary/Active, based on which is holding traffic. When we enable header-based routing, it will add one more path with the same configuration; the only difference is the service name, which is equal to the name we gave when defining the canary step. If you remember the below step, ``` - setHeaderRoute: match: - headerName: version headerValue: exact: "2" name: canary-header-route-new ``` So, you might be wondering where this traffic between the services is specified and which service to point to currently. This is done by the annotation, which is then understood by the alb controller. Let’s look into the action annotation, which tells us which service is holding the traffic. ``` alb.ingress.kubernetes.io/actions.service-rollout-active: >- {"Type":"forward","ForwardConfig":{"TargetGroups":[{"ServiceName":"service-rollout-canary","ServicePort":"80","Weight":0}, {"ServiceName":"service-rollout-root","ServicePort":"80","Weight":100}]}} ``` Here we can compare that when we give the service name while defining the path in ingress as service-rollout-active. It means that the service name matches the annotation and accordingly sends traffic to particular services with a percentage. Now, when we enable header-based routing, it will add one more annotation as follows: ``` alb.ingress.kubernetes.io/actions.canary-header-route-new: >- {"Type":"forward","ForwardConfig":{"TargetGroups":[{"ServiceName":"service-rollout-canary","ServicePort":"80","Weight":100}]}} ``` So, as we can see, the active one is Root, which is currently holding 100% of traffic, and in the next iteration, it will be shifted to Canary, which is then pointed by the header route also. Hence, All this configs are added by rollout on the fly, which then Auto Synced by ArgoCD and remove this configs ## Solution To address this gap and enable the use of header-based routing, we devised a workaround. The solution involved instructing ArgoCD to ignore specific changes made by Argo Rollout to the Ingress resources. By doing so, we could ensure that the desired configuration for header-based routing was maintained, even though these changes were not reflected in the GitHub repository. We made modifications to the apps.yaml file in our ArgoCD configuration to instruct it to ignore the specific changes related to the Ingress resources. Here’s a snippet of the relevant configuration: ``` ignoreDifferences: - group: networking.k8s.io kind: Ingress jqPathExpressions: - >- .spec.rules[]?.http.paths[]?|select (.backend. service.name=="canary-header-route-new") ``` This configuration specifies that ArgoCD should ignore any changes made to Ingress resources where the backend service points to “canary-header-route-new.” By applying this workaround, we were able to maintain the integrity of our header-based routing configuration despite the OutOfSync issue. ## Conclusion By integrating header-based routing with Argo Rollout and ArgoCD, we’ve effectively safeguarded our production environment against potential bugs. This newfound capability has brought immense satisfaction to our organizational teams, particularly in enabling thorough testing of critical features before full rollout. The fear of introducing bugs into production has been significantly reduced, instilling confidence in our deployment process. Moreover, the enhanced control over deployments has streamlined our workflow, resulting in a higher frequency of deployments compared to before. However, it’s important to acknowledge that the solutions we’ve implemented are temporary workarounds. We anticipate that future versions of Argo Rollout will address these compatibility issues with ArgoCD, providing a more seamless and integrated deployment experience. We look forward to leveraging these improvements to further optimize our deployment processes in the future. --- # RBAC in Kubernetes By Sudeep Kulkarni · 2024-04-29 Canonical: https://www.infraspec.dev/blog/kubernetes-rbac Role-Based Access Control (RBAC) is a crucial feature in Kubernetes that allows administrators to define and manage permissions for users and services within the cluster. RBAC helps prevent unauthorised access and actions, ensuring the security of your Kubernetes environment. In this blog, we’ll explore how RBAC works in Kubernetes, its components, and best practices. Why Use RBAC? 1. Security : RBAC helps enforce the principle of least privilege, ensuring that users and components have only the permissions necessary for their tasks. 1. Granular Control: RBAC allows for fine-grained control over permissions, enabling administrators to define specific roles with specific sets of permissions. 1. Scalability: As Kubernetes clusters grow, managing access control becomes more complex. RBAC provides a scalable solution for managing permissions across large clusters. Understanding RBAC in Kubernetes RBAC in Kubernetes follows a simple principle: Users, Roles, and RoleBindings. Let’s break down these components. - Users: Represents individuals or entities that interact with the Kubernetes cluster. - Roles: Defines a set of permissions that can be assigned to users which define what actions an entity can perform on resources - RoleBindings: Associates users with roles, granting them the specified permissions allowing those entities to perform the actions defined by the role on resources within the namespace. Let us understand RBAC with an example , Imagine you have a Kubernetes cluster with two namespaces: development and production. You want to restrict access so that users in the development namespace can deploy pods and delete pods, while users in the production namespace should not be able to delete pods. Let’s implement this using RBAC in Kubernetes First, we define two roles: deployer for the development namespace and operator for the production namespace. ``` # deployer-role.yaml apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: namespace: development name: deployer rules: - apiGroups: [""] resources: ["pods"] verbs: ["create", "get", "list", "watch", "delete"] # operator-role.yaml apiVersion: rbac.authorization.k8s.io/vI kind: Role metadata: namespace: production name: operator rules: - apiGroups: [""] resources: ["pods"] verbs: ["create", "get", "list", "watch"] ``` Next, we create RoleBindings to associate these roles with users , ``` # deployer-binding.yaml apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: deployer-binding namespace: development subjects: - kind: User name: sudeep roleRef: kind: Role name: deployer apiGroup: rbac.authorization.k8s.io # operator-binding.yaml apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: operator-binding namespace: production subjects: - kind: User name: nimisha roleRef: kind: Role name: operator apiGroup: rbac.authorization.k8s.io ``` Best Practices for Role-Based Access Control in Kubernetes 1. Least Privilege Principle - Assign minimal RBAC rights to users and service accounts, granting only permissions required for their operation. - Use RoleBindings instead of ClusterRoleBindings to give users rights only within a specific namespace. 1. Avoid Wildcard Permissions - Avoid providing wildcard permissions, especially to all resources, as this gives rights not just to current object types but also to future object types. 1. Limit Privileged Accounts - Kubernetes Administrators should avoid using cluster-admin accounts unless specifically needed. - Consider providing a low-privileged account with impersonation rights to avoid accidental modifications of cluster resources. 1. Privilege Escalation Risks - Be aware of privileges that can allow users or service accounts to escalate their privileges or affect systems outside the cluster. - For example, granting access to create workloads in a namespace implicitly also grants access to many other resources in that namespace, such as Secrets, ConfigMaps, and PersistentVolumes. 1. Denial of Service Risks - Users with rights to create objects in a cluster may be able to create sufficient large objects to create a denial of service condition. Consider using resource quotas to limit the quantity of objects that can be created , ``` apiVersion: v1 kind: ResourceQuota metadata:   name: pod-quota spec:   hard:     pods: "10" ``` Tip: Use Kubernetes native-tools like kubectl auth can-i to simulate permissions before applying changes How to evaluate your Security Strategy? The simplest way to evaluate your implementation is by asking questions Ask Yourself , 1. Have you defined the roles with the right level of granularity , ensuring that users have the minimum permissions required for their tasks? 1. Have you integrated RBAC with other security mechanisms such as network policies and pod security policies? 1. Do you regularly audit your RBAC configuration to ensure it aligns with your organization’s security policies? In Conclusion , RBAC in Kubernetes is a powerful tool for securing your cluster by controlling access to resources. By following best practices and using RBAC effectively, you can ensure that your Kubernetes environment is secure and your operations are streamlined. --- # Winston Logger Guide for Node.js By Shivani Banke · 2024-04-29 Canonical: https://www.infraspec.dev/blog/guide-to-implement-winston-logger “The only thing more satisfying than fixing a bug is reading the frustrated log messages that led you there.” This humorous yet insightful quote perfectly encapsulates the importance of logging in software development. In any project, large or small, understanding what’s happening under the hood is paramount. ![“The only thing more satisfying than fixing a bug is reading the frustrated log messages that led you there.” This humorous yet insightful quote perfe](https://www.infraspec.dev/images/blog/guide-to-implement-winston-logger/logs-meme.jpeg) Logging is used to track errors, exceptions, warnings, and other events that may occur during the execution of an application. It is crucial for understanding the behavior of an application and for troubleshooting issues that may arise during its operation. It is an important tool for developers, system administrators, and other IT professionals who need to monitor the performance and behavior of complex systems. ## Logging Practices for Application Development: Here’s a list of events that your application should log: 1. Service Executions: Keep track of the execution of various services within your application, including authentication, authorization, system access, data retrieval, and application usage. 1. Resource Utilization: Log instances of exhausted resources, exceeded capacities, and connectivity issues to ensure efficient resource management. 1. Availability Monitoring : Include log statements to monitor the runtime and availability of your application, capturing faults, exceptions, and system stability. 1. Security Threats : Record any security-related issues, such as invalid API keys, failed authentication attempts, and security verification failures, to mitigate potential threats. ## Logging Libraries in Node.js Node.js offers various logging options beyond the default console module, allowing developers to structure, configure, and customize their logs efficiently. While console.log and console.error serve basic logging needs, they lack advanced features such as log structuring and customizable log levels. Fortunately, the Node ecosystem provides several logging libraries tailored to address these limitations. Let’s explore some popular options: 1. [Winston](https://github.com/winstonjs/winston) : A versatile logging library with support for multiple transports and customizable log formats. 1. [Bunyan](https://github.com/trentm/node-bunyan) : A high-performance logging library with structured logging capabilities. 1. [Pino](https://github.com/pinojs/pino) : A lightweight and fast logging library optimized for performance. - [Log4js](https://github[.](https://github.com/pinojs/pino)com/log4js-node/log4js-node) : A feature-rich logging library inspired by Apache Log4j, offering various configuration options . 1. [Debug](https://github.com/visionmedia/debug) : A tiny debugging utility for Node.js applications. This post will delve into the process of configuring and utilizing the Winston library for logging messages. ## What is Winston Logger? Winston Logger is a versatile logging library for Node.js applications, offering extensive flexibility and customization options compared to the built-in console module. Whether you’re debugging code during development,or logging critical events in production, Winston provides the necessary tools and integrations to meet your logging needs effectively. It supports logging to the console, files, databases, and third-party services like [Loggly or Papertrail](https://betterstack.com/logs?utm_medium=c&utm_campaign=adwords19703922957&utm_source=adwords&utm_content=648793502849&utm_term=papertrail&gad_source=1&gclid=CjwKCAjwoa2xBhACEiwA1sb1BG9qUjgD2jGosVMhYytL76lWcnaL38LiXWlSxH3z5Hk6FG7YjShL1BoCeU0QAvD_BwE) , making it a popular choice for logging in Node.js projects. ## Installation and Setup To get started with Winston Logger, you can install it via npm using the following command: ``` $ npm install winston ``` ## Configuration Options Winston Logger offers a wide range of configuration options to customize its behavior. You can set the log level, specify transports, define custom log formats, and more. ### What are logging levels in Winston Logger? In Winston Logger, logging levels are used to categorize log messages based on their severity or importance. Winston defines several standard logging levels, each corresponding to a specific numeric value and representing different degrees of urgency.For example, ``` levels: { error: 0, warn: 1, info: 2, http: 3, verbose: 4, debug: 5, silly: 6 } ``` ### What are Transports in Winston Logger? In Winston Logger , Transports allow developers to specify how and where log messages should be logged, such as to the console, files, databases, http or third-party services. For example, ``` transports: [ new winston.transports.Console(), new winston.transports.File({ filename: 'logfile.log' }) } ``` Here are some popularly used custom transport to check out: - [winston-daily-rotate-file](https://github.com/winstonjs/winston-daily-rotate-file) - [winston-syslog](https://www.npmjs.com/package/winston-syslog) - [winston-cloudwatch](https://www.npmjs.com/package/winston-cloudwatch) - [winston-mongodb](https://www.npmjs.com/package/winston-mongodb) - [winston-elasticsearch](https://www.npmjs.com/package/winston-elasticsearch) ### What are formats in Winston Logger? In Winston Logger , Formats allow developers to customize how log messages are formatted before being outputted by the logger. Formats can include timestamp, log level, message, metadata, and any custom formats to tailor the appearance of log messages to their specific requirements. For example, ``` const customFormat = winston.format.printf(({ level, message, timestamp }) => { return `${timestamp} [${level}]: ${message}`; }); ``` Here’s an example of configuring Winston : ``` const winston = require('winston'); const customLevels = { levels: { error: 0, warn: 1, info: 2, debug: 3 }, colors: { error: 'red', warn: 'yellow', info: 'green', debug: 'blue' } }; const customFormat = winston.format.printf(({ level, message, timestamp }) => { return `${timestamp} [${level}]: ${message}`; }); winston.addColors(customLevels.colors); const logger = winston.createLogger({ level: 'info', // Default log level levels: customLevels.levels, format: winston.format.combine( winston.format.timestamp(), customFormat ), transports: [ new winston.transports.Console(), new winston.transports.File({ filename: 'logfile.log' }) ] }); module.exports = logger; ``` > 📝 Note : With the default log level set to ‘info’, messages with a severity level of ‘info’ or higher (e.g., ‘warn’, ’error’) will be logged. Messages with a lower severity level (e.g., ‘debug’) will not be logged by default. ### Logging Middleware for Express.js If you’re using Express.js for your Node.js application, you can integrate Winston Logger with middleware to log HTTP requests and responses. Here’s how you can configure Winston middleware: ``` const expressWinston = require('express-winston'); app.use(expressWinston.logger({ transports: [ new winston.transports.Console(), new winston.transports.File({ filename: 'requests.log' }) ] })); ``` ### Usage of Winston Logger in a Sample Blog Posting Application: ``` const logger = require('./logger'); function createPost(userId, title, content) { logger.info(`User ${userId} created a new post: ${title}`); } function updatePost(userId, postId, updatedContent) { logger.info(`User ${userId} updated post ${postId}`); } function deletePost(userId, postId) { logger.warn(`User ${userId} deleted post ${postId}`); } function publishPost(userId, postId) { if (!postId) { logger.error(`User ${userId} attempted to publish a post without specifying a post ID`); return; } logger.info(`User ${userId} published post ${postId}`); } ``` ## Rotating Files in Winston: In Winston Logger, rotating files refer to a mechanism where log files are automatically rotated or split into multiple files based on certain criteria such as file size, time intervals, or a combination of both. This ensures that log files do not grow indefinitely and consume excessive disk space, while also facilitating log management and analysis. > 📝Note: For more advanced options and detailed configuration settings for log rotation, you can refer to the official documentation of the [winston-daily-rotate-file](https://www.npmjs.com/package/winston-daily-rotate-file) package. Here is an example for retaining logs for 14 days before being deleted: ``` const winston = require('winston'); const DailyRotateFile = require('winston-daily-rotate-file'); const dailyRotateTransport = new DailyRotateFile({ filename: 'app-%DATE%.log', datePattern: 'YYYY-MM-DD', zippedArchive: true, maxFiles: '14d' }); const logger = winston.createLogger({ level: 'info', format: winston.format.combine( format.timestamp(), format.printf(({ timestamp, level, message }) => { return `${timestamp} [${level.toUpperCase()}]: ${message}`; }) ), transports: [ dailyRotateTransport, new winston.transports.Console() ] }); module.exports = logger; ``` > 📝Note: Handling Zipped Log Files in Winston Logger When using the winston-daily-rotate-file package with zipped log archives, it’s important to note that the package doesn’t automatically handle unzipping of log files before deletion. As a result, zipped log files may remain in the directory even after they are no longer needed. ## How implementing logging system using Winston transformed our node.js application When our Discord application faced issues with requests failing, it often led to our application crashing. it was executed using PM2 (process manager)with the restart option enabled, we encountered a challenge. Whenever the application failed and restarted, the logs would vanish instantly, leaving us clueless about the cause. To address this, we implemented logging using Winston. We configured it to log to both the console and a file for persistent storage, utilizing file rotation with filenames containing the date for quick access. Additionally, we set up the system to delete files after a certain period using daily rotate files, preserving memory usage . ## Here are some best practices for logging in Node.js : 1. Use Log Levels : Utilize different log levels to categorize log messages based on their severity. Common levels include error , warn , info , and debug . 1. Include Contextual Information : Provide timestamps and additional context in log messages to aid in debugging and troubleshooting. ``` const winston = require('winston'); const customFormat = winston.format.printf(({ level, message, timestamp }) => { return `${timestamp} [${level}]: ${message}`; }); const logger = winston.createLogger({ level: 'info', format: customFormat, transports: [ new winston.transports.Console(), ] }); ``` 1. Centralized Logging Configuration : Configure logging settings in a centralized location for consistency across the application. ``` const logger = require('winston'); logger.configure({ level: 'info', format: winston.format.json(), transports: [ new winston.transports.Console(), new winston.transports.File({ filename: 'app.log' }) ] }); ``` 1. Do not log sensitive information: it’s crucial to ensure that sensitive and confidential user information is never included in your log entries, especially in production environments. Not only does this protect users from potential malicious attacks, but it also helps your application comply with data privacy laws and regulations. Sensitive information encompasses personally identifiable data (PII), health records, financial details, passwords, IP addresses, and similar data. > Note: Have a look at the article dedicated to [structured logging](https://reflectoring.io/structured-logging/) if you want to dive deeper. ## Conclusion In this step-by-step guide, we’ve explored the implementation of Winston Logger in Node.js projects, enabling us to build robust and reliable applications. With best practices like utilizing log levels, including contextual information, and centralizing logging configuration, we’ve paved the way for more reliable and usable Node.js applications. Let’s embark on our logging journey to enhance our projects further!! --- # Getting Started with GitHub Runners By Rahul Patil · 2024-04-25 Canonical: https://www.infraspec.dev/blog/github-runners ## Introduction In today’s fast-paced world of software development, automation is key to staying competitive. GitHub, a leading platform for collaboration and version control, offers an extensive set of tools to automate Continuous Integration and Continuous Deployment (CI/CD) pipelines. At the heart of this automation are GitHub Runners, which execute CI/CD tasks to streamline the development process. Let’s dive into the world of GitHub Runners and explore how they can enhance your projects. ## GitHub Runners: Your DevOps Assistants GitHub Runners handle repetitive, time-consuming tasks, allowing you to focus on creating innovative software. By automating test runs, builds, and deployments, they streamline your workflow and boost productivity. These runners work seamlessly in the background to keep your projects on track and ensure smooth operations. ## GitHub-hosted Runners Think of GitHub-hosted runners as the all-inclusive resorts of the CI/CD world. These virtual environments are provided by GitHub, pre-loaded with everything you need. Need a Linux machine to build your app? They’ve got it. How about a Windows environment for your .NET project? Check. With GitHub-hosted runners, you can hit the ground running without worrying about setting up infrastructure. No setup required! Simply define your workflows in .github/workflows , and GitHub will take care of the rest. It’s as easy as writing a recipe and letting GitHub do the cooking. ## Self-hosted Runners If you prefer to take control of your setup and fine-tune your execution environment, self-hosted runners are a great option. These are machines you manage within your own infrastructure, giving you full control. They are perfect for projects with specific requirements or security constraints. Self-hosted runners can connect directly with your internal network, enabling access to applications and services hosted within your office environment or on-premises servers. This direct interaction allows your workflows to access databases, APIs, and other internal resources securely, reducing reliance on external connections and ensuring your CI/CD processes have controlled, secure access to the resources they need for successful workflows. ### Setting Up self-hosted Runners To set up self-hosted runners, follow these steps: - Create a Folder ``` $ mkdir actions-runner && cd actions-runner ``` - Download the Latest Runner Package: Visit the [GitHub Actions runner releases page](https://github.com/actions/runner/releases) . Download the appropriate runner package for your operating system (Linux, Windows, or macOS) and architecture (x64 or ARM). Save the package to the actions-runner folder. - Extract the Installer: For Linux and macOS For Windows ``` $ tar xzf actions-runner-{os}-{arch}-{version}.tar.gz ``` ``` $ tar -xzf actions-runner-{os}-{arch}-{version}.tar.gz ``` - Configure the Runner Run the configuration script for the runner, specifying your GitHub repository URL and the registration token provided by GitHub. Replace {username} and {repo} with your GitHub username and repository name, and replace {token} with your registration token. ``` $ ./config.sh --url https://github.com/{username}/{repo} --token {token} ``` - Run the Runner: For Linux and macOS For Windows ``` $ ./run.sh ``` ``` $ run.cmd ``` By following these steps and using the appropriate commands for your operating system, you can set up your self-hosted runner and use it in your GitHub Actions workflows. ## Setting Up GitHub Runners in CI/CD Workflow Using GitHub-hosted runners requires no setup on your part. All you need to do is define your workflows in your .github/workflows directory, and GitHub will handle the execution of your workflows using hosted runners. ## Example YAML File Here is an example YAML file demonstrating how to use both GitHub-hosted and self-hosted runners in a CI/CD workflow: ``` name: CI/CD Workflow on: push: branches: - main jobs: # Job using GitHub-hosted runners build_and_test: # Specify GitHub-hosted runner (in this case, Ubuntu) runs-on: ubuntu-latest steps: # Checkout the repository code - name: Checkout code uses: actions/checkout@v2 # Install dependencies (example using npm, customize as needed) - name: Install dependencies run: npm install # Run tests (customize this step for your testing needs) - name: Run tests run: npm test # Build the project (customize as needed) - name: Build project run: npm run build # Job using self-hosted runners deploy: # Specify the job runs on a self-hosted runner runs-on: self-hosted # Specify the job will run after the previous job needs: build_and_test steps: # Checkout the repository code - name: Checkout code uses: actions/checkout@v2 # Deploy the application (customize this step for your deployment method) - name: Deploy application run: | echo "Deploying application..." # Add your deployment commands here # Verify the deployment - name: Verify deployment run: | echo "Verifying deployment..." # Add your verification commands here ``` ### Overview of the YAML File - The file is set up to trigger on pushes to the main branch. - The build_and_test job uses GitHub-hosted runners ( ubuntu-latest ) to check out the code, install dependencies, run tests, and build the project. - The deploy job uses self-hosted runners ( self-hosted ) and specifies a dependency on the build_and_test job. - In the deploy job, the workflow checks out the code and deploys the application using a custom deployment method, which you can tailor to your specific needs. ## Customizing GitHub Notifications for CI/CD Workflow Status Updates GitHub automatically sends notifications about CI/CD workflow status updates to the individuals who triggered the workflow. However, GitHub offers the flexibility to customize notification settings at the repository level. ## How to Customize Notifications - Access Notification Settings : Go to the settings of your GitHub repository and navigate to the “Notifications” section. This is where you can control how you receive updates about your repository. - Choose Notification Preferences : Specify the types of events you want to be notified about, such as all workflow runs, specific events like failures, or only certain workflows. Customize your preferences to receive only the notifications you care about. - Specify Recipients : Customize who receives notifications by specifying email addresses or choosing to receive notifications via GitHub itself. You can adjust these settings for individuals or teams, making it easy to keep the right people informed about your workflow status. ## Conclusion GitHub Runners are the backbone of modern CI/CD pipelines, enabling developers to automate their workflows with ease and efficiency. Whether you opt for GitHub-hosted runners for convenience or self-hosted runners for control, GitHub provides the tools and infrastructure to support your automation needs. By embracing GitHub Runners, you can unlock new levels of productivity and innovation, allowing your projects to reach their full potential. So, don’t wait any longer! Dive into the world of GitHub Runners and elevate your CI/CD workflow today! --- # Docker: Simplify, Scale & Secure By Sudeep Kulkarni · 2024-04-24 Canonical: https://www.infraspec.dev/blog/docker-deep-dive This blog will cover the foundational concepts of Docker layers, caching mechanisms, and Dockerfile optimization. Additionally, provide insights on minimizing image sizes, adhering to security protocols, and understanding Docker’s licensing requirements. ### Understanding Docker Image Layers Docker images are constructed from a series of layers; each layer corresponds to instructions in the Dockerfile that modify the filesystem of the image. These layers are stacked on top of each other, forming the final image. Understanding how these layers work is key to optimizing your Docker builds. ![Docker Layers](https://www.infraspec.dev/images/blog/docker-deep-dive/docker_layers.png) Leveraging Docker’s Caching Mechanism for Efficient Builds During the build process, Docker looks at each instruction in the Dockerfile and checks if an intermediate layer for that instruction already exists in its cache. If it does, and if nothing has changed that would affect that layer, Docker will reuse the cached layer instead of recreating it. This reuse of layers speeds up the build process significantly and makes it more efficient in terms of resource use. ![Invalidated Docker Layers](https://www.infraspec.dev/images/blog/docker-deep-dive/docker_layers_invalidated.png) For example, if your Dockerfile starts with a RUN instruction to install dependencies, and these dependencies haven’t changed, Docker will use the cached layer from a previous build for this instruction. This avoids the need to re-download and install dependencies every time you build the image, as long as the corresponding instruction in the Dockerfile remains unchanged. ### Best Practices for Dockerfile Structure To make the most of Docker’s caching mechanism, it’s important to organize your Dockerfile instructions thoughtfully. Instructions that are less likely to change should be placed near the top of the Dockerfile. This allows Docker to cache these layers early in the build process, and they can be reused in subsequent builds as long as they remain unchanged. For instance, system packages and application dependencies don’t change often once they’re set. By placing these instructions (like RUN apt-get install -y some-package or RUN npm install ) near the top of your Dockerfile, you ensure that Docker can cache them effectively. Subsequent instructions, which might change more frequently (like COPY . /app ), are placed lower in the Dockerfile. This strategy minimizes the number of layers that need to be rebuilt in each build, saving time and computational resources. Let us look at an example of Non Optimised Docker Build Vs an Optimised Docker Build Non Optimised Docker Build In this Dockerfile, we demonstrate a non-optimised Docker build where we directly copy all files at once using COPY . . , causing unnecessary rebuilds of layers even when minor changes occur. ``` FROM node WORKDIR /app COPY . . RUN npm install RUN npm build ``` Optimised Docker Build In this Dockerfile, we show the optimized approach where we first copy just the package.json yarn.lock file which might not change more frequently (like COPY . /app ), and then execute RUN npm install , followed by copying the remaining application files with COPY . . , significantly improving build efficiency by leveraging Docker’s caching mechanism. ``` FROM node WORKDIR /app COPY package.json yarn.lock . RUN npm install COPY . . RUN npm build ``` Incorporating these principles into your Dockerfile can drastically improve your build times and resource usage, making your development process more efficient. This strategic placement of instructions, combined with Docker’s robust caching mechanism, is essential for optimising Docker environments in production. ### How to keep your docker images small? 1. Start with an appropriate base image. For instance, if you need a JDK, consider basing your image on a Docker Official Image which includes OpenJDK rather than building your own image from scratch. 1. If you have multiple images with a lot in common, consider creating your own base image with the shared components, and basing your unique images on that. Docker only needs to load the common layers once, and they are cached. This means that your derivative images use memory on the Docker host more efficiently and load more quickly. Let us look at an example below Creating a Base File ``` # Base Dockerfile FROM node:14 WORKDIR /app RUN npm install express \ && npm install axios \ && npm install body-parser CMD ["node", "index.js"] ``` Creating Derivative images from the base image: ``` # Derivative Dockerfile for Services FROM base_image COPY /ServiceA /app/ServiceA CMD ["node", "ServiceA/index.js"] ``` 1. Keeping your layers small is a good first step, and the logical next step is to reduce the number of layers that you have. Fewer layers mean that you have less to rebuild, when something in your Dockerfile changes, so your build will complete faster. ``` # Update the package index ( Creates a new layer ) RUN apt-get -y update # Install Python with its dependencies ( creates a new layer ) RUN apt-get install -y python # Update package index & install python with it's dependencies in a single commange ( Creates a single new layer ) RUN apt-get -y update && RUN apt-get install -y python ``` 1. To keep your production image lean but allow for debugging, consider using the production image as the base image for the debug image. ### Dockerfile Best Practices - Decouple Applications to make sure each container should have only one concern , each handling a single concern, primarily aids in horizontal scalability. For example, if your Docker image contains both the application and the database, scaling the database due to increased load would also necessitate scaling the application instances, even if the application itself isn’t under similar load. This inefficient scaling can lead to unnecessary resource utilization and increased costs. 1. Whenever possible, sort multi-line arguments in the dockerfile alphanumerically to make maintenance easier. 1. Use .dockerignore files in Docker builds to exclude unnecessary files and directories from being included in the image. - Use the SHA256 Digest to reference docker images , this method ensures that you are always pulling the exact version of the image you intend to use, which is useful for maintaining consistency and security in your deployments. To get the SHA256 Digest of the Docker Image you are using , execute this command. ``` docker inspect --format='{{index .RepoDigests 0}}' $IMAGE ``` ``` FROM alpine:3.19 Better Version - Using SHA 256 FROM alpine:3.19@sha256:13b7e62e8bdf80e64dbb745 ``` ### Security Practices for Docker 1. Use Official Docker Images 1. Multi-stage builds minimise complexity and reduce vulnerability risks by allowing selective artifact inclusion, avoiding the inheritance of vulnerabilities from base images. 1. Docker recommends that you rebuild your Docker image regularly to prevent known vulnerabilities that have been addressed. When rebuilding, use the option —no-cache to avoid cache hits and to ensure a fresh download. 1. Secret Management: Avoid hardcoding sensitive information in Dockerfiles or configuration files. Instead, use Docker secrets or environment variables to securely pass secrets to containers. ### Understanding Docker Licensing When incorporating Docker into your business operations, it’s crucial to understand and adhere to Docker’s licensing requirements. Docker offers various types of licenses depending on the scale of use and the features required. These range from free versions suitable for developers and small projects to enterprise editions designed for large-scale commercial deployments. So, talking about the docker license change, the personal subscription has a free plan. The personal subscription is valid for organizations having less than 250 employees. In contrast, the ones with 250+ organizations need to use their paid version. By understanding Docker licensing and ensuring that your usage complies with these legal requirements, you protect your organization against legal risks and optimize your Docker environments with the appropriate tools and support. For more information please refer: [https://www.docker.com/legal/docker-subscription-service-agreement/](https://www.docker.com/legal/docker-subscription-service-agreement/) ### Conclusion To wrap up, getting the hang of Docker is about more than just wrapping your app in a container. It’s about really getting into the nitty-gritty—like setting up Dockerfiles properly, making smart use of Docker’s caching perks, and keeping those images lean and mean. On top of that, keeping things above board with Docker’s licensing rules is key for keeping your operations smooth and compliant. Stick with these strategies, and you’re on your way to making your Docker setups as efficient, secure, and compliant as they can be. --- # Secrets Rotation w/ AWS Secrets Manager - Part 2 By Saumitra Topinkatti · 2024-04-22 Canonical: https://www.infraspec.dev/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2 In [Part 1](/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-1/) , we discussed upon configuring AWS Secrets Manager, AWS Lambda, and Automatic Rotation for our Secret. We also defined permissions for our Lambda function, which enabled the Secrets Manager to invoke it on a scheduled basis. In Part 2, we will focus on setting up the Lambda function, including the required permissions and implementation. ## Allowing our Lambda function to update secrets in the Secret Manager Before diving into implementing our Lambda function, it will require permission to update secrets in the Secrets Manager. This permission can be granted by creating a new policy in IAM and then attaching it to our Lambda function’s role. Let’s start by defining our policy in IAM. ### Using AWS CLI ``` # Create a policy.json (make sure to replace the "REGION" and "YOUR_ACCOUNT_ID" with the appropriate region name, and your Account ID, respectively) echo '{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "secretsmanager:UpdateSecret", "Resource": "arn:aws:secretsmanager:[REGION]:[YOUR_ACCOUNT_ID]:secret:demo/GoogleAuth/AccessToken-*" } ] }' > policy.json ``` ``` # Create the IAM policy aws iam create-policy --policy-name "demo-GoogleAuth-AccessToken-UpdateSecret-policy" --policy-document file://policy.json ``` ### Using AWS Console 1. Visit the [IAM dashboard](https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#/home) in the AWS Console. 1. Under “Access management,” click on “Policies.” 1. Create a new policy. 1. In the “Specify permissions” section, under “Select a service,” choose “Secrets Manager” in the dropdown to see all permissions. 1. In the “Actions allowed” section, under the “Write” Access level, check the “UpdateSecret” box. Also, ensure that the “Effect” is set to “Allow.” ![Let’s start by defining our policy in IAM.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2/external-1.png) ![Let’s start by defining our policy in IAM.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2/external-2.png) ![Let’s start by defining our policy in IAM.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2/external-3.png) - Next, in the “Resources” section, we have the option to either permit access to all resources (meaning all stored Secrets under the Secrets Manager) or limit access to only chosen Secrets. Typically, it’s best to grant access to specific Secrets that are needed, according to the policy. Since we are setting up the policy for our Lambda function to access the “ demo/GoogleAuth/AccessToken ” secret, we will restrict access to only that specific Secret. We can do this by: Visit the Secrets Manager page and view the secret details, Copy the secret’s ARN (Amazon Resource Name, which uniquely identifies resources), and Paste the Secret ARN in the “Specify ARN(s)” window after clicking “Add ARNs”. Click on “Add ARNs” and then click on “Next”. 1. Under “Policy details”, let’s name our policy “ demo-GoogleAuth-AccessToken-UpdateSecret-policy ” since it is closely linked to our “ demo/GoogleAuth/AccessToken ” Secret. ![Let’s start by defining our policy in IAM.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2/external-4.png) 1. Create policy. ## Linking the Policy under our Lambda function’s role in the IAM Now that we have created a policy to allow updating our Secret in the Secrets Manager, let’s proceed to link this policy under the Lambda function’s role. You can find the Lambda function’s role in IAM under Access Management > Roles . ### Using AWS CLI ``` # Attach the IAM policy to the Lambda function's Execution Role (make sure to replace the "YOUR_ACCOUNT_ID" with your Account ID) aws iam attach-role-policy --role-name "lambda_ex" --policy-arn "arn:aws:iam::[YOUR_ACCOUNT_ID]:policy/demo-GoogleAuth-AccessToken-UpdateSecret-policy" ``` ### Using AWS Console ![Now that we have created a policy to allow updating our Secret in the Secrets Manager, let’s proceed to link this policy under the Lambda function’s role.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2/external-5.png) 1. Click on the role name to view the role’s details. - Scroll down to “Permissions policies” and click on Add permissions > Attach policies . This allows us to link our Policy to this role, granting our Lambda function access to the Secret and enabling it to update the Secret’s value. 1. In the “Other permissions policies” section, search for the newly created Policy. 1. Lastly, select the Policy and click on “Add permissions”. ![Now that we have created a policy to allow updating our Secret in the Secrets Manager, let’s proceed to link this policy under the Lambda function’s role.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2/external-6.png) This action will link our Policy to the role, giving access to the Secret and enabling our Lambda function to securely update the Secret’s value. This completes all the essential configuration needed for our Lambda function to securely update the Secret’s value, and we can now move on to implementing the Lambda function. ## Implementing our Lambda function Our Lambda function will use the Google Service Account key and scopes to create an Access Token with a specific validity period. It will then update the value of the Secret in the Secrets Manager. We can input the Service Account key as a Base64-encoded string and the scopes as Environment Variables. Additionally, the Lambda function will need the Secret’s name (in this case, “ demo/GoogleAuth/AccessToken ”). We can choose to read this as an Environment Variable or hard-code it. I recommend reading it as an Environment Variable to avoid tight coupling. Hard coding could complicate future changes, as we would need to find and update all references to the Secret, even within the Lambda function implementations. ![We can input the Service Account key as a Base64-encoded string and the scopes as Environment Variables.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2/external-7.png) The above flowchart outlines a Lambda function’s operation for rotating an access token. The function begins by extracting necessary Environment Variables, initializes Google Auth for access token generation, and then sets up the AWS Secrets Manager client. Once the token is generated, the function prepares and sends an update command to Secrets Manager to update the secret. It concludes by returning a successful response upon the successful updating of the secret in AWS. Okay, enough blabbering, let’s set up the necessary Environment Variables, and get into the implementation part. ### Using AWS CLI ``` # Set the Environment Variables in the Lambda Function aws lambda update-function-configuration --function-name "refreshGoogleAccessTokenSecret" --environment "Variables={GOOGLE_SERVICE_ACCOUNT_KEY_BASE64='* * *',GOOGLE_APIS_SCOPES='https://www.googleapis.com/auth/calendar.events.readonly,https://www.googleapis.com/auth/calendar.readonly',SECRET_ID='demo/GoogleAuth/AccessToken'}" ``` ### Using AWS Console 1. Visit the Lambda function overview page. ![Okay, enough blabbering, let’s set up the necessary Environment Variables, and get into the implementation part.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2/external-8.png) ![Okay, enough blabbering, let’s set up the necessary Environment Variables, and get into the implementation part.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2/external-9.png) - Scroll down to view the template code or the starter code under the “Code” tab. In my case, the handler function represents the core of our Lambda function and acts as the starting point. We can access the Google Service Account key using Environment Variables, specifically through process.env in my scenario. Let’s promptly configure the necessary Environment Variables for our Lambda function. - Under the “Configuration” tab, within the “Environment variables” section, click on “Edit environment variables.” Here, we can input our details - Service Account key as Base64, scopes, and the Secret’s name. Click on Save. Next, let’s proceed with implementing our Lambda function. Within the Function overview page, under the “Code” tab, we can edit the source code and implement the Lambda function. Since our Lambda function utilizes Google APIs to create Access Tokens, it will need the [googleapis](https://www.npmjs.com/package/googleapis) dependency from the NPM repository. Moreover, we will need [@aws-sdk/client-secrets-manager](https://www.npmjs.com/package/@aws-sdk/client-secrets-manager) to update the Secret in the Secrets Manager. We need to include all dependencies in our Lambda function’s source code because we can’t install NPM modules on the go. Another option is to use NPM modules by setting up an EC2 instance (as recommended in this [blog](https://aws.amazon.com/blogs/compute/nodejs-packages-in-lambda/) ). However, the easiest method is to work on the Lambda function’s source code locally. We do this by starting an NPM project, installing the necessary dependencies, packaging the whole project into a ZIP file, and then uploading it. Let’s first initialize an empty Node project. ``` npm init -y ``` Below is the implementation of the google_auth_init.mjs file, which defines the createGoogleAuthFromBase64Credentials function used to create a GoogleAuth instance. ``` // google_auth_init.mjs import { google } from "googleapis"; /** * Initializes a new GoogleAuth from the specified credentials * and scopes. */ export function createGoogleAuthFromBase64Credentials( credentialsInBase64, scopes ) { // Decode the Base64 string using `atob` function const decodedCredentials = atob(credentialsInBase64); const decodedCredentialsInJson = JSON.parse(decodedCredentials); return new google.auth.GoogleAuth({ credentials: decodedCredentialsInJson, scopes, }); } ``` Let’s now implement the aws_secrets_manager_init.mjs file. This file will contain the createAwsSecretsManagerClient function, used to create an instance of SecretsManagerClient. ``` // aws_secrets_manager_init.mjs import { SecretsManagerClient } from "@aws-sdk/client-secrets-manager"; /** * Initializes a new SecretsManagerClient instance */ export function createAwsSecretsManagerClient() { const client = new SecretsManagerClient({ region: "us-east-1" }); return client; } ``` Next, we can: - Use the createGoogleAuthFromBase64Credentials function to create a new GoogleAuth instance, - Generate an access token using the GoogleAuth, - Create a new instance of SecretsManagerClient using the createAwsSecretsManagerClient function, - Update the secrets using the SecretsManagerClient. Let’s proceed with implementing the source code in index.mjs . ``` // index.mjs import { UpdateSecretCommand } from "@aws-sdk/client-secrets-manager"; import { createGoogleAuthFromBase64Credentials } from "./google_auth_init.mjs"; import { createAwsSecretsManagerClient } from "./aws_secrets_manager_init.mjs"; const { GOOGLE_SERVICE_ACCOUNT_KEY_BASE64, GOOGLE_APIS_SCOPES, SECRET_ID } = process.env; // Entry point export const handler = async (event) => { const googleAuthScopes = GOOGLE_APIS_SCOPES.split(","); const googleAuth = createGoogleAuthFromBase64Credentials( GOOGLE_SERVICE_ACCOUNT_KEY_BASE64, googleAuthScopes ); // Generate a new Access Token, and prepare // an object with updated secrets. const accessToken = await googleAuth.getAccessToken(); const updatedSecrets = { GOOGLE_ACCESS_TOKEN: accessToken, }; const secretsManagerClient = createAwsSecretsManagerClient(); // Prepare the update secret command with // secret id (name of the Secret), and // secret string which is the updated secrets // stringified. const updateSecretCommand = new UpdateSecretCommand({ SecretId: SECRET_ID, SecretString: JSON.stringify(updatedSecrets), }); // Commit the changes to Secrets Manager await secretsManagerClient.send(updateSecretCommand); // Return a response with the status code const response = { statusCode: 200, body: "Access Token was rotated", }; return response; }; ``` Also, ensure that you install the dependencies before moving on to the uploading step. ``` npm install googleapis @aws-sdk/client-secrets-manager ``` Now that we have implemented the Lambda function, we can package all the source files, including their dependencies (node_modules), into a ZIP file. Open a terminal in the project’s (or implementation’s) root directory and execute the command to create a ZIP archive from the project files. ``` zip -r code.zip . ``` #### Uploading the ZIP file using AWS CLI ``` # Upload the ZIP file containing the Lambda function implementation aws lambda update-function-code --function-name "refreshGoogleAccessTokenSecret" --zip-file fileb://code.zip ``` #### Uploading the ZIP file using AWS Console ![Open a terminal in the project’s (or implementation’s) root directory and execute the command to create a ZIP archive from the project files.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2/external-10.png) Next, open the Lambda function overview page, and under the “Code” tab, click on Upload from > .zip file . Select the generated ZIP file (in this case, “ code.zip ”), and upload it to update the Lambda function’s source code. ## Testing out the Lambda function After uploading the source code, let’s test our Lambda function to confirm if it successfully rotates the Access Token in the Secrets Manager. ### Using AWS CLI ``` # Invoke the Lambda function and store the result to "output.txt" aws lambda invoke --function-name "refreshGoogleAccessTokenSecret" --payload '{}' output.txt ``` ``` # View the result cat output.txt ``` ### Using AWS Console 1. Visit the Lambda function overview page. 1. Scroll down to locate the “Test” tab. - In the “Test event” section, you can choose to create an event with details like the event name and the event JSON, which are then passed as parameters to the Lambda handler function. This step is optional and can be skipped in this case. Creating and using events can be useful when specific tests need to be defined. 1. Click on Test to trigger the Lambda function. ![After uploading the source code, let’s test our Lambda function to confirm if it successfully rotates the Access Token in the Secrets Manager.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2/external-11.png) If the Lambda function successfully rotates the Access Token, we will observe that the Lambda function execution completes without any errors. By checking the Secret in the Secrets Manager, we can verify that the Secret has indeed been updated. ![By checking the Secret in the Secrets Manager, we can verify that the Secret has indeed been updated.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2/external-12.png) Note: If the execution fails with a Task timed-out error, we can resolve this problem by extending the timeout duration. ![Note: If the execution fails with a Task timed-out error, we can resolve this problem by extending the timeout duration.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2/external-13.png) We can accomplish this by going to the Lambda function overview page, navigating to the “Configuration” tab, and then to “General configuration”. Click on “Edit” and increase the timeout to a longer duration. In my situation, the timeout duration is currently set to 10 seconds. ![We can accomplish this by going to the Lambda function overview page, navigating to the “Configuration” tab, and then to “General configuration”.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2/external-14.png) ## After using AWS Secrets Manager Now that we have set up and configured our Secrets Manager service, we can smoothly integrate the secrets into our application using the AWS SDK. In my case, I will utilize the [aws-sdk](https://www.npmjs.com/package/aws-sdk) NPM package to interact with AWS. To access the Secrets Manager service securely, we must create a SecretsManagerClient. This client allows us to fetch secrets securely. Let’s create the aws_secrets_manager_util.mjs script, which will contain the necessary functions to set up a client and retrieve secrets using it. ``` // aws_secrets_manager_util.mjs import AWS from "aws-sdk"; const { SecretsManager } = AWS; /** * Initializes a new SecretsManager instance */ export function createSecretsManagerClient(region) { const client = new SecretsManager({ region }); return client; } /** * Fetches secrets from a Secret Manager using the client and the secret Id * @returns {Promise<{ GOOGLE_ACCESS_TOKEN: string }>} Secrets */ export async function getSecretsFromSecretsManagerClient(client, secretId) { const secretsResult = await client .getSecretValue({ SecretId: secretId, }) .promise(); const secrets = JSON.parse(secretsResult.SecretString); return secrets; } ``` We can now use the functions exported from my aws_secrets_manager_util.mjs in the start script to effectively utilize the Google Access Token for fetching Calendar events and remove the reliance on Service Account keys in the application. ``` import { config } from "dotenv"; config(); import { createSecretsManagerClient, getSecretsFromSecretsManagerClient, } from "./aws_secrets_manager_util.mjs"; import { createCalendarClient, getEventsByCalendarId, } from "./google_calendar_service.mjs"; /** * AWS_SECRET_MANAGER_REGION -> AWS Secrets Manager Region (us-east-1) * AWS_SECRET_MANAGER_SECRET_ID -> AWS Secrets Manager Secret Id * (demo/GoogleAuth/AccessToken) */ const { AWS_SECRET_MANAGER_REGION, AWS_SECRET_MANAGER_SECRET_ID, GOOGLE_CALENDAR_ID, } = process.env; // Fetch Google Access Token from the AWS Secrets Manager const secretsManagerClient = createSecretsManagerClient( AWS_SECRET_MANAGER_REGION ); const { GOOGLE_ACCESS_TOKEN } = await getSecretsFromSecretsManagerClient( secretsManagerClient, AWS_SECRET_MANAGER_SECRET_ID ); const calendarClient = createCalendarClient(GOOGLE_ACCESS_TOKEN); // Fetch all Calendar events getEventsByCalendarId(calendarClient, GOOGLE_CALENDAR_ID) .then(console.log) .catch(console.error); ``` ## Conclusion In conclusion, by using AWS Secrets Manager with Lambda functions, we can automate secret rotation, improve security, and simplify management processes. This ensures smooth and effective handling of sensitive information in our applications. Until next time, Happy Coding! --- # Secrets Rotation w/ AWS Secrets Manager - Part 1 By Saumitra Topinkatti · 2024-04-21 Canonical: https://www.infraspec.dev/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-1 Automating Secret Rotation with AWS Secrets Manager Managing secrets has always been a significant aspect when deploying applications. Typically, we set up a pipeline to provide secrets to our application as Environment Variables. For enhanced security, we can also choose to encrypt our secrets and store them as configuration files, which the application can access and decrypt at runtime. However, [using long-lived credentials in our applications is a risky practice](https://www.chainguard.dev/unchained/the-principle-of-ephemerality) . The potential damage in the future could be substantial due to their indefinite validity, leading to risks like data theft, privacy breaches, and unauthorized access. On the other hand, short-lived credentials, while not entirely hack-proof, help reduce unauthorized access by expiring after a set period. We can utilize services such as AWS Secrets Manager to efficiently manage secrets, automatically rotate them, and use them in our application. In this blog, I will explore setting up AWS Secrets Manager and Lambda functions to accomplish this. Let’s begin! ## Before using AWS Secrets Manager For this example, I will be considering a simple Node.js application that uses the Google Calendar API to get events from a specific calendar. So far, we’ve been using Service Account keys to easily reach the Google Calendar API. Service Accounts help make Access Tokens for Google API use. Since Service Account keys stay valid for a long time, it’s not recommended for the app to directly use them for access. Let’s employ AWS Secrets Manager and Lambda functions to: 1. Use the Service Account key to make the Access Token. 1. Save the Access Token in the Secrets Manager. This method allows the app to get the Access Token from Secrets Manager and remove the need for Service Account keys. ``` import { config } from "dotenv"; config(); import { createGoogleAuthFromBase64Credentials } from "./google_auth_service"; import { createCalendarClient, getEventsByCalendarId, } from "./google_calendar_service"; /** * `GOOGLE_AUTH_CREDENTIALS_BASE64` -> Google Service Account Key Encoded as Base64 String */ const { GOOGLE_AUTH_CREDENTIALS_BASE64, GOOGLE_AUTH_SCOPES, GOOGLE_CALENDAR_ID, } = process.env; // Split the `GOOGLE_AUTH_SCOPES` string by commas to retrieve a list of scopes const googleAuthScopes = GOOGLE_AUTH_SCOPES.split(","); const googleAuth = createGoogleAuthFromBase64Credentials( GOOGLE_AUTH_CREDENTIALS_BASE64, googleAuthScopes, ); const calendarClient = createCalendarClient(googleAuth); // Fetch all Calendar events getEventsByCalendarId(calendarClient, GOOGLE_CALENDAR_ID) .then(console.log) .catch(console.error); ``` This is my starter code. The Google Service Account key being used is a long-lived credential. That’s why I aim to remove this dependency by having an external service provide my application with the Access Token, which is a short-lived credential. Let’s start configuring the AWS infrastructure to set up AWS Secrets Manager and Lambda functions. ## Configuring the AWS Secrets Manager ### Using AWS CLI ``` # Create a new Secret under the Secrets Manager aws secretsmanager create-secret --name "demo/GoogleAuth/AccessToken" --secret-string '{"GOOGLE_ACCESS_TOKEN":""}' --description "Storing Google Access Token" --kms-key-id "alias/aws/secretsmanager" ``` ### Using AWS Console 1. Visit the [Secrets Manager](https://us-east-1.console.aws.amazon.com/secretsmanager/home?region=us-east-1) service in the AWS Console. 1. Let’s begin by storing a new secret, and let the type of secret be set to “Other type of secret”. ![Let’s start configuring the AWS infrastructure to set up AWS Secrets Manager and Lambda functions.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-1/external-1.png) 1. As I will be storing the Access Token, let’s set the secret key as “ GOOGLE_ACCESS_TOKEN ” and leave the value empty. ![Let’s start configuring the AWS infrastructure to set up AWS Secrets Manager and Lambda functions.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-1/external-2.png) 1. For the Encryption key selection, I’ll leave it as the default option, which is a key managed by AWS. However, you can choose to take an additional step and utilize customer-managed keys for encrypting secrets if you prefer. ![Let’s start configuring the AWS infrastructure to set up AWS Secrets Manager and Lambda functions.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-1/external-3.png) 1. In the “Configure secret” step, let’s name our secret “ demo/GoogleAuth/AccessToken ”. 1. In the “Configure rotation” step, let’s keep the Automatic rotation disabled. We will set up a Lambda function later for Automatic rotation. And there we have it, we have successfully created our secret in the Secrets Manager. Now, let’s proceed to create the Lambda function. This function can be triggered by the Secrets Manager to rotate the secret. ## Configuring the AWS Lambda function ### Using AWS CLI ``` # Create a "trust-policy.json" to use while creating the Lambda Execution Role echo '{ "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }' > trust-policy.json ``` ``` # Create an Execution Role for the Lambda function aws iam create-role --role-name lambda_ex --assume-role-policy-document file://trust-policy.json ``` ``` # Create an empty script file for the Lambda function, and create a Zip archive out of it echo "" > index.js && zip function.zip index.js ``` ``` # Create the Lambda function (make sure to replace the "YOUR_ACCOUNT_ID" with your Account ID) aws lambda create-function --function-name "refreshGoogleAccessTokenSecret" --runtime "nodejs20.x" --role "arn:aws:iam::[YOUR_ACCOUNT_ID]:role/lambda_ex" --handler "index.handler" --architecture "x86_64" --zip-file fileb://function.zip ``` ### Using AWS Console 1. Visit the [Lambda](https://us-east-1.console.aws.amazon.com/lambda/home?region=us-east-1#/begin) service in the AWS Console. 1. Create a new Lambda function and select the “Author from scratch” option. 1. Since the function is meant to refresh the Google Access Token secret, name it “ refreshGoogleAccessTokenSecret ”. 1. I will write the Lambda function in JavaScript, so I’ll choose the Runtime as “Node.js 20.x” and keep the Architecture as “x86_64”. ![And there we have it, we have successfully created our secret in the Secrets Manager.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-1/external-4.png) 1. Create the function. Now that we have configured the Secrets Manager and the Lambda function, let’s link them together. ## Allowing Secrets Manager to invoke our Lambda function We can now set up automatic rotation in the Secrets Manager and connect it to our Lambda function. Before linking them, we need to grant permissions to our Lambda function so that it can be invoked on a scheduled basis through the Secrets Manager. ### Using AWS CLI ``` # Create a new permission under the Lambda function (make sure to replace the `REGION` and `YOUR_ACCOUNT_ID` with the appropriate region name, and your Account ID, respectively) aws lambda add-permission --function-name "refreshGoogleAccessTokenSecret" --statement-id "scheduled-invocation-policy" --action "lambda:InvokeFunction" --principal "secretsmanager.amazonaws.com" --source-arn "arn:aws:secretsmanager:[REGION]:[YOUR_ACCOUNT_ID]:secret:demo/GoogleAuth/AccessToken-*" ``` ### Using AWS Console 1. Go to the Lambda function overview page. 1. Scroll down to locate the “Configuration” tab, and then go to the “Permissions” tab within it. 1. Scroll further down to the “Resource-based policy statements” section. Click on “Add permissions”. ![Before linking them, we need to grant permissions to our Lambda function so that it can be invoked on a scheduled basis through the Secrets Manager.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-1/external-5.png) 1. In the “Edit policy statement” section, choose the “AWS service” option. 1. Under the Service dropdown, select “Secrets Manager”. 1. For the Statement ID, let’s name it “ scheduled-invocation-policy ”. 1. Make sure that the principal is set to “ secretsmanager.amazonaws.com ”. 1. Finally, select the “lambda:InvokeFunction” action from the Action dropdown, and then click on Save. ![Before linking them, we need to grant permissions to our Lambda function so that it can be invoked on a scheduled basis through the Secrets Manager.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-1/external-6.png) This permission will enable the Secrets Manager service to refer to our Lambda function and automatically trigger it at a set schedule. ## Configuring automatic rotation in the Secrets Manager We can now configure automatic rotation in the Secrets Manager and reference our Lambda function. Since I will be rotating the Google Access Token, I will generate the Access Token with a validity of 12 hours, which is the maximum allowed. This allows me to schedule automatic rotation to refresh the access token every 12 hours, instead of every 1 hour. ### Using AWS CLI ``` # Setup automatic rotation in the Secrets Manager (make sure to replace the "REGION", "YOUR_ACCOUNT_ID" and "SECRET_TRAILING_HASH", with the appropriate region name, your Account ID, and the Secret's ARN's trailing hash sequence, respectively) aws secretsmanager rotate-secret --secret-id "arn:aws:secretsmanager:[REGION]:[YOUR_ACCOUNT_ID]:secret:demo/GoogleAuth/AccessToken-[SECRET_TRAILING_HASH]" --rotation-lambda-arn "arn:aws:lambda:[REGION]:[YOUR_ACCOUNT_ID]:function:refreshGoogleAccessTokenSecret" --rotation-rules '{"AutomaticallyAfterDays":12}' ``` ### Using AWS Console 1. Visit the Secrets Manager service page to check our secret details. ![Since I will be rotating the Google Access Token, I will generate the Access Token with a validity of 12 hours, which is the maximum allowed.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-1/external-7.png) - Scroll down to locate the “Rotation” tab. At first, automatic rotation is turned off. You can activate this by clicking on “Edit rotation”. 1. In the “Edit rotation configuration” window, enable “Automatic rotation”. ![Since I will be rotating the Google Access Token, I will generate the Access Token with a validity of 12 hours, which is the maximum allowed.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-1/external-8.png) - In the “Rotation schedule” section, we can set our desired schedule. To refresh the Access Token every 12 hours, I will choose “Hours” as the Time Unit and set it to 12 hours. Additionally, we have the option to define our schedule using an expression, similar to a cron schedule expression. This allows us to create more complex schedules effortlessly. 1. Finally, under the “Rotation function” section, select the created Lambda function from the dropdown menu, and click Save. ![Since I will be rotating the Google Access Token, I will generate the Access Token with a validity of 12 hours, which is the maximum allowed.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-1/external-9.png) Upon saving, you should now notice that the automatic rotation is now enabled. ![Upon saving, you should now notice that the automatic rotation is now enabled.](https://www.infraspec.dev/images/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-1/external-10.png) ## Continuation In this blog, we covered the steps for configuring AWS Secrets Manager and AWS Lambda, as well as setting up Automatic Rotation for our Secret. In Part 2, we will further explore creating and utilizing the IAM policy for our Lambda function and implementing the Lambda function. You can find Part 2 [here](/blog/securing-and-rotating-secrets-with-aws-secrets-manager-part-2/) . --- # TFTP Overview By Nimisha G J · 2024-04-19 Canonical: https://www.infraspec.dev/blog/tftp-overview ## TFTP protocol overview TFTP known as Trivial File transfer protocol is a simple file transfer protocol with features such as get or put files. Unlike FTP or SFTP which can share files across networks TFTP can only share files over a local network, TFTP is known as Lightweight because it uses UDP(User Datagram Protocol) to transfer files and it has no advanced features such as listing files or listing directories ## What problem did TFTP solve? TFTP, or Trivial File Transfer Protocol, was developed to address specific challenges in network environments, primarily focusing on scenarios where simplicity, speed, and efficiency were crucial. ## How does TFTP work? TFTP operates on a client-server model. The client initiates a connection to the server and sends a request for a file transfer, specifying the filename and the transfer mode (binary or ASCII). The server, upon receiving the request, responds by either sending the requested file or an error message if the file is not found or if there’s another issue. Visual Representation of TFTP Communication Flow: Client-Server Interaction: ![tftp communication flow](https://www.infraspec.dev/images/blog/tftp-overview/tftp-communication-flow.png) TFTP has 5 Different message types which is used to communicate between client and server. They are: - RRQ - WRQ - DATA - ACK - ERROR ### RRQ ( Read Request ) The Read Request message, also known as a GET request, is sent by a TFTP client to request a file transfer from the server to the client. It includes the filename of the desired file and the transfer mode (binary or ASCII). Upon receiving an RRQ, the server responds with a Data packet containing the requested file’s contents or an Error packet if the file is not found or cannot be accessed. Packet Layout of RRQ message: ![RRQ message packet format](https://www.infraspec.dev/images/blog/tftp-overview/rrq.png) ### WRQ ( Write Request ) Contrary to RRQ, the Write Request message, or PUT request, is initiated by the client to upload a file to the server. Similar to RRQ, it includes the filename and transfer mode. Upon receiving a WRQ, the server acknowledges the request with an ACK packet, indicating its readiness to receive the file, or responds with an Error packet if the operation cannot be completed. Packet Layout of WRQ message: ![WRQ message packet format](https://www.infraspec.dev/images/blog/tftp-overview/wrq.png) ### DATA message The Data packet carries a portion of the file being transferred, typically containing a block of data. Each Data packet includes a block number to facilitate sequential transmission and acknowledgment. After sending a Data packet, the sender awaits an ACK packet from the receiver before transmitting the next block. If the sender doesn’t receive an ACK within a specified timeout period, it retransmits the Data packet. Packet Layout of DATA message: ![DATA message packet format](https://www.infraspec.dev/images/blog/tftp-overview/data.png) ### ACK ( Acknowledgment ) Acknowledgment packets, or ACKs, are sent by the receiver to confirm the successful receipt of a Data packet. Each ACK packet contains the block number of the Data packet it acknowledges. Upon receiving an ACK, the sender proceeds to transmit the next block of data. In case of packet loss or corruption, the sender retransmits the Data packet until it receives a valid ACK. Packet Layout of ACK message: ![ACK message packet format](https://www.infraspec.dev/images/blog/tftp-overview/ack.png) ### ERROR message Error packets are generated by either the client or the server to communicate error conditions during a TFTP transaction. An Error packet includes an error code and a textual error message describing the encountered issue. Common error codes include file not found, access violation, disk full, and illegal TFTP operation. Upon receiving an Error packet, the recipient terminates the transaction and may display or log the error message for diagnostic purposes. Packet Layout of ERROR message: ![ERROR message packet format](https://www.infraspec.dev/images/blog/tftp-overview/error.png) ## Advantages of TFTP 1. Simplicity: TFTP’s design is straightforward, with fewer features and commands compared to FTP. This simplicity makes it easier to implement and use, requiring less overhead and fewer resources. 1. Minimalist: TFTP is lightweight, both in terms of its protocol design and its resource requirements. This makes it suitable for embedded systems, such as routers, switches, and other network devices with limited memory and processing power. 1. Fast: Because TFTP operates over UDP, which doesn’t have the connection establishment and teardown overhead of TCP, it can be faster for transferring small files over high-speed networks. 1. Bootstrapping: One of TFTP’s primary use cases is bootstrapping diskless devices, such as network booting of thin clients, diskless workstations, or embedded systems. Its simplicity and low overhead make it ideal for this purpose. ## Limitations of TFTP 1. Lack of Authentication: TFTP lacks built-in user authentication mechanisms, which can pose security risks in environments where user access control is essential. 1. Limited Error Handling: TFTP’s error handling capabilities are basic, with error messages providing minimal information about the encountered issue. 1. No Directory Listing: Unlike protocols like FTP or SFTP, TFTP does not support directory listing functionality. Users must manually specify the filenames they want to transfer, which can be cumbersome, especially when dealing with large numbers of files or directories. 1. File Size Limitation: TFTP is not optimized for transferring large files efficiently. Its reliance on UDP and lack of features like file segmentation or resuming transfers mean that transferring large files can be slower and less reliable compared to protocols designed specifically for handling such scenarios. 1. UDP Reliance: While UDP offers advantages in terms of speed and efficiency, it also introduces potential issues such as packet loss or out-of-order delivery. TFTP’s reliance on UDP means that it may not be the best choice for environments where reliability is paramount, particularly over unreliable or congested networks. ## Most commom use cases of TFTP - Network Booting: Booting diskless devices over a network, where the operating system is loaded from a remote server. - Firmware Updates: Updating firmware on network devices, such as routers, switches, and printers. - Configuration Management: Transferring configuration files to network devices for provisioning and management. - Software Distribution: Distributing small files, such as firmware updates or configuration files, across a network. ## Conclusion In conclusion, TFTP has established itself as a valuable tool within network environments. Its core strengths lie in simplicity, speed, and minimal resource requirements. These attributes make TFTP particularly well-suited for tasks like network booting, firmware updates, and configuration management, especially for devices with limited processing power or memory. While more feature-rich protocols exist for broader file transfer needs, TFTP remains a relevant and efficient solution for specific use cases. ## Question How do you think TFTP compares to other file transfer protocols in terms of ease of use? --- # Automated Netbooting for Raspberry Pi By Rohit Nagmoti · 2024-04-17 Canonical: https://www.infraspec.dev/blog/rpi-netboot-automation In this blog, we’ll delve into automating the netbooting process using a bash script ( pxeService.sh ) and an address list ( addresslist.txt ) to enhance the deployment and management of Raspberry Pi devices. If you haven’t already, you can catch up on the initial steps and concepts discussed [here](https://www.infraspec.dev/blog/rpi-netboot-deep-dive/) , where we laid the groundwork for this automation project. ## Bash Script Overview The pxeService.sh script is designed to automate the setup for each PXE client (Raspberry Pi device). You can look at the complete pxeService.sh script [here](https://github.com/infraspecdev/rpi-network-boot/blob/main/pxeScript.sh) . Here’s a breakdown of the script: ### Constants and Log Paths In this code snippet, we define constants for the script, such as the UDP port to listen on (PORT=69) and the path for logging (pxe_service_log_path="/var/log/pxeService.log") . Before running the script, it’s essential to ensure that the pxeService.log file is created in the /var/log directory. This log file will store the script’s output and any logged messages during execution. ``` #!/bin/bash PORT=69 pxe_service_log_path="/var/log/pxeService.log" ``` ### Handling Error and Listening to Requests One of the script’s critical components is the use of tcpdump . This tool plays a crucial role in real-time network monitoring. It allows the script to capture and analyse network traffic, specifically UDP requests, on a specified port ( $PORT ). This capability is fundamental as it enables the script to promptly detect and respond to incoming requests from PXE clients. ``` # Function to handle errors handle_error() { local line_number="$1" echo "An error occurred at line $line_number" >> "$pxe_service_log_path" exit 1 } # Function to process UDP packets process_udp_packets() { tcpdump -l -i any -e udp port "$PORT" | while read -r line; do MAC=$(echo "$line" | awk '{print $6}' | tr ':' '-') TIME=$(date +"%Y-%m-%d %H:%M:%S") if grep -q "$MAC" /opt/addresslist.txt; then echo "$MAC already exists" >> "$pxe_service_log_path" else echo "************Executing macscript.sh for $MAC***************" >> "$pxe_service_log_path" echo "$MAC" >> /opt/addresslist.txt FILE=$(echo "$line" | grep -o -P '(?<=RRQ ")[^"]+') FILE=$(awk -F'/' '{print $NF}' <<< "$FILE") if [ "$FILE" = "start4.elf" ]; then echo "Time: $TIME, MAC address: $MAC, Requested file: $FILE" >> "$pxe_service_log_path" configure_pxe_services "$MAC" & echo "**********macscript execution finished for MAC $MAC**********" >> "$pxe_service_log_path" else echo "Not found" >> "$pxe_service_log_path" fi fi done } # Trap for handling errors trap 'handle_error $LINENO' ERR # Start processing UDP packets process_udp_packets ``` ### Configure dnsmasq.conf Another vital aspect is configuring dnsmasq specifically for the TFTP (Trivial File Transfer Protocol) server functionality. In this context, dnsmasq serves as the TFTP server, which is essential for transferring boot files to PXE clients during netbooting. The enable-tftp option in the configuration enables TFTP support within dnsmasq , ensuring seamless file transfer operations. Additionally, the tftp-root parameter specifies the root directory for TFTP, providing a structured environment for storing and accessing boot files required by PXE clients. ``` # Function to configure dnsmasq service configure_dnsmasq_service() { local service_name="$1" local dnsmasq_conf="/etc/dnsmasq.conf" if [ "$service_name" == "dnsmasq" ] && systemctl is-active --quiet "dnsmasq"; then echo "Configuring $dnsmasq_conf..." read -p "Enter the interface name (e.g., bond0): " interface_name # Create or append to dnsmasq configuration cat < /dev/null interface=$interface_name no-hosts enable-tftp tftp-root=/srv/tftp tftp-unique-root=mac log-facility=/var/log/dnsmasq port=5353 EOF echo "Configuration has been added to $dnsmasq_conf" >> "$pxe_service_log_path" fi } ``` ### Install Necessary Services The ensure_service_installed function checks whether a specific service is installed and active. If the service is inactive, it attempts to install it using apt and then starts. If the installation and start are successful, it logs the outcome; otherwise, it logs a failure message. ``` # Function to ensure service is installed ensure_service_installed() { local service_name="$1" if systemctl is-active --quiet "$service_name"; then echo "$service_name is already installed and active." >> "$pxe_service_log_path" else echo "Installing and starting $service_name..." >> "$pxe_service_log_path" sudo apt update sudo apt install -y "$service_name" if systemctl is-active --quiet "$service_name"; then echo "$service_name installed and started successfully." >> "$pxe_service_log_path" configure_dnsmasq_service "$service_name" else echo "Failed to install or start $service_name. Please check and install it manually." >> "$pxe_service_log_path" fi fi } ``` ### Copying Boot, Root Files and Exporting the Entries to Exports The configure_pxe_services function is responsible for setting up the necessary directories, copying boot and root files, configuring cmdline.txt and fstab files, and adding entries to the Raspberry Pi server’s exports. It performs these actions to ensure the PXE services are properly configured for a specific MAC address, effectively facilitating the netbooting process. ``` # Function to configure PXE services configure_pxe_services() { local mac_address="$1" local nfs_root="/srv/nfs/$mac_address" local tftp_root="/srv/tftp/$mac_address" local nfs_exports="/etc/exports" # Log start of script execution echo "**********Configuring PXE services for $mac_address**********" >> "$pxe_service_log_path" # Ensure required services are installed ensure_service_installed "nfs-kernel-server" ensure_service_installed "dnsmasq" # Create directories for TFTP and NFS echo "Creating directories for $mac_address in TFTP and NFS" >> "$pxe_service_log_path" sudo mkdir -p "$tftp_root" "$nfs_root" # Copy necessary files to NFS and TFTP directories echo "Copying root files to NFS directory" >> "$pxe_service_log_path" sudo cp -a "/home/pi/userfiles/"* "$nfs_root" echo "Finished copying root files" >> "$pxe_service_log_path" echo "Copying boot files to TFTP directory" >> "$pxe_service_log_path" sudo cp -r "/home/pi/bootfiles/"* "$tftp_root" echo "Finished copying boot files" >> "$pxe_service_log_path" # Configure cmdline.txt for boot parameters echo "Configuring boot parameters in cmdline.txt" >> "$pxe_service_log_path" echo -e "console=serial0,115200 console=tty1 root=/dev/nfs nfsroot=192.168.XX.XX:$nfs_root rw rootwait" | sudo tee "$tftp_root/cmdline.txt" > /dev/null # Update fstab with NFS mount entry local new_fstab_content="proc /proc proc defaults 0 0\n\ PARTUUID=4e639091-02 / ext4 defaults,noatime 0 1\n\ 192.168.XX.XX:$tftp_root /boot nfs defaults 0 0" echo "Updating fstab with NFS mount entry" >> "$pxe_service_log_path" echo -e "$new_fstab_content" | sudo tee "$nfs_root/etc/fstab" > /dev/null # Add NFS and TFTP entries to export file echo "Adding NFS export in $nfs_exports" >> "$pxe_service_log_path" echo "$nfs_root *(rw,sync,no_subtree_check,no_root_squash)" | sudo tee -a "$nfs_exports" > /dev/null echo "Adding TFTP export in $nfs_exports" >> "$pxe_service_log_path" echo "$tftp_root *(rw,sync,no_subtree_check,no_root_squash)" | sudo tee -a "$nfs_exports" > /dev/null # Reload NFS exports echo "Reloading NFS exports" >> "$pxe_service_log_path" sudo exportfs -r # Log completion of script execution echo "**********Successfully configured PXE services for $mac_address**********" >> "$pxe_service_log_path" } ``` ## Address List Management The addresslist.txt file serves as a record of processed MAC addresses. Before executing the setup for a new MAC address, the script checks this list to ensure it hasn’t already been configured. This prevents unnecessary duplication of efforts. Create addresslist.txt in the /opt directory. Here’s an example of how the addresslist.txt file might look: ``` 00-11-22-33-44-55 aa-bb-cc-dd-ee-ff ``` ## Running the Script as a Daemon To ensure continuous monitoring and execution of the pxeService.sh script, we can set it up as a daemon process using a systemd service unit file ( pxeService.service ). Here’s how you can create and configure the service: 1. Copy the pxeService.sh file to the /usr/bin directory. 1. Create a new file named pxeService.service in the /etc/systemd/system/ directory. 1. Add the following content to pxeService.service : ``` [Unit] Description=PXE Service Daemon After=network.target [Service] Type=simple ExecStart=/bin/bash /usr/bin/pxeService.sh Restart=always [Install] WantedBy=multi-user.target ``` Save the file and exit the editor, then reload systemd to read the new service unit: ``` sudo systemctl daemon-reload ``` Enable and start the pxeService.service ``` sudo systemctl enable pxeService.service sudo systemctl start pxeService.service ``` Now, the pxeService.sh script will run as a daemon, continuously monitoring and automating the netbooting process for the new Raspberry Pi devices. ## Conclusion In this guide, we’ve automated the booting process using bash scripting. By leveraging automation and creating a daemon service, you can significantly streamline the provisioning and maintenance of Raspberry Pi devices in your network. --- # PXE Boot Sequence Deep Dive By Rohit Nagmoti · 2024-04-16 Canonical: https://www.infraspec.dev/blog/rpi-netboot-deep-dive ## Understanding PXE Boot ### What is PXE Boot? The Preboot Execution Environment (PXE) specification describes a standardized client-server environment that boots a software assembly retrieved from a network on PXE-enabled clients. ### Why PXE Boot? - Simplify Pi provisioning and maintenance as much as possible. - Automate updates/upgrades as much as possible. Netbooting is a good path to achieve this. For example, when you netboot a Pi, it does not require an SD card to boot. The OS and file system live on a central server. Because most provisioning happens on a central server, we can eventually automate it via scripts. ### PXE Boot Sequence - Power On Raspberry Pi (PXE Client): The user powers on the Raspberry Pi device configured for PXE boot. - PXE Boot Initialization: The Raspberry Pi initiates a PXE boot process and sends a PXE boot request (DHCPDISCOVER) to the network. - DHCP Server Response: A DHCP server on the network receives the PXE boot request. The DHCP server assigns an IP address to the Raspberry Pi and responds with DHCP offer (DHCPOFFER) containing network configuration details. - PXE Client Request to Main Router: The Raspberry Pi, acting as a PXE client, sends a TFTP request for specific files (e.g., start4.elf) to the main router’s IP address. The main router receives the TFTP request from the PXE client. - Router Redirects TFTP Request to PXE Server: The main router, configured for PXE boot services, redirects the received TFTP request to the PXE server where the TFTP server is running. The router forwards the TFTP request to the PXE server’s IP address. - PXE Server Response: The PXE server, hosting the TFTP server, receives the redirected TFTP request from the main router. The TFTP server on the PXE server responds with the requested file (e.g., start4.elf) to the PXE client (Raspberry Pi). - File Transfer and Execution: The Raspberry Pi (PXE client) receives the requested file (start4.elf) from the PXE server’s TFTP server. The Raspberry Pi executes the received file, which may be part of the initial boot process or firmware loading for the device. - Boot Process Continues: Depending on the boot configuration and setup, the Raspberry Pi may continue to load additional files or components necessary for booting, such as bootloader configurations, kernel images, and initial RAM disks. - NFS Mount for Root File System: Once the boot process is completed, the Raspberry Pi performs an NFS mount to access the root file system, which is mounted on the PXE server. This step allows the Raspberry Pi to access and use the root file system located on the PXE server over the network. ## Setting Up The Infrastructure ![Network Infrastructure](https://www.infraspec.dev/images/blog/rpi-netboot-deep-dive/network-infrastructure.png) ### Required Components To implement netbooting for Raspberry Pi devices, you’ll need the following components: - Raspberry Pi units acting as PXE clients connected via Ethernet to the router or switch. - Raspberry Pi as a PXE server containing boot files and user files connected via Ethernet to the router or switch. ## Configuration ### PXE Boot Client Configuration #### Configuring Boot Order To set the boot order on your Raspberry Pi, follow these steps: 1. Access raspi-config: Run sudo raspi-config in the terminal to open the Raspberry Pi configuration tool. 1. Navigate to Advanced Options: Within raspi-config, choose “Advanced Options” from the menu. 1. Select Boot Order: In the Advanced Options menu, select “Boot Order.” 1. Choose Network Boot: Within the Boot Order settings, select “Network Boot” as the desired boot option. 1. Save Changes and Reboot: Confirm the selection and exit raspi-config. Reboot the Raspberry Pi for the changes to take effect. Important Note: After rebooting, ensure that you reboot back into Raspberry Pi OS and not just shut down the device. This is necessary for the change in boot order to be programmed into the bootloader EEPROM. To verify that the boot order has been set correctly, run the following command after rebooting: ``` $ vcgencmd bootloader_config ``` This command will display the current bootloader configuration, confirming that the boot order is set to prioritize the SD card first, followed by network boot. ### PXE Boot Server Configuration #### Install the packages needed ``` $ sudo apt update $ sudo apt install -y nfs-kernel-server dnsmasq ``` The client Raspberry Pi will need a root file system to boot from: we can use a copy of the server’s root filesystem and place it in /nfs/ . ``` $ sudo mkdir -p /nfs/ $ sudo cp -a ~/userfiles/* /nfs/ ``` #### Configure /etc/fstab for the client ``` $ echo | sudo tee /nfs//etc/fstab $ echo "proc /proc proc defaults 0 0" | sudo tee -a /nfs//etc/fstab $ echo "192.168.XX.XX:/tftpboot/ /boot nfs defaults,vers=4.1,proto=tcp 0 0" | sudo tee -a /nfs//etc/fstab ``` Configuring the /etc/fstab file for the PXE client is essential to ensure that the client mounts the necessary file systems correctly during the boot process. #### Export the root file system created earlier, and the TFTP boot folder ``` $ echo "/nfs/ *(rw,sync,no_subtree_check,no_root_squash)" | sudo tee -a /etc/exports $ echo "/tftpboot *(rw,sync,no_subtree_check,no_root_squash)" | sudo tee -a /etc/exports ``` #### Copy the boot files to the specified directory ``` $ sudo mkdir -p /tftpboot/ $ sudo chmod 777 /tftpboot $ sudo cp -r ~/bootfiles/* /tftpboot/ ``` Important Note: Replace 192.168.XX.XX with the IP address of PXE server and with the MAC address of PXE client. #### Configure dnsmasq.conf Dnsmasq simplifies PXE booting because it’s a versatile tool that combines DHCP, DNS, and TFTP services into one package. 1. Integrated Services: Dnsmasq handles IP address assignment (DHCP), hostname resolution (DNS), and boot file delivery (TFTP), making it a one-stop solution for PXE booting. 1. Lightweight: It’s lightweight and efficient, meaning it doesn’t require a lot of system resources to run, making it suitable for a wide range of devices and environments. 1. Easy Configuration: Dnsmasq is easy to set up and configure, with straightforward options for defining DHCP lease ranges, DNS settings, and TFTP root directories. ``` $ cat << EOF | sudo tee /etc/dnsmasq.conf interface=eth0 log-dhcp enable-tftp log-facility=/var/log/dnsmasq tftp-root=/tftpboot tftp-unique-root=mac pxe-service=0,"Raspberry Pi Boot" EOF ``` ### Conclusion In conclusion, implementing PXE boot for Raspberry Pi devices streamlines deployment and maintenance by centralizing the boot process and file systems. Automation of these processes further enhances efficiency and reduces manual intervention. To learn more about automating Raspberry Pi deployment using PXE boot, click [here](https://www.infraspec.dev/blog/rpi-netboot-automation) . --- # Cron Jobs Guide By Shivani Banke · 2024-04-15 Canonical: https://www.infraspec.dev/blog/cron-jobs ![Cron Jobs cover](https://www.infraspec.dev/images/blog/cron-jobs/cron-jobs-cover.png) In this article, tailored specifically for users of Unix-like systems such as Linux, we’ll explore everything you need to know about cron jobs. From understanding their functionality and syntax to mastering practical applications.Additionally, we’ll touch upon the alternative systemd timers and their role in modern task scheduling. ## So, what are Cron Jobs? Before crons, managing repetitive tasks was like being a chef juggling multiple pans on a hot stove, constantly checking and flipping without any help - exhausting and prone to mishaps! But then came crons, the kitchen timer of the digital world! Just like how a chef can set a timer and walk away, crons are like your trusty digital sous chef, taking care of business while you sip your coffee. Cron jobs are scheduled tasks that run at predefined intervals on Unix-like operating systems. They are commonly used to automate repetitive tasks such as backups, maintenance, and report generation. ## How to execute Cron Jobs using Crontabs ? - Access the crontab file using the following command ``` $ crontab -e. ``` 1. Add your cron job entries using the proper syntax (timing and command). 1. Save and exit the crontab file. 1. Cron will automatically execute the scheduled tasks according to the specified timings. ## What is a Crontab file? Crontab, short for “cron table,” is a text file that outlines the schedule for cron jobs. There are two main types of crontab files: system-wide crontab files and individual user crontab files. Cron is commonly pre-installed by default in all Linux distributions. Otherwise, run the installation command according to your package manager. Here’s the command for Ubuntu with apt: ``` $ sudo apt install cron ``` Individual user crontab files are named after the respective user and their storage location varies based on the operating system. For example, in Red Hat-based distributions like CentOS, these files reside in the /var/spool/cron directory while in Debian and Ubuntu systems, they are stored in the /var/spool/cron/crontabs directory. Although it’s possible to manually edit user crontab files, it’s generally recommended to utilize the crontab command for this purpose. On the other hand, the /etc/crontab file and the scripts within the /etc/cron.d directory serve as system-wide crontab files and are typically editable only by system administrators. ## Crontab Syntax and Operators Each line in the user crontab file contains six fields separated by a space followed by the command to be run. ![Cron Expression syntax](https://www.infraspec.dev/images/blog/cron-jobs/cron-expression-syntax.png) ### Special Characters - Asterisk (*) : Represents all possible values for a field. - Hyphen (-) : Specifies a range of values. - Comma (,) : Specifies multiple values. - Forward Slash (/) : Specifies increments. For example, * /10 8-16 * 1-5 /home/u[s](http://script.sh)er/scripts/ s cript.sh" This cron expression executes the script /home/user/scripts/script.sh every 10 minutes during the hours of 8:00 AM to 4:00 PM, Monday through Friday. > Note: If you want an easy way to debug cron syntax, there are many online editors such as [crontab.guru](https://crontab.guru/) that will show you what your schedule expression means in layman terms, i.e. “Every weekday at 3 PM”. ## Predefined Macros There are several special Cron schedule macros used to specify common intervals. You can use these shortcuts in place of the five-column date specification. - @yearly (or @annually ) - Run the specified task once a year at midnight (12:00 am) of the 1st of January. Equivalent to 0 0 1 1 * . - @monthly - Run the specified task once a month at midnight on the first day of the month. Equivalent to 0 0 1 * * . - @daily - Run the specified task once a day at midnight. Equivalent to 0 0 * * * . - @weekly - Run the specified task weekly at midnight on Sunday. Equivalent to 0 0 * * 0 . - @reboot - Run the specified task at the system startup (boot-time). > Note: For simplifying the process of generating cron job expressions, there’s a website called [Crontab Generator](https://crontab-generator.org/) . ## Linux Crontab Command The crontab command enables you to manage cron jobs by installing, viewing, or opening a crontab file for editing. - crontab -e - Edit crontab file or create one if it doesn’t already exist. - crontab -l - Display crontab file contents. - crontab -r - Remove your current crontab file. - crontab -i - Remove your current crontab file with a prompt before removal. - crontab -u - Edit other user crontab file. This option requires system administrator privileges. For example: ![Crontab entry](https://www.infraspec.dev/images/blog/cron-jobs/crontab-entry.png) ## Crontab Variables The cron daemon automatically configures several environment variables: 1. The default path is set to PATH=/usr/bin:/bin . If your command isn’t in this path, you can either use the absolute command path or adjust the cron $PATH variable. Note that you can’t implicitly append: $PATH as with regular scripts. 1. The default shell is /bin/sh . To use a different shell, modify the SHELL variable. 1. Cron executes commands from the user’s home directory. You can set the HOME variable in the crontab if needed. - By default, cron sends email notifications to the crontab owner. However, you can override this behavior by using the MAILTO environment variable, specifying a comma-separated list of email addresses. Setting MAILTO="" will prevent any email notifications from being sent. This feature is particularly useful in case a cron job encounters errors; it allows the system to promptly inform the owner or specified recipients about any issues that occurred during the execution of the job. For example: Run a script every 5 minutes and redirected the standard output to dev null, only the standard error will be sent to the specified e-mail address: MAILTO= [email@example.com](mailto:email@example.com) */5 * * * * /path/to/script.sh > /dev/null ## Crontab Restrictions To control user access to the crontab command, you can utilize the /etc/cron.deny and /etc/cron.allow files. These files contain lists of usernames, with one username per line. By default, only the /etc/cron.deny file is present and empty, allowing all users to utilize the crontab command. To restrict access for specific users, you can add their usernames to the /etc/cron.deny file. If the /etc/cron.allow file exists only the users who are listed in this file can use the crontab command. If neither of the files exists, only the users with administrative privileges can use the crontab command. ## Systemd Timers as Cron Job Alternatives: ### What are Systemd Timers? Systemd timers offer a modern approach to task scheduling on Unix-like systems. Integrated seamlessly into the systemd init system, systemd timers provide similar functionality to cron jobs but with some distinct advantages. Unlike cron, which relies solely on crontab files, systemd timers are part of a larger systemd service. They are typically configured using a combination of .timer and .service files. This approach allows for more comprehensive management and integration of scheduled tasks with other systemd services and units. ### Advantages of Systemd Timers Over Cron Jobs - Event-Based Triggering: Systemd Timers can trigger tasks based on various events such as service activation, socket activation, or path existence. This event-based approach offers more flexibility than Cron Jobs, which rely solely on time triggers such as specific times, intervals, or predefined strings like @daily . For example, Automatically restarting a failed service using Systemd Timers when a specific error log file indicates a failure. - Dependency Management: Systemd Timers efficiently handle dependencies between tasks and services, ensuring that tasks are executed only when specific conditions are met. This dependency management capability is not available in Cron Jobs. For example, a web application requires a database connection for a scheduled task to run. With Systemd Timers, you can ensure the task only executes after the database service is up and running. - Built-in Logging and Monitoring: Systemd provides comprehensive logging of service and timer units, simplifying debugging and monitoring of automated tasks. In contrast, Cron Jobs do not offer built-in logging capabilities, making troubleshooting more challenging. The logs are located in the /var/log/journal/ directory. - Better Integration with System Services: Systemd Timers are tightly integrated into the Systemd init system, resulting in better integration and easier management of tasks with other system services. For example, You have a web application that relies on a backend API service. Now, you need to schedule regular cache clearing tasks to prevent stale data buildup. With Systemd Timers, you can tightly integrate cache clearing tasks with the API service. - Advanced Scheduling Options: Systemd Timers offer more advanced scheduling options, including monotonic and realtime timers, which provide precise control over task execution timing. For example, Consider a financial institution processing stock trades. Systemd Timers with advanced scheduling options allow the institution to execute critical tasks, such as trade settlement processes, with precise timing accuracy as monotonic timers ensure consistent intervals between trades, while realtime timers enable timely execution of end-of-day processes. ### Features relevant to Cron Jobs - Simple Time-Based Scheduling: If your task scheduling needs are straightforward and involve only time-based triggers (e.g., running a backup script every night at midnight), Cron Jobs provide a simple and effective solution without the need for additional complexity. - Legacy System Compatibility: On older Unix-like systems as well as some Linux distros that do not use Systemd as their init system, Cron Jobs remain the standard and widely supported method for task scheduling. - Portability Across Systems : Cron Jobs offer portability across different Unix-like systems, allowing scripts and automation workflows to be easily transferred and executed without dependencies on specific init systems like SystemD. - User-Specific Tasks : Setting up user-specific Cron Jobs is often simpler and more straightforward compared to configuring user-specific Systemd Timers. For users who require individualized task scheduling or automation, Cron Jobs provide an accessible solution without the need for complex configuration. - Minimal System Dependency : Cron Jobs have minimal dependencies on other system components, making them lightweight and efficient for simple task scheduling needs. In contrast, Systemd Timers are part of the larger Systemd init system and may introduce additional overhead or complexity for users who only require basic task scheduling capabilities. > Note: If you’re unsure how to use Systemd Timers, check out the guide on how to get started: [ https://documentation.suse.com/smart/systems-management/html/systemd-working-with-timers/index.html ]. ### Conclusion Both Cron Jobs and Systemd Timers play vital roles in task scheduling and system automation. While Cron Jobs offer simplicity and widespread compatibility, Systemd Timers provide advanced features like event-based triggering and better integration with system services making it well-suited for modern automation needs. Whether you opt for Cron Jobs or Systemd Timers depends on your specific requirements, familiarity with the tools, and the complexity of your automation tasks. By understanding the strengths and limitations of each option, you can make an informed decision to streamline your task scheduling and enhance system efficiency. --- # Linux Memory & Swap By Nimisha G J · 2024-04-15 Canonical: https://www.infraspec.dev/blog/linux-memory-swap ## Introduction This blog will help you figure out how to check how much memory is left on your Linux machine. Knowing this will tell you if your server is running low on memory and needs attention, or if everything is fine. Following this, an explanation will be provided regarding the concept of swap and its relevance for the operation of a Linux machine or server. ### Output of htop command ![My Collection](https://www.infraspec.dev/images/blog/linux-memory-swap/htop.png) ## What is htop? Htop is a resource monitoring utility, here we can see the amount of resources being used and how much memory is being used htop also shows the number of CPUs, the average CPU usage, and the amount of swap usage The issue is that most of the times htop is not always available in Linux servers, but most distributions make the htop available to install, but some Linux distributions don't offer htop to install even in the standard repository Next, we will explore how to view the amount of memory usage without relying on third-party utilities. This leads us to the first command, the free command. The free command provides information on the amount of free memory available. ### Output of free command ``` user@machineHost:~$ free total used free shared buff/cache available Mem: 16148256 4191812 4560 619412 2315200 11956444 Swap: 2048 0 2048 ``` However, these numbers may not be immediately comprehensible. Therefore, we will utilize the -m option with the free command, which presents the memory statistics in megabytes, making them easier to interpret. ### Output of free -m command ``` user@machineHost:~$ free total used free shared buff/cache available Mem: 15769 4191 456 522 2178 11593 Swap: 2048 0 2048 ``` Determining the amount of free memory in Linux can be confusing. We might initially look at the free field and feel concerned if we see only 100MB of free memory. However, focusing on the available field provides a better picture. If we find 1000MB of available memory, we can feel reassured. Simply checking the available field in the free command gives us an idea of available memory, but it's not the whole story. Let's explore how Linux manages memory. The total field indicates the total memory installed, while used shows current memory usage by processes. Free indicates unused memory, and available represents memory ready for use, including cached data. In Linux, unused RAM is Wasted RAM . Linux caches data in RAM for quicker access, meaning the available field includes memory used for caching but is ready for immediate use if needed. In summary, Linux optimizes RAM usage by caching data, ensuring efficient memory utilization for better system performance. Now, we’ll shift our focus to swap usage. ## What is Swap? Swap memory, also known as swap space, is a section of a computer's hard disk or SSD that the operating system (OS) uses to store inactive data from Random Access Memory (RAM). Because swap exists on the hard disk, accessing swap memory is slower compared to accessing RAM. While swap is something we hope to avoid using, it serves as a safety net for when RAM becomes full. It's debated whether it's okay to run a Linux server or workstation without swap, but having some swap space, even sparingly like 1GB, doesn't heavily impact the hard disk. Additionally, some applications require swap even if there's available memory. Linux determines whether to use swap with the swappiness value. This value helps the system decide how much swap to use at any given time. To check the swappiness value, you can use the command: sysctl vm.swappiness ### Output of sysctl vm.swappiness command ``` user@machineHost:~$ sysctl vm.swappiness vm.swappiness = 60 ``` Lowering the swappiness value means that the system is less likely to use swap. However, setting it to zero doesn't guarantee that the swap won't be used; instead, it indicates that the system aggressively avoids using the swap unless necessary. There isn’t a universal value for setting swappiness, it varies depending on the server and its workload. ## Conclusion In conclusion, the comprehension of memory and swap usage is deemed paramount for the optimization of Linux system performance. By understanding memory management techniques and understanding the role of swap, efficient allocation of resources can be ensured, and system responsiveness ## Question So, do you prefer using swap memory in your Linux distro, or do you opt to run without it? --- # Building Internal Tooling in Legacy Systems By Abhishek Sangwan · 2024-04-11 Canonical: https://www.infraspec.dev/blog/building-internal-tools This article takes you through what it is like to build an internal tool while dealing with a lot of legacy systems where a lot of tech debts already exist. I have worked on some internal tools during my journey of being a software engineer in companies like Gojek, Swiggy, an education platform and CRED. In this article I am going to talk about my experiences in building an internal tool. ## Prelude ### What are internal tools ? Internal tools are the ones which become a necessity for a tech organization after a period of existence into the business and definitely not needed before the PMF of the product. So the necessity could be dev productivity, pulling up security standards, efficiency in the internal processes etc . As every organization is a unique combination of different perspectives their systems/patterns also look different from each other at 10000 ft level. Due to these different perspectives they run into unique problems which any off the shelf tools can’t solve. For e.g you need to build a authorization system for your internal CRM (security enhancement), where you are calling 100s of APIs to get and aggregate the data from multiple backend systems, in this case there will be different contracts, different kind of adoption of HTTP verbs and implementation and trust me you’ll be surprised day on seeing the permutation of variety HTTP that can exist in the system. After considering these ground realities organizations decide to build an internal tool which solves the problem and also fits in the processes. ## Horizontal cutting These kinds of problems are going to impact a lot of internal users from operations to engineers, there are going to be multiple key stakeholders from impact and collaboration point of view. What you are going to deal with is legacy and a process which is already adopted by the organization. ## Ownership These are going to be legacy systems/processes and your job is to build a tool to solve it, as this is going to be mostly processes which are leaky and tech debts, it’s highly likely you are not going to have shared ownership between product manager/programme manager/engineer. ## Discovery As I said this is post PMF phase, most organizations miss out that these problems are going to hit you once you scale your product while they are majorly focussing on the growth of the business. So think about the problem which is compounding with time and suddenly gets prioritized while being on the back burner since the org existed. Most likely there would be no single person whom you can interview to understand all the use cases and problem statement. It’s going to be a fuzzy and blurred space which you have to navigate. ## Collaboration Now that you have identified the problem statement and a solution, there are going to be situations where your solution is dependent on other teams and has some past context and history. Software is already a high collaborative work but in this case it might become a bottleneck for you. ## Execution From an engineering point of view you are going to deal with a lot of tech debts, where it’s hard to navigate while executing the project, and you might end up breaking the existing systems or add more to the tech debts. ## Adoption Adoption is going to be the toughest and most frictional part of the whole process where you need to move people from the existing process to the solution which you have built. You’re definitely going to uncover something which you missed out in the analysis. As most of your users mostly won’t be having any incentive to move to a new tool, and it is going to take a lot of convincing for them to move. This is more or less the nature of work and what are some key problems you are going to face while building and rolling out an internal tool. As an engineer you need to operate in a certain way to overcome this problem as the problem space is dynamic and full of constraints which you can’t break. Every system and process has flaws, and you need to be understanding and be patient while dealing with this as the organization has scaled to a certain level with the current systems and the processes around it. Nobody wants to do bad work but while the focus was on growth leadership was not able to prioritize and fix the gaps. Now that you are owning the problem statement organization has put faith in you to do the right thing. So think from an open mind and understand the constraint and situation of all the people who are using and maintaining those systems. This will help you to be calm as you are going to deal with a lot of unknowns and be comfortable in uncomfortable situations. One time while putting a code patch we encountered a JS file with more than 12k lines of code, we wanted to write tests for the patch we have put in but gave up after days of effort as the code dependency was quite huge and tightly coupled with the system. We had to give up on the discipline which we follow to make progress and such instances are going to be normal. This is about ownership and there are going to be multiple key touch points it’s hard to build these systems in silos and show outcome one fine day. To get you unblocked, figure out the key sponsor of the project in the leadership team who has vested interest in getting this product shipped. This will help you put some weight in the places where you are struggling to prioritize your requirements and get yourself unblocked. Make sure you keep producing artifacts during your journey of discovery, execution and roll out of the product. This encompasses the current state of the system and how it is getting used, use cases and the persona of the colleagues who are using the system in the discovery phase. While we were building a tool for enhanced security on an internal CRM portal this is definitely going to mask/abstract information from the users(operations) as there is going to be some personal information of the customer which is visible on that portal that is not needed to be accessed by everyone. What we did was identify the persona on what kind of role (customer-support/payment-operations etc) needs what kind of access and from here we started building up requirements. This stands true for design documents, rollout plan, rollback plans too. You are going to interview a lot of people during the whole process, document everything as carrying and sharing this much context without documents is not possible. You need to have a collaborative first mindset to tackle execution, you will end up picking changes in the systems which are outside your purview, understand the codebase and introduce the changes. You’ll have to collaborate very closely with the teams who own the current systems. Hacky mindset is something this space will demand as you are going to migrate from the current systems to the new ones. You might end up building some custom router/gateway plugins etc to achieve what you want. As the scale and impact is high, always keep in mind to have a rollback even for the slightest change. Adoption is the biggest beast in this whole journey which is very hard to tame and you are going to face a lot of problems in adoption and onboarding as it needs change in the mindset and people have to work with constraints of the new systems. You need to think like a sales person here and sell the outcome and benefits of the new system. Take the ownership of onboarding and can you automate the onboarding process which will bring down the entry barrier significantly. Take some sessions for the users of the new systems on how to use the new systems and what is supported and what is in the roadmap, make them believe in your vision and what the future looks like. Like when we migrated from VMs to kubernetes for all the deployments in Gojek, we took multiple sessions on how the new deployment platform works, how do you debug the failures, how logs are getting shipped etc. This is the place where you show off the capabilities of the new systems over the legacy and how easy it is for users to leverage the new system. Share documentation, demo videos and try to evangelize the adoption as much as you can. ## Conclusion This problem space is quite exciting and lets you wear a different hat at different points in the journey like product, programme manager, engineer, sales etc. It’s quite important for the success of the project that the system is forward looking and will work for the organization for at least next 2-3 years. Understanding the needs of your stakeholders, sponsor of the project and what’s the right product to solve for the current issues is very crucial for success of the project. There might be situations where every stakeholder has different needs but it’s your job as an engineer to do the right thing. --- # Streams in Java By Rahul Patil · 2024-03-05 Canonical: https://www.infraspec.dev/blog/java-streams ## Java Streams: A Paradigm Shift in Data Processing ## What are Streams? Imagine a lazy river carrying data elements one by one. That’s essentially what a stream is – a sequence of elements that you can process on the fly, without storing everything in memory at once. This makes them ideal for handling huge datasets without overwhelming your computer. Scenario: Imagine you have a basket of apples. You want to count all the red apples. Traditionally, you might pick each apple, check its color, and increment a counter if it’s red. This is similar to iterating through a list using a loop. With streams, it’s like having a conveyor belt carrying the apples. You set up a “filter” that only lets red apples through. Then, you have a “counter” that automatically counts each red apple that passes through. You don’t have to touch each apple individually, and you only process the red ones you’re interested in. Let’s break down the magic with some code snippets and explanations: ## 1. Immutability: Ensuring Strong and Safe Code What is Immutability in Streams? Immutability ensures that the original data stays the same during stream operations. With Java Streams, it means making new streams without changing the existing data. How it Benefits: - Predictable Behavior: Immutability helps avoid accidental changes, making sure that one part of the code doesn’t mess up another. - Thread Safety: In places with lots of things happening at once (multi-threaded), immutability acts like a safety net. Many threads can use the original data at the same time without causing problems. Code Snippet and Benchmark Output: ``` // Immutability with Streams List values = Arrays.asList(1, 10, 3, 4, 2); Stream mappedValues = values.stream() .filter(n -> n % 2 == 0) .map(n -> n + 1); List modifiedList = mappedValues.toList(); System.out.println("Original List: " + values); System.out.println("Modified List: " + modifiedList); System.out.println("The above two lists are equal? " + (mappedValues.count() == values.size())); ``` Analysis: - The starting list stays the same; nothing is changed, proving that streams keep things unchanged. - When we filter and map, it’s like making a fresh stream, leaving the original data intact. - Using toList() helps make a new list without messing up anything. It’s like a safety feature for threads. Benchmark Output: ``` Original List: [1, 10, 3, 4, 2] Modified List: [11, 5] Lists Equality: true ``` ## 2. One-Time Use: Ensuring Stream Integrity What is the One-Time Use of Streams? Streams, once consumed, cannot be reused. This design ensures that each stream operation, especially terminal operations, represents a distinct processing step. Once a terminal operation is invoked on a stream, it marks the end of its usability for further operations. How it Benefits: - Efficient Resource Management: When you have a large amount of data, utilizing streams in Java aligns with the practice of processing data and closing resources promptly. This practice helps prevent data leakage and minimizes the presence of unused resources. - Prevention of Unintended Behavior: The inability to reuse streams after terminal operations minimizes the risk of unintended side effects, promoting safer and more controlled data manipulation. Attempting to use a consumed stream again results in an IllegalStateException , ensuring a clear and intentional data processing flow. Code Snippet and Benchmark Output: ``` // Creating a stream from the list Stream mappedValues = list.stream() .filter(n -> n % 2 == 0) .map(n -> n + 1); // Using a terminal operation 'count' long count = mappedValues.count(); // Attempting to reuse the stream will result in an exception try { // This line attempts to reuse the 'mappedValues' stream System.out.println("Reused Stream: " + mappedValues.toList()); } catch (IllegalStateException e) { System.out.println("Error: " + e.getMessage()); } ``` Analysis: - The code begins by creating a stream, mappedValues , from the original list. - The stream is processed with an intermediate operation ( filter and map ) and a terminal operation ( count ). - Attempting to reuse the mappedValues stream (here with toList() ) after the terminal operation will result in an IllegalStateException . This error occurs because once a stream is consumed by a terminal operation, it cannot be reused for another terminal operation. - The use of count() serves as a point of consumption, making the stream no longer available for further terminal operations. Output: ``` Error: stream has already been operated upon or closed ``` ## 3. Parallel Streams: Leveraging Multi Core Power for Performance What are Parallel Streams? Parallel streams divide the workload among multiple threads, leveraging the power of multicore processors for concurrent execution. They are designed for efficient processing of large datasets. How it Benefits: - Reduced Execution Time: Parallel processing leads to shorter execution times compared to sequential streams, especially when dealing with massive datasets. - Optimal Resource Utilization: Multicore processors are fully utilized, making parallel streams ideal for performance optimization. Code Snippet and Benchmark Output: ``` // Populate the list with values for (int i = 0; i < datasetSize; i++) { values.add(random.nextInt(Integer.MAX_VALUE)); } // Parallel Stream Processing long parallelStartTime = System.currentTimeMillis(); values.parallelStream() .sorted() .toList(); long parallelEndTime = System.currentTimeMillis(); long parallelTimeTaken = parallelEndTime - parallelStartTime; System.out.println("\n"); // Sequential Stream Processing long sequentialStartTime = System.currentTimeMillis(); values.stream() .sorted() .toList(); long sequentialEndTime = System.currentTimeMillis(); long sequentialTimeTaken = sequentialEndTime - sequentialStartTime; ``` Scenario 1: Small Dataset (datasetSize = 10) Analysis: - The dataset is deliberately kept small to showcase the impact on performance. - Parallel processing does not demonstrate a significant advantage due to the overhead of managing parallel threads which overshadows the potential advantages. Benchmark Output: ``` Parallel Time Taken: 9 milliseconds Sequential Time Taken: 0 milliseconds ``` Scenario 2: Large Dataset (datasetSize = 1,000,000) Analysis: - Parallel streams potentially perform better when dealing with large datasets. - The process of dividing the work among multiple threads becomes more advantageous for significant workloads. - Multicore processors are utilized optimally, leading to shorter execution times compared to sequential streams. Benchmark Output: ``` Parallel Time Taken: 2318 milliseconds Sequential Time Taken: 7789 milliseconds ``` ## Parallel Stream and Synchronous Resources In Java, the use of parallel streams can significantly improve performance for certain operations. However, when dealing with synchronous resources, such as System.out.println() , the impact of parallel streams is limited. Let’s explore the general concept and illustrate it using an example. ### 1. Synchronous Nature of System.out.println(): - System.out.println() is inherently synchronous and operates in a single-threaded manner. - It’s a blocking operation, printing text to the console one line at a time. - When multiple threads execute println() statements, the output becomes sequential. Example: ``` List list = Arrays.asList(1, 2, 3, 4, 5); // Synchronous output System.out.println("Sequential Stream:"); list.forEach(value -> { System.out.println("Value " + value + " - thread " + Thread.currentThread().getName()); }); ``` ### 2. Limited Impact on Parallel Streams with Synchronous Resources: - Parallel streams are designed to parallelize operations on data. - When using parallel streams with synchronous resources like System.out.println() , parallel processing is applied to the data, but the printing remains sequential. - The synchronous nature of the resource limits the full potential of parallelization. Example: ``` // Limited impact with parallel streams System.out.println("\nParallel Stream:"); list.parallelStream() .forEach(value -> { System.out.println("Value " + value + " - thread " + Thread.currentThread().getName()); }); ``` ### 3. Real Benefits of Parallel Streams: - Parallel streams are most effective for CPU-bound or I/O-bound operations that can be parallelized. - They shine in scenarios where parallelization can significantly improve performance, such as parallelizing CPU-bound or I/O-bound tasks. ## 4. Lazy Evaluation: Optimal Resource Utilization What is Lazy Evaluation in Streams? Lazy evaluation means that operations on a stream are not executed until a terminal operation is invoked. This allows for efficient resource usage by processing only the elements necessary for the final result. How it Benefits: - Efficient Resource Utilization: Elements are processed on-demand, saving processing time and memory. - Suitable for Large Datasets: Laziness ensures that the stream doesn’t process the entire dataset if it’s not required for the final result. Code Snippet and Benchmark Output: ``` // Leveraging Lazy Evaluation List values = Arrays.asList(1, 2, 5, 10, 15); Stream doubleValues = values.stream() .filter(LazyEvaluation::isDivisibleBy5) .map(LazyEvaluation::doubleValue); System.out.println(doubleValues.findFirst().orElse(0)); ``` Analysis: - The stream operations, filter and map , are defined but not immediately executed. - Processing occurs only when the terminal operation findFirst() is invoked. - The lazy nature ensures that only elements needed for the final result are processed, saving resources. - The output demonstrates the selective processing of elements that meet the specified criteria. Output: ``` in isDivisibleBy5 1 in isDivisibleBy5 2 in isDivisibleBy5 5 in doubleValue 5 Result: 10 ``` ## In Summary Using Java Streams goes beyond just syntax – it’s a game-changer in how we handle data. The code snippets we explored dig into the inner workings, showcasing the simplicity, effectiveness, and practical use of Java Streams. Dive into the world of streams, where both imperative and functional approaches blend seamlessly, and watch your Java coding experience evolve. --- # How TDD helps design better software By Chetan Kothari · 2023-01-18 Canonical: https://www.infraspec.dev/blog/tdd-design-benefits Most of us think of TDD as a tool for software testing and verification. But if used effectively it is more than that. Since Test Drive Development (TDD) was introduced by Kent Beck it has always been a bit of a controversial topic. Today we are going to explore what TDD has to offer apart from being a way to test and verify software. Before we dig deeper, let’s take a look back at what is TDD, in the first place. > TDD is a process used to build software in which unit tests are written even before writing any code. As defined above, we write unit tests even before we write the code. This might sound counterintuitive as to how can we test something before it even exists. To make this easier to understand, try to think of it like this. It is not testing but stating what you expect the code to do. With this, you are trying to put your expectation before writing the code. This shift in mindset, helps you be very clear and concise about what you want and how you want your software to behave. Since we don’t have any code to test, this inversion of thought process and development style now poses a few interesting questions: 1. What do we expect from the function and how do we want it to behave? 1. What should be the function/method name? What would make sense from the caller’s perspective? 1. What would be the Class name in the case of Object Oriented language? 1. What does the function need as dependencies for it to perform its task? Let’s see how these questions help us one by one ### Q1: What do we expect from the function and how do we want it to behave? Answering this question helps us to focus on the exact intended outcome before implementing the code. This enables us to break the problem statement into smaller chunks as we need to test for each expectation separately. This helps us build the software incrementally, and discover edge cases by asking how should it work for weird input values. ### Q2: What should be the function name? What would make sense from the consumer perspective? Since we would be having the consumer of the function even before it is implemented, it forces us to think of a good function name. This helps us in understanding how different pieces of code will use this new function. This significantly improves readability and guides us to arrive at meaningful names. ### Q3: What would be the Class name in case of Object Oriented language? Naming as we all know is one of the hardest things for software engineers. One thing I have realised over the years is naming in a meaningful manner only takes iterations. But one easy way to get started in the right direction is to name things from the consumer’s point of view. What this means is when we start to think from the consumer’s point of view, it starts becoming clear as to how it could be used. And test cases are the first consumers of the code. This like the previous one helps us improve readability ad arrive at meaningful class names. ### Q4: What does the function/class need as dependencies for it to perform the task? When we write code, we sometimes expect certain things to be present or need to be passed in for the new code to work. This helps us understand how complicated the code setup could be if it needs a lot of things. This acts as an indicator and surfaces tight coupling if any early on in the development lifecycle. We could consider this as a tool which would prevent the design of the system from having high coupling and reduce complexity. > TDD is not just about having tests but a lot more than that. It not only helps us verify the correctness of the software but if practised well, helps us design the software well. This is why I sometimes think of TDD as Test Driven Design All of this sounds too good, but it’s easier said than done. Here is one of the many reasons why people are not able to successfully adopt this practice into their development lifecycle. Not treating this as any other skill and not giving it enough time. Like any other skill, TDD is also a skill which needs some learning. But what I have observed is people don’t give it enough time or practice it enough to be able to master this skill. This leads to some of the most obvious pushback of it taking longer than just writing code. We are going to be slow in anything we don’t know, not just TDD. Only spending enough time with any skill will make us move faster. Be it learning a new programming language, playing a new musical instrument or learning to drive. > To conclude, TDD could be used to improve the overall design of the system instead of just using it to increase code coverage. --- # k3s cluster on Raspberry Pi's By Rajat Tomar · 2023-01-02 Canonical: https://www.infraspec.dev/blog/lightweight-k3s-cluster-raspberry-pi As a developer at Infraspec, I am responsible for managing internal tooling and ensuring the smooth operation of local tooling and network services in our office. We had a cluster of Raspberry Pi devices available and saw an opportunity to utilize them by setting up a Kubernetes cluster. This allowed us to cost-effectively utilize our existing hardware and avoid the expense of purchasing additional infrastructure. However, we recognized that configuring a full Kubernetes cluster on resource-constrained devices like Raspberry Pis could be challenging. To mitigate these difficulties, we chose to use k3s, a lightweight version of Kubernetes optimized for edge computing and Internet of Things (IoT) environments. To automate the process, we used Ansible to set up the k3s cluster and GitHub Actions to deploy services on top of it. In this blog, I want to share my learnings and a step-by-step configuration setup to provision a lightweight k3s cluster on Raspberry Pis. ### 1. Our Hardware Setup ![My Collection](https://www.infraspec.dev/images/blog/lightweight-k3s-cluster-raspberry-pi/collection.png) - We used 6 Raspberry Pis in total, including: 3 Raspberry Pi 4’s with 4GB of RAM 1 Raspberry Pi 4 with 8GB of RAM 2 Raspberry Pi 4’s with 2GB of RAM These Raspberry Pi’s were used as data nodes in our k3s cluster. - For the control plane, we used an [ODROID-H2](https://www.hardkernel.com/shop/odroid-h2/) which had: 32GB of RAM 500GB SSD - We also used a [NETGEAR GS310TP 8 Port POE Switch](https://www.netgear.com/support/product/GS310TP.aspx#docs) , which allowed us to pass both electric power and data along the same twisted-pair Ethernet cabling, making it easier to set up and power multiple devices at once. If you want to know more about Power over Ethernet (PoE), check out this [whitepaper](https://www.saelig.com/supplier/amplicon/PoE-white-paper.pdf) . Our hardware setup was sufficient for running a k3s cluster for our internal tooling, although it may not have been top-of-the-line. The [ODROID-H2](https://www.hardkernel.com/shop/odroid-h2/) had enough RAM and SSD storage to serve as the control plane. Although the hardware specifications may not be impressive, they were adequate for our needs. It’s important to note that reliability was not a primary concern for our setup, as we were primarily focused on using available resources efficiently. ### 2. Setup Raspberry Pi headless To use Raspberry Pis as nodes in our k3s cluster we need to set up Raspberry Pi headless, which means we will not be using a monitor, keyboard, or mouse. Instead, we will be using SSH to connect to the Raspberry Pi and configure it remotely. Headles setup doesn’t have GUI attached to it. ![Choose OS](https://www.infraspec.dev/images/blog/lightweight-k3s-cluster-raspberry-pi/choose_os.png) ![Choose Storage](https://www.infraspec.dev/images/blog/lightweight-k3s-cluster-raspberry-pi/choose_storage.png) - Download and install the Raspberry Pi Imager on your computer. You can find it on the official Raspberry Pi website or ``` sudo apt install rpi-imager ``` 1. Open the Raspberry Pi Imager and select the “CHOOSE OS” option. - From the list of available operating systems, select “Raspberry Pi OS (other)”, and then choose “Raspberry Pi OS Lite (64-bit)” and click “CHOOSE STORAGE”. 1. Select the SD card you want to use for your Raspberry Pi and click on the gear icon to configure Raspberry Pi. ![Selectl SD Card](https://www.infraspec.dev/images/blog/lightweight-k3s-cluster-raspberry-pi/select_sd_card.png) ![Configure Pis](https://www.infraspec.dev/images/blog/lightweight-k3s-cluster-raspberry-pi/configure_pis.png) ![Write Image](https://www.infraspec.dev/images/blog/lightweight-k3s-cluster-raspberry-pi/write_image.png) ![Office Setup](https://www.infraspec.dev/images/blog/lightweight-k3s-cluster-raspberry-pi/office_setup.png) - Set up a unique hostname for every Raspberry Pi, like knode1 , knode2 , knode3 , etc for each node. Activate ssh with password authentication and pass in your ssh credentials. It is recommended to provide the same username and password to all the Raspberry Pis as it becomes easier to run ansible on all the nodes. - Next, click “WRITE” and note that this will clear all the existing data on the SD card. Wait for the image to be written to the SD card. This may take a while, so grab a cup of tea and relax. 1. Once the image has been written, eject the SD card and insert it into your Raspberry Pi. - Next, connect your Raspberry Pi to your router using Ethernet cables, and make sure to attach a power source. I’m using a [NETGEAR GS310TP 8 Port POE Switch](https://www.netgear.com/support/product/GS310TP.aspx#docs) , which allows me to pass both electric power and data along the same twisted-pair Ethernet cabling. This makes it easier to set up and power multiple devices at once. Note that, we’ll continuously be working on improving our setup, and booting Raspberry Pis from network is one of the things we’ll be working on in next iteration. Once it’s done, we’ll update this blog. ### 3. Setup ODROID-H2 We installed Ubuntu Server on ODROID-H2. Ubuntu Server, is an operating system for a server machine based on Ubuntu. It is a stripped-down version of the Ubuntu Desktop, shipped with the necessary tools to set up and maintain a server machine. We used [balenaEtcher](https://www.balena.io/etcher/) to boot SD card with Ubuntu Server to install it on ODROID-H2. Configure ODROID-H2 to allow SSH connection and set hostname to kmaster . ### 3. Setup k3s Cluster To automate the process of setting up our Kubernetes cluster, I wrote ansible playbooks to handle the configuration and deployment of the cluster. These playbooks allowed us to easily set up and manage our cluster and streamline the process of deploying applications on it. If you have used ansible before, you may already be familiar with the concept of an inventory. The simplest inventory is a single file with a list of hosts and groups. In my case, Here’s my inventory.yaml to define the specific hosts or nodes that I wanted to run my playbook tasks on. ``` k3s_cluster: children: control_plane: hosts: kube-control-01: ansible_user: my_user ansible_host: 192.168.0.10 ansible_python_interpreter: /usr/bin/python3 k3s_control_node: true data_plane: hosts: kube-data-01: ansible_user: another_user ansible_host: 192.168.0.11 ansible_python_interpreter: /usr/bin/python3 kube-data-02: ansible_user: another_user ansible_host: 192.168.0.12 ansible_python_interpreter: /usr/bin/python3 kube-data-03: ansible_user: another_user ansible_host: 192.168.0.13 ansible_python_interpreter: /usr/bin/python3 kube-data-04: ansible_user: another_user ansible_host: 192.168.0.14 ansible_python_interpreter: /usr/bin/python3 kube-data-05: ansible_user: another_user ansible_host: 192.168.0.15 ansible_python_interpreter: /usr/bin/python3 kube-data-06: ansible_user: another_user ansible_host: 192.168.0.16 ansible_python_interpreter: /usr/bin/python3 ``` This ansible inventory defines a group called k3s_cluster with two child groups: control_plane and data_plane . The control_plane group contains a single host called kube-control-01 , which is specified with its ansible_user , ansible_host , and ansible_python_interpreter variables. The data_plane group contains six hosts, each of which is specified with the same variables as the control_plane host. The ansible_user variable specifies the username that ansible should use to connect to the host. The ansible_host variable specifies the IP address or hostname of the host. The ansible_python_interpreter variable specifies the path to the python interpreter on the host, which is used by ansible to execute tasks on the host. The k3s_control_node variable in the kube-control-01 host is a custom variable that specifies that this host is a control plane node in the k3s cluster. This variable can be used by ansible tasks and templates to customize the behavior of the role for control plane nodes. Note that reliability is not our concern here, so we are not using a highly available control plane, so we’ve used a single control plane node. Overall, this ansible inventory defines a group of hosts that can be used to set up a k3s cluster, with a single control plane node and multiple data plane nodes. It specifies the necessary connection and authentication details for each host, as well as any custom variables that may be needed by ansible tasks and templates. I used [PyratLabs/ansible-role-k3s](https://github.com/PyratLabs/ansible-role-k3s) which helps automate the process of provisioning a k3s cluster. It provides a set of ansible tasks and templates that can be used to install and configure k3s on a set of nodes. Now, to use the [PyratLabs/ansible-role-k3s](https://github.com/PyratLabs/ansible-role-k3s) role in our playbook, we first added it to our requirements.yaml file. This allowed us to specify the role as a dependency for our playbook and ensured that it would be installed and configured correctly. The syntax for adding a role to the requirements.yaml file looks like this: ``` roles: - name: xanmanning.k3s src: https://github.com/PyratLabs/ansible-role-k3s.git version: v3.3.0 ``` Once we had added the role to the requirements.yaml file, we run the command to install the role and its dependencies. ``` ansible-galaxy install -r requirements.yaml ``` This downloaded and installed the role from the specified repository, making it available for use in our playbook. To use the role in our playbook site.yaml , we included it in the list of roles to be executed, like this: ``` - hosts: k3s_cluster gather_facts: yes become: true vars: k3s_become: true ansible_host_key_checking: false roles: - role: xanmanning.k3s ``` This playbook contains a single role called xanmanning.k3s , which is responsible for installing and configuring k3s on the hosts in the k3s_cluster group. Once you have Ansible installed, you can use the following command to apply the playbook: ``` ansible-playbook -i inventory.yaml site.yaml --extra-vars "ansible_sudo_pass=YOUR_PASSWORD" ``` This command will apply the playbook defined in site.yaml to the hosts defined in inventory.yaml . The --extra-vars flag is used to pass extra variables to the playbook at runtime. In this case, the ansible_sudo_pass variable is being set to YOUR_PASSWORD . This variable will be used by the playbook tasks to specify the password that should be used when running tasks that require sudo privileges. By running this playbook, we will be able to provision a k3s cluster on the specified hosts using Ansible. ### Key Takeaways One of the key takeaways from this project was the importance of automating the process of setting up this Kubernetes Cluster. By using ansible playbooks, I was able to streamline the configuration and deployment of the cluster, making it easier to set up and manage. If I had chosen to go the manual route of setting up a k3s cluster, rather than using automation tools like Ansible, the process would likely have been much more time-consuming and prone to errors. Another learning was the value of using a lightweight version of Kubernetes like k3s, which is specifically designed for edge computing and IoT scenarios. This allowed me to set up a cost-effective and efficient cluster that was well-suited for my needs. --- # Is DNS migration a tricky affair? 2022-12-15 Canonical: https://www.infraspec.dev/blog/is-dns-migration-a-tricky-affair Never trust a friend who says DNS migration is easy. Your instinct says it’s easy, well don’t trust your instinct. In this post, I will be sharing my experience with one such encounter with DNS migration from GoDaddy to Route53. Before starting, if you are here because of the catchy title and have no idea of what DNS is, or you are one of my many (zero) followers or need to brush up your knowledge on DNS, please refer to these resources: 1. [What is DNS - Cloudflare](https://www.cloudflare.com/learning/dns/what-is-dns/) 1. [Deep Dive on DNS - IETF](https://www.youtube.com/watch?v=DV0q9s94RL8) I won’t keep you waiting any longer - I will start my story and explain the reason for my introductory lines. ## Need for DNS migration One of our clients wanted us to move their workload from Docker Swarm to Amazon ECS. Earlier, they were using HaProxy to load-balance the traffic. This setup also included generation and installation of SSL certificates using in-house scripts, which the client needed to maintain. Since we were moving to ECS, ALB and ACM felt like an obvious choice. In order for ACM to auto-renew expiring SSL certificates, we decided to use Route53 as the DNS service, ditching GoDaddy’s DNS service. BTW, if you are curious, the domain was registered with GoDaddy and hence their DNS service. These decisions landed us onto the supposedly EASY task of DNS migration. This was my first DNS migration task, and I was equally afraid as I was excited. Just then, I overheard someone (friend/colleague) saying with a very convincing tone that DNS migration is an easy task. Well, I was somewhat convinced. 😅 Still, as a good engineer 🤭, I went ahead and did my research regarding DNS migration and carved out a migration plan. Looking at the plan for migration, even my instincts were convinced. ![Instinct calling](https://www.infraspec.dev/images/blog/is-dns-migration-a-ticky-affair/do_it.gif) ## Migration Plan Basically I divided the migration plan in three phases along with a rollback strategy: ### Pre-execution phase In this phase we exported the [zone file](https://en.wikipedia.org/wiki/Zone_file) from GoDaddy DNS service which we will be referring to for the list of domain records to migrate. Another thing we did was to reduce the [TTL](https://www.cloudflare.com/learning/cdn/glossary/time-to-live-ttl/) of all the records in GoDaddy DNS to the least possible value. These tasks we performed a day before the execution phase. Why one day before execution? We looked at the TTL values of all the records and the maximum value we found was 86400 (seconds), which translates to 24 hours. We wanted to let all the clients(browsers) using our application to make the query to the new DNS service as soon we make the switch. For this to happen, it was important to expire the cached results containing information of old DNS service. Since maximum cache duration was 24 hours, we updated TTL to least possible values and waited for old cache to expire. ### Execution Phase This phase included changes at Route53’s end. This included: 1. Addition of hosted zone in Route53 for the [apex domain](https://www.isc.org/blogs/cname-at-the-apex-of-a-zone/) 1. Addition of all the records we have in the zone file to Route53 hosted zone we just created. - Update the nameserver records provided by Route53 in the domain registration configuration. This will switch the DNS service to Route53 once the TTL is expired. We actually used [Terraform](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/route53_record) to add the hosted zone as well as other records, as this would ease up the maintenance of the records. ### Verification Phase This phase included verification of DNS records of our application and mail servers. One way to verify this is by simply heading to the application domain for verifying the application and sending a mail to the colleague for verifying the working of mail server. This can be considered as a correct way to verify since we have taken care of the TTL but this does not clarify who is serving the records - GoDaddy’s DNS service or Route53. To make sure the DNS query result is being served by Route53 nameservers we have to make use of a linux utility called - ![dig](https://www.infraspec.dev/images/blog/is-dns-migration-a-ticky-affair/dig.gif) ``` $ dig -t NS my-cool-domain.in ``` The output should be similar to this ![dig_ns_output](https://www.infraspec.dev/images/blog/is-dns-migration-a-ticky-affair/dig_ns_output.png) The response should have the Route53 nameservers and NOT the GoDaddy DNS nameservers. This validates that all the future queries for our domain/subdomain will be served by Route53. ### Rollback Strategy There can be scenarios where the migration may go wrong, and it may take time for debugging the issue and the fix may take time. In such cases, we can revert to the old DNS service with a simple change (assuming that the records are not cleaned up from the old service). We only need to replace the Route53 nameservers with the old nameservers in the Domain Registrar. ## D-Day ![me crying](https://www.infraspec.dev/images/blog/is-dns-migration-a-ticky-affair/bug.gif) It was this day (and a few of my colleagues 😝) that compelled me to write this blog. We proceeded as per our well-thought-out plan ( at-least what we believed it to be ), everything worked well…until the verification phase. We were not able to send/receive emails and the application was down. Furthermore, we verified using dig as mentioned in the verification phase, and it was returning the Route53 nameservers as expected. This GIF can express what I was like that day. Others in my team were trying to console me by showing tweets of failed DNS migrations and how common this is. Just kidding!! They were like ![panicing](https://www.infraspec.dev/images/blog/is-dns-migration-a-ticky-affair/panic.gif) Well, this is a bit exaggerated. ## Troubleshooting ![troubleshooting](https://www.infraspec.dev/images/blog/is-dns-migration-a-ticky-affair/troubleshooting.gif) With the verification using dig, we were sure that migration did happen and DNS had migrated to Route53. This eliminated the chance of issue in nameserver configuration at the domain registrar end. Next we moved to Route53 to check the domain records for the email server and application. It was at this point we noticed something unusual. When we copied the records from the zone file exported from GoDaddy DNS service, we copied the name of the records as it is. In a lot of DNS services “@” is used to represent the apex domain i.e. my-cool-domain.in . We assumed it to be the same for Route53 as well and applied the changes. This led to creation of subdomain @.my-cool-domain.in in Route53. As a result of this, all the record types (A, MX and CNAME) with apex domain my-cool-domain.in were not being returned in DNS query answers by Route53. Later we figured out that in Route53 to create a record with the apex domain we need to give the full name of the domain i.e. my-cool-domain.in or leave it blank. Luckily, we identified the issue quickly and the fix was not big, so we fixed the issue instead of reverting. This is where reducing the TTLs to lower values paid off. The fix was applied within a minute . ## Further Verification Since our migration plan failed at the verification phase, we realized that we need to add more verification steps. We realized that we could have verified the records that will be served by Route53 nameservers even before making the switch. This is made possible by our good old friend - dig ``` $ dig @ns1.route53-nameserver.com -t MX my-cool-domain.in ``` This command will return all the MX records for my-cool-domain.in being served by ns1.route53-nameserver.com nameserver. If the record is not present in the response, that would mean that we made some mistake while adding the domain/subdomain in Route53. We can use it to check for other record types as well. The command below can also be used to get the difference in records returned by two nameservers. This will give us the missing/different records in just a single execution. ``` $ diff <(sort -u <(dig +nocmd +noall +answer +nottlid @ns1.old-nameserver.com example.com ANY)) <(sort -u <(dig +nocmd +noall +answer +nottlid @ns1.new-nameserver.com example.com ANY)) ``` Once we are satisfied with this verification, we can comfortably switch the nameserver in domain registrar configuration and continue the verification phase mentioned in the original plan. With all this successfully completed, we can go ahead and clean up the records from the GoDaddy DNS service. ## What do we learn? Now, it’s time to answer the question - Is DNS migration a tricky affair? Well from my experience, DNS migration seems to be easy if looked from the technical process. All we need to do is follow carefully curated steps and verify the result after every step. From a business standpoint, DNS migration can prove to be tricky as most of the businesses nowadays use the internet in one form or the other. Losing access to your emails, or your customers unable to access your websites/ applications, can lead to huge financial losses. So yes, DNS migration can be tricky affairs if executed without careful planning. To close this post on a lighter note - I am still looking for that friend/colleague. If you are reading this - ![I_will_find_you](https://www.infraspec.dev/images/blog/is-dns-migration-a-ticky-affair/i_will_find_you.gif) --- # Office/Home Lab Internet Failover Setup By Arihant Hirawat · 2022-12-15 Canonical: https://www.infraspec.dev/blog/office-home-lab-internet-failover-setup An overview of how to set up internet failover for an office or home lab. We started working out of our Infraspec office last year. To start with we had a broadband connection from ACT. It worked fine till it didn’t. One fine day, few people on call started complaining that their calls were getting dropped. On checking, we found that our internet went down. We raised a complaint and but nothing would get fixed immediately. This incident got us to think more about our internet reliability. We also have our internal workloads running on Raspberry PIs, so it is important for us to get reliable internet connectivity to run efficiently. This led to get another internet connection(Airtel) which we can use as a backup connection. Now we have got two wireless connections, If one goes down we can just manually switch to another. However, this does require some manual effort. We needed a cost-effective way where if the primary connection(which is ACT for our case due to high network bandwidth) goes down, it could auto-switch (or failover) to the secondary backup connection(Airtel) and restores back to the primary connection once it regains its connectivity. This led to think about failover/multi-WAN setup. ## Overview - Two ISP connections (primary and secondary) - Failover setup (not load balancing) - Quick switching time between ISPs - Clients should be part of a single network (IPs allocated from a single DHCP server) ## Context ![Failover Setup](https://www.infraspec.dev/images/blog/office-home-lab-internet-failover-setup/failover-setup.png) Few routers provide the flexibility to configure individual Ethernet ports. By default, out of all the available ports, either one/two is configured as the WAN port and the others are configured as LAN ports. This allows you to connect your WAN connection to the WAN ports and use the remaining LAN ports to connect devices on your office network. You can also configure the Ethernet ports in different ways, such as configuring multiple ports as WAN ports for a multi-WAN setup. This would allow you to connect a second Internet source, such as a second broadband modem to the router and use it as a redundant WAN connection. You can then configure the router to use both WAN connections and switch between them if one of the connections fails. This can help to provide a more reliable and resilient Internet connection for your Office/Home lab. > Note : Not all routers allow the conversion of LAN ports to WAN ports. If your router does not have this option, you will need to use a different router or a network switch to create a WAN port. Some routers also come equipped with multiple WAN ports that can be used as well for failover in case one of the connections fails. ### How we go about setting up the internet failover The process to set up internet failover may vary depending on our specific setup and needs, but generally, we will need to follow these steps: - Identify the primary and secondary internet connections that you will use for failover. In our case, We are using ACT as our primary as I mentioned due to its high bandwidth and Airtel as our secondary connection. 1. Configure your network router or network switch to use the primary internet connection as its default gateway. 1. Configure the secondary internet connection as a backup gateway in your router or switch. 1. Test the failover by disconnecting the primary internet connection and verifying that the secondary connection is used automatically. ### The configurations to manage We can manage router configurations by login to the router’s web-based configuration page. This can typically be done by entering the router’s IP address (such as 192.168.1.1 ) in a web browser. The configurations will vary with the router you have, here we will take an overview of the process we need to follow to manage the router’s configuration. #### 1. Configure WAN/LAN as a WAN port ![LAN port configured as WAN](https://www.infraspec.dev/images/blog/office-home-lab-internet-failover-setup/lan-configured-as-wan.png) - Our router had only one WAN port, We need to convert one of its LAN port to a WAN port as we need two internet sources. - Once we have accessed the router’s configuration page, look for a section on bridging or port forwarding. From here, you should be able to remove the port from the bridge by selecting the port and choosing the option to remove it. Now this second port (eth2 in our case) can be used as another WAN port. - By default, the LAN ports are configured as a single network, with all the ports being part of a single bridge. Now that we have two WAN ports/interfaces (eth1 & eth2) ready to act as our internet sources, the next step is to configure DHCP Clients for these ports. #### 2. Setup DHCP client - Plug in the ISP cables to both the WAN interfaces we just configured in the above step. - In the network settings, We need to enable the DHCP client and configure the network settings. - After the DHCP client has been configured, the device should be able to automatically obtain an IP address from the DHCP server on the network. Each ISP has its own DHCP server, the router acts as a DHCP client for each ISP connection. This would allow the router to obtain IP address information from each ISP and use that information to route traffic appropriately. This blog is written considering dynamic IP assignments only. #### 3. Configure routes - Now we need to configure the routes for our primary and the secondary internet connection, For that find the settings for the routing table, which is typically found in the advanced settings or network settings section of the router’s configuration page. - Check the default configured static routes, else create two default routes for the primary and the secondary internet connection. Then configure the gateway address and WAN interface to it. - Then we need to specify the route distance for each WAN connection by assigning a value to each WAN connection. The lower the value, the higher the priority of the connection. For example, if you have two WAN connections, you might assign a value of “1” to the primary connection and a value of “2” to the secondary connection. This will ensure that the primary connection is used whenever possible, and the secondary connection is only used if the primary connection is unavailable. #### 4. Setting up the DHCP Server - We need to have uninterrupted connection for all our devices in the office network. Instead of using the ISP’s DHCP servers (both will provide different IPs from different pools), we will be setting up our own DHCP server which will be providing IPs from a single IP pool. - This DHCP server will be assigning IPs to all the devices connected to the LAN bridge. Till now all the connections are wired, and we need to provide a wireless access point to which the clients (devices) will be able to connect wireless. The Access Point is connected to one of the LAN ports and since it is part of the bridge network, all the devices connected via access point will be assigned the IP from our DHCP server instead of ISPs. #### 5. Testing our setup - Although there are a lot of tools available to simulate network failures, we chose a simpler approach to test the working of our setup. - Router provides us with the capability to disable the physical ethernet interfaces. To simulate the network failure on the primary ISP, we disabled the ethernet port. Within a few seconds, we should see the secondary/ failover connection kick in and the internet traffic flowing through it. - Once we enable the primary connection port again, we should see that the traffic again is directed through the primary ISP. ## Conclusion In this article, We had an overview on how to go about setting up the office/home lab internet failover connection. We discussed configuring WAN interface, setting and configuring the DHCP client and server, and finally we looked at testing our setup. In the next part, We will set up the internet failover in MicroTik hex series router which is the one we have used at our office. --- # Setting up Ingress on EKS By Rajat Tomar · 2022-11-30 Canonical: https://www.infraspec.dev/blog/setting-up-ingress-on-eks > Note : Everything here applies to [Amazon Elastic Kubernetes Service (EKS)](https://aws.amazon.com/eks/) . If you are running on another cloud, on-prem, with minikube, or something else, these will be slightly different. ## What is an Ingress? An Ingress in Kubernetes provides external access to your Kubernetes services. You configure access by creating a collection of routing rules that define which requests reach which services. This lets you consolidate your routing rules into a single resource. For example, you might want to send requests to [[mydomain.com/](http://example.com/api/v2)](http://example.com/api/v1) api1 to the api1 service, and requests to mydomain.com/ api2 to the api2 service. With an Ingress, you can easily set this up without creating a bunch of LoadBalancers or exposing each service on the Node. An Ingress provides the following: - Externally reachable URLs for applications deployed in Kubernetes clusters - Name-based virtual host and URI-based routing support - Load Balancing rules and traffic, as well as SSL termination ## Kubernetes Service types – an overview ### ClusterIP A ClusterIP service is the default service. It gives you a service inside your cluster that other apps inside your cluster can access. There is no external access. ![ClusterIP](https://www.infraspec.dev/images/blog/setting-up-ingress-on-eks/cluster-ip.png) The YAML for ClusterIP service looks like this: ``` apiVersion: v1 kind: Service metadata: name: nginx-service namesapce: default spec: selector: app: nginx type: ClusterIP ports: - name: http port: 80 targetPort: 80 protocol: TCP ``` Create the service: ``` $ kubectl apply -f nginx-svc.yaml service/nginx-service created ``` Check it: ``` $ kubectl get svc nginx-serice NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE nginx-service ClusterIP 172.20.54.138 80/TCP 38s ``` ### NodePort A NodePort service is the most primitive way to get external traffic directly to your service. NodePort, as the name implies, opens a specific port on all the Nodes (the VMs), and any traffic that is sent to this port is forwarded to the service. When we create a Service of type NodePort, Kubernetes gives us a nodePort value. Then the Service is accessible by using the IP address of any node along with the nodePort value. In other words, when a user sets the Service type field to NodePort, the Kubernetes master allocates a static port from a range, and each Node will proxy that port (the same port number on every Node) into our Service. ![NodePort](https://www.infraspec.dev/images/blog/setting-up-ingress-on-eks/node-port.png) The YAML for NodePort service looks like this: ``` apiVersion: v1 kind: Service metadata: name: nginx-service namespace: default spec: selector: app: nginx type: NodePort ports: - name: http port: 80 targetPort: 80 nodePort: 30036 protocol: TCP ``` The nodePort parameter here is optional, added here just for an example. Without it, Kubernetes will allocate a port from the 30000-32767 ports range. Create the service: ``` $ kubectl apply -f nginx-svc.yaml service/nginx-service created ``` Check it: ``` $ kubectl get svc nginx-service NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE nginx-service NodePort 172.20.54.138 80:30036/TCP 40s ``` Please keep in mind that it will work as long as the node is reachable via its IP addresses. In most cases, the worker nodes reside in our private network(like office networks or private VPC). In such cases, we can not access the NodePort service from the Internet. ### LoadBalancer A LoadBalancer service is the standard way to expose a service to the internet. In case of AWS – will create an AWS Load Balancer, by default Classic type, which will proxy traffic to all ЕС2 instances of the TargetGroup tied to this Load Balancer, and then via NodePort Service – to all the pods. LoadBalancer type provides a Public IP address or DNS name to which the external users can connect. The traffic flows from the LoadBalancer to a mapped service on a designated port, which eventually forwards it to the healthy pods. Note that LoadBalancers doesn’t have a direct mapping to the pods. ![LoadBalancer](https://www.infraspec.dev/images/blog/setting-up-ingress-on-eks/load-balancer.png) The YAML for LoadBalancer service looks this: ``` apiVersion: v1 kind: Service metadata: name: nginx-service namespace: default spec: selector: app: nginx type: LoadBalancer ports: - name: http port: 80 ``` Apply it: ``` $ kubectl apply -f nginx-svc.yaml service/nginx-service created ``` Check: ``` $ kubectl get svc nginx-service NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE nginx-service LoadBalancer 172.20.54.138 ac8415de24f6c4db9b5019f789792e45-443260761.ap-south-1.elb.amazonaws.com 80:30968/TCP 1h ``` So, the LoadBalancer service type: - will provide external access to pods - will provide a basic load-balancing to pods on different EC2 - will give an ability to terminate SSL/TLS sessions - doesn’t support level-7 routing The big downside is that each service you expose with a LoadBalancer will get its own IP address, and you have to pay for a LoadBalancer per exposed service, which can get expensive! ## Ingress Unlike all the above examples, Ingress is actually NOT a dedicated Service. Instead, it sits in front of multiple services and act as a “smart router” or entrypoint into your cluster. It just describes a set of rules for the Kubernetes Ingress Controller to create a Load Balancer, its Listeners, and routing rules for them. An Ingress does not expose arbitrary ports or protocols. Exposing services other than HTTP and HTTPS to the internet typically uses a service of type [Service.Type=NodePort](https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport) or [Service.Type=LoadBalancer](https://kubernetes.io/docs/concepts/services-networking/service/#loadbalancer) . ![Ingress](https://www.infraspec.dev/images/blog/setting-up-ingress-on-eks/ingress.png) ![Ingress managed LB](https://www.infraspec.dev/images/blog/setting-up-ingress-on-eks/ingress-managed-lb.png) image source: https://kubernetes.io/docs/concepts/services-networking/ingress/ In order for the Ingress resource to work, the cluster must have an ingress controller running. Only creating an Ingress resource has no effect. An [Ingress controller](https://kubernetes.io/docs/concepts/services-networking/ingress-controllers) is responsible for fulfilling the Ingress, usually with a load balancer, though it may also configure your edge router or additional frontends to help handle the traffic. In this example, we’ll use the Nginx Ingress Controller: Install: ``` $ kubectl apply -f ``` Output: ``` namespace/ingress-nginx created serviceaccount/ingress-nginx created clusterrole.rbac.authorization.k8s.io/ingress-nginx created clusterrolebinding.rbac.authorization.k8s.io/ingress-nginx created role.rbac.authorization.k8s.io/ingress-nginx created rolebinding.rbac.authorization.k8s.io/ingress-nginx created service/ingress-nginx-controller-admission created service/ingress-nginx-controller created deployment.apps/ingress-nginx-controller created validatingwebhookconfiguration.admissionregistration.k8s.io/ingress-nginx-admission created serviceaccount/ingress-nginx-admission created clusterrole.rbac.authorization.k8s.io/ingress-nginx-admission created role.rbac.authorization.k8s.io/ingress-nginx-admission created rolebinding.rbac.authorization.k8s.io/ingress-nginx-admission created job.batch/ingress-nginx-admission-create created job.batch/ingress-nginx-admission-patch created ``` Pre-flight check A few pods should start in the ingress-nginx namespace: ``` $ kubectl get pods --namespace=ingress-nginx ``` After a while, they should all be running. The following command will wait for the ingress controller pod to be up, running, and ready: ``` $ kubectl wait --namespace ingress-nginx \ --for=condition=ready pod \ --selector=app.kubernetes.io/component=controller \ --timeout=120s ``` This has set up the Nginx Ingress Controller. Now, we can create Ingress resources in our Kubernetes cluster and route external requests to our services. Let’s do that. ### Creating a Kubernetes Ingress First, let’s create two services to demonstrate how the Ingress routes our request. We’ll run two web applications that output a slightly different response. ``` apiVersion: v1 kind: Pod metadata: name: apple-app labels: app: apple spec: containers: - name: apple-app image: hashicorp/http-echo args: - "-text=apple" --- apiVersion: v1 kind: Service metadata: name: apple-service spec: selector: app: apple type: NodePort ports: - port: 5678 # Default port for image ``` ``` apiVersion: v1 kind: Pod metadata: name: banana-app labels: app: banana spec: containers: - name: banana-app image: hashicorp/http-echo args: - "-text=banana" --- apiVersion: v1 kind: Service metadata: name: banana-service spec: selector: app: banana type: NodePort ports: - port: 5678 # Default port for image ``` Create the resources ``` $ kubectl apply -f apple.yaml $ kubectl apply -f banana.yaml ``` Now, declare an Ingress to route requests to /apple to the first service, and requests to /banana to second service. ``` apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: example-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: / spec: rules: - http: paths: - path: /apple pathType: Prefix backend: service: name: apple-service port: number: 5678 - path: /banana pathType: Prefix backend: service: name: banana-service port: number: 5678 ``` Here we set two rules: if URI == /apple or /banana – then send the traffic to the apple-service or banana-service accordingly. Deploy it: ``` $ kubectl apply -f ingress.yaml ``` Another example is the hostname-based routing. Update the manifest: ``` apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: example-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: / spec: rules: - host: apple.banana.com http: paths: - path: /apple pathType: Prefix backend: service: name: apple-service port: number: 5678 - path: /banana pathType: Prefix backend: service: name: banana-service port: number: 5678 ``` The Ingress controller provisions an implementation-specific load balancer that satisfies the Ingress, as long as the Services ( apple-service , banana-service ) exist. When it has done so, you can see the address of the load balancer at the Address field. Name based virtual hosting Name-based virtual hosts support routing HTTP traffic to multiple host names at the same IP address. ![Name based virtual hosting](https://www.infraspec.dev/images/blog/setting-up-ingress-on-eks/name-based-virtual-hosting.png) image source: https://kubernetes.io/docs/concepts/services-networking/ingress/#name-based-virtual-hosting The following Ingress tells the backing load balancer to route requests based on the Host header. ``` apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: example-ingress spec: rules: - host: apple.service.com http: paths: - pathType: Prefix path: "/" backend: service: name: apple-service port: number: 5678 - host: banana.service.com http: paths: - pathType: Prefix path: "/" backend: service: name: banana-service port: number: 5678 ``` Here we left Services without changes, but in the Rules, we set that a request to the [apple.service.com](http://apple.service.com) must be sent to the apple-service and [banana.service.com](http://banana.service.com) to the banana-service. ## Summary A Kubernetes Ingress is a robust way to expose your services outside the cluster. It lets you consolidate your routing rules to a single resource, and gives you powerful options for configuring these rules. “That’s all folks!” --- # Container Networking Deep Dive - Part 3 By Arihant Hirawat · 2022-11-21 Canonical: https://www.infraspec.dev/blog/container-networking-deep-dive-p3 In part 3 of this series, we will see how containers running on the host communicates with the outside world i.e., the internet > Note : This article is continuation of [part 2](/blog/container-networking-deep-dive-p2/) , We recommend you to first go through part 2 and then come back to this. ## Topics to be covered 1. Try to connect containers to the internet 1. We will understand about NAT, ip forwarding and iptables 1. Configure ip forwarding and iptables rules to connect containers to the internet ## Try to connect containers to the internet In [part 2](/blog/container-networking-deep-dive-p2/) , we had multiple containers running which were able to communicate with each other and the host as shown below. ![Multiple container attached to linux bridge](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p2/containers-attached-to-bridge.png) But when we try to connect containers to the internet, it was unsuccessful. ![Ping internet](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p2/ping-internet.png) What exactly is happening and what could be the reason that containers are not able to connect to the internet? We know that for every request we send to the internet, the destination server sends back response in order for the ping to be successful. In this case, the destination server is not able to send packets back to the containers as the container’s ip address is private. Our containers are assigned private IPs in the range 172.16.0.0/24. A lot of devices or the containers in this world can have this ip address range. Then how will the destination server know to whom to send the response back. This is where network address translation(NAT) and iptables comes to help. ## NAT and iptables In NAT, any packets originated from the containers, and going to the external network, the packets source ip is replaced by the host’s external interface address. The host also keep track of this, and on arrival it will be restoring the ip address before forwarding the packet to the containers. This can be achieved by adding a simple rule in the nat table. ## Configure ip forwarding and iptables rules to connect containers to the internet ``` iptables -t nat -A POSTROUTING -s 172.16.0.0/24 -j MASQUERADE ``` This command means that we are adding a new rule to the nat table of the POSTROUTING chain to MASQUERADE all the packets whose source is 172.16.0.0/24 network. > POSTROUTING means right before leaving the interface. > MASQUERADE allows you to translate your private ip addresses with a single external ip address. In our case, we replaced containers private ip address with the host’s external interface address. You can run iptables -t nat -L to list the nat table rules. You can see a new rule is added in the nat table after you run the above postrouting masquerade command. ![Postrouting masquerade](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p3/masquerde-command-terminal.png) Before you try to ping internet from the containers, we need to enable ip forwarding. By default, the ip forwarding is disabled in Linux, if any incoming network packet arrives at one interface which is not meant for the system itself will be dropped. Enabling ip forwarding will allow the incoming packet meant to be passed on to the another network to be accepted and then forwards it accordingly. ``` # To see the ip forwarding status cat /proc/sys/net/ipv4/ip_forward # 0 means it's disabled. Setting it to 1 would mean it's enabled sysctl -w net.ipv4.ip_forward=1 ``` Now once again it’s time to test our containers’ connectivity with the internet. Let’s do it… Run ip netns exec container1 ping 1.1.1.1 ![Ping internet from container1 success](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p3/ping-internet-success.png) CONGRATULATIONS, YOU DID IT !! 🥳🎉 ## Conclusion In this, you learned how you can configure iptables to allow containers to connect with the internet. A big shoutout to you for making it this far in the journey of learning about container networking. ## Other related articles - [Container Networking Deep Dive - Part 1](/blog/container-networking-deep-dive-p1/) - [Container Networking Deep Dive - Part 2](/blog/container-networking-deep-dive-p2/) --- # Container Networking Deep Dive - Part 2 By Arihant Hirawat · 2022-11-20 Canonical: https://www.infraspec.dev/blog/container-networking-deep-dive-p2 In part 2 of this series, we will demystify how multiple containers running on the same host communicates with the host and vice versa. ## Topics to be covered 1. Setting up multiple containers on the host 1. We will understand about Linux bridge 1. Set up container networking from scratch using Linux commands ## Setting up the multiple containers on the host In [part 1](/blog/container-networking-deep-dive-p1/) , we had single container running on the host, and it was able to communicate with the host. The implementation of it is shown below. ![Single container host](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p2/single-container-host.png) Now consider that we want to have one more container named container 2 as shown below. We created veth pair named veth2 and ceth2, attached one end (ceth2) inside the container and another end (veth2) in the host. This way the container 2 will be able to talk with the host. ![Container 2](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p2/container-2.png) But with this, how will container1 and container2 will communicate with each other? One possible way which I could think of now is to create another veth pair and connect two containers with each other as shown below. ![Two container connected with veth pair](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p2/two-containers-with-veth-pair-connected.png) You might now have a question is what was so difficult with this. Think of having one more container named container3, and further more containers. Now if all the containers wants to communicate with each other, we will end up creating many veth pairs which is not the ideal way. ## How can we achieve that 🤔?. Think for few minutes …. Okay, it’s the right time to introduce one more container networking constituent element. ## Linux Bridge Linux bridge is a virtual device which allow forwarding packets to the interfaces that are connected to it. ![Linux Bridge](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p2/linux-bridge.png) In the above diagram, we have two networks LAN1 and LAN2 connected by a bridge allowing host1 in LAN1 to send packets to host4 in LAN2. Any devices connected with bridge can communicate with each other by forwarding packets. In our multi container scenario, we can create a bridge and attach our containers to it that will facilitate all containers to communicate with each other. ## Continuing with setting up the multiple containers on the host We will create a bridge and to attach containers to it, we can put one end of veth pair in container and attach other end with the bridge as shown. ![Multiple container attached to linux bridge](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p2/containers-attached-to-bridge.png) Now inside the containers we can set bridge as the default gateway to send packets to each other and the host. If any packets are sent to the bridge, the bridge can forward to the destination connected to it. Now let’s switch back to the terminal and write some scripts 😎 ## Prerequisites In this article also, we are using the [vagrant](https://developer.hashicorp.com/vagrant/downloads) ubuntu/jammy64 virtual machine. Make sure you have the vagrant installed. Here is the [link](https://github.com/arihant-2310/Container-Networking-Deep-Dive/blob/main/1-single-network-namespace/Vagrantfile) to the vagrant file to set up the VM. To start the VM, go to the directory where you downloaded the vagrant file and then execute the below commands: ``` #To start the VM vagrant up #To SSH into the VM vagrant ssh ``` > Note: All the commands in the following articles are run with root privileges. Either you can add sudo before each command or switch to different a user with root privileges by running sudo su ## Set up container networking from scratch using Linux commands In part 1 of this series, we already saw how to create network namespaces, add routes, run command inside network namespace etc. In this I will quickly run the commands. We will focus more on the bridge part to help you understand how containers are attached to it and how packets are sent via it. ![Bridge](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p2/terminal-bridge.png) ![Veth pair attached to bridge](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p2/veth-pair-bridge-terminal.png) ![Bridge created default route](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p2/bridge-default-route.png) ![Ping internet](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p2/ping-internet.png) - To create two network namespace container1 and container2 ``` ip netns add container1 ip netns add containe2 ``` - To create two veth pairs ``` ip link add veth1 type veth peer name ceth1 ip link add veth2 type veth peer name ceth2 ``` - To attach one end of each veth pair with containers ``` ip link set ceth1 netns container1 ip link set ceth2 netns container2 ``` - To enables the interfaces inside the containers ``` ip netns exec container1 ip link set lo up ip netns exec container2 ip link set lo up ip netns exec container1 ip link set ceth1 up ip netns exec container2 ip link set ceth2 up ``` - To assign ip address to interface inside containers ``` ip netns exec container1 ip addr add 172.16.0.2/24 dev ceth1 ip netns exec container2 ip addr add 172.16.0.3/24 dev ceth2 ``` - To create a bridge, run ip link add br0 type bridge This will create a bridge named br0. Run ip link to list the bridge. - To attach the veth1 and veth2 to the bridge ``` ip link set veth1 master br0 ip link set veth2 master br0 ``` - To enable veth1, veth2 and bridge br0 ``` ip link set veth1 up ip link set veth2 up ip link set br0 up ``` - To assign an ip address to the bridge, Run ip addr add 172.16.0.1/24 dev br0 A route is added in the host, it means any traffic which is destined for 172.16.0.0/24 send it via bridge and the source ip of the packet will the bridge ip address 172.16.0.1 - To ping container2 form container1, Run ip netns exec container1 ping 172.16.0.3 You can now ping container 1 and container 2 from the host, ping containers from each other. But if you try to ping host from any containers ( ip netns exec container1 ping 10.0.0.10 ), it will fail saying the host is unreachable because there is no route in containers saying how to forward packets destined for host. - To add a default route in containers For container1, Run ip netns exec container1 ip route add default via 172.16.0.1 dev ceth1 For container2, Run ip netns exec container2 ip route add default via 172.16.0.1 dev ceth2 This adds a default route in the containers saying if no route matches for the destination, use bridge(172.16.0.1) as the default gateway to forward all packets and the out interface is ceth1 and ceth2. - To ping to internet from container 1, Run ip netns exec container1 ping 1.1.1.1 The ping to internet did not succeed!! Give yourself some time to think why cannot the containers reach to the internet…. In part 3, we will see how the containers can connect to the internet. ## Conclusion In this, you learned how multiple containers running on a single host can communicate with each other. You also learned about linux bridges and created a linux bridge to attach containers to it. In part 3, we will try to resolve the connection between the containers and the internet. You will learn about iptables, network address translation etc. ## Other related articles - [Container Networking Deep Dive - Part 1](/blog/container-networking-deep-dive-p1/) - [Container Networking Deep Dive - Part 3](/blog/container-networking-deep-dive-p3/) --- # Container Networking Deep Dive - Part 1 By Arihant Hirawat · 2022-11-19 Canonical: https://www.infraspec.dev/blog/container-networking-deep-dive-p1 In part 1 of this series, we will demystify how a container communicates with the host and vice versa. ## Topics to be covered 1. Isolating containers with network namespaces. 1. Constituent networking elements like network interface, veth pair, and routing rules. 1. Set up container networking from scratch using Linux commands. ## Prerequisites In this article, we are using the [vagrant](https://developer.hashicorp.com/vagrant/downloads) ubuntu/jammy64 virtual machine. Make sure you have the vagrant installed. Here is the [link](https://github.com/arihant-2310/Container-Networking-Deep-Dive/blob/main/1-single-network-namespace/Vagrantfile) to the vagrant file to set up the VM. To start the VM, go to the directory where you downloaded the vagrant file and then execute the below commands: ``` #To start the VM vagrant up #To SSH into the VM vagrant ssh ``` > Note: All the commands in the following articles are run with root privileges. Either you can add sudo before each command or switch to different a user with root privileges by running sudo su ## Isolating containers with network namespaces Linux [namespaces](https://www.nginx.com/blog/what-are-namespaces-cgroups-how-do-they-work/) are one of the technologies that make up containers and allow process isolation. We will be using a network namespace to isolate the containers. A network namespace is logically another copy of a network stack, with its routes, firewall rules, and network devices. ![Network namespaces with their network stack](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/network-namespace.png) Instead of creating fully-isolated containers, we’d rather restrict the scope to only the network stack. ## Container networking constituent elements ### 1. Network Interface ![Host with a network interface to connect to public/private network](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/network-interface.png) A network interface is the point of interconnection between a computer and a private or public network. ### 2. Virtual Ethernet Device (veth) The veth devices are virtual ethernet devices. They can act as tunnels between network namespaces. ![Two namespaces connected by a veth pair](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/veth-pair.png) In the above, veth1 and veth2 are the names assigned to the two connected endpoints. Packets transmitted on one device in the pair are immediately received on the other device. For e.g., if we transmit packets from veth1 , they will be immediately received on veth2 and vice versa, thus allowing communication between network namespaces ns1 and ns2 . ### 3. Routing Tables Routing tables stores information on how packets are to be forwarded from one point to another. ![Routing table with one route entry](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/routing-table.png) The entry in the above routing table means that any packet destined for the 102.26.67.0 network with a netmask of 255.255.255.0 has to be transmitted via the gateway 10.0.0.2 and goes out through the interface eth0 . ## Let’s set up container networking from scratch with Linux commands Hope you have set up the fresh VM and ssh into it ✌️. ![host device IP addresses](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/ip-addr.png) ![Host machine with network interface named enp0s8](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/host-machine-interface.png) ![Host machine with a single container](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/host-machine-single-container.png) ![a veth pair with one end named veth1 and peer name ceth1](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/veth-cable.png) ![veth pair created in the host](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/veth-pair-bash.png) ![container-with-veth-pair](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/container-with-veth-pair.png) ![list-interfaces-inside-container](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/list-interfaces-inside-container.png) ![route inside container](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/route-inside-container.png) ![ping hang](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/ping-hang.png) - To see the host interfaces and devices’ IP addresses, run ip addr Initially, our host machine is configured with a network interface of IP address 10.0.0.10. The interface name and IP can be different for your case. 1. To create a network namespace, run ip netns add container1 1. To list the network namespaces, run ip netns . It will show container1 as a network namespace in the host. - Now we need a way for the host and container1 to communicate with each other. We already learned that a veth pair can be used to enable communication between two namespaces. The two namespaces are the root namespace (i.e., the host) and the container1 namespace. To create a veth pair, run ip link add veth1 type veth peer name ceth1 - To see the veth pair created, run ip link . You will see veth1 and ceth1 are created in the host, and they are in a down state. - Now we need to connect one end of the veth pair to container1 to allow communication between the host and container1. To set ceth1 inside container1, run ip link set ceth1 netns container1 - To list the interfaces inside container1 Below you can see the ceth1 interface is set inside container1 ``` #ip netns exec ip netns exec container1 ip link ``` - By default, both ends of the veth pair were down. To enable ``` #To set veth1 up ip link set veth1 up #To set ceth1 up ip netns exec container1 ip link set ceth1 up ``` - To send packets to container1, we need to assign IP address to ceth1 interface inside container1 You can check if the IP address was assigned to the ceth1 interface ip netns exec container1 ip addr . When you assigned an IP address to the ceth1 interface, a route was dynamically added inside the container1 namespace. To check the routes inside container1 , ip netns exec container1 ip route . This route means that any packet destined for 172.16.0.0/24 will be sent via the ceth1 interface. ``` ip netns exec container1 ip addr add 172.16.0.2/24 dev ceth1 ``` - To ping container1 from the host, run ping 172.16.0.2 The ping hangs infinitely because the host has no route to send packets to container IP 172.16.0.2 . 1. To send all packets destined for 172.16.0.0/24 via veth1 in the host, run ip route add 172.16.0.0/24 dev veth1 ![ping-unreachable](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/ping-unreachable.png) - Ping the container1 again from the host The ping is still unsuccessful! Take a minute thought to understand why 🤔 Okay, if you got the reason why ping was unsuccessful, Congrats 🥂 👏, else I have the answer. When we send a ping request from host IP 10.0.0.10 , the container needs to send a response back to the host for the ping to be successful. Since there is no route in container1 for sending the response back to the host, it says the destination host is unreachable. Let’s add a route inside container1 . 1. Set ceth1 as the default gateway for container1, run ip netns exec container1 ip route add default via 172.16.0.2 dev ceth1 ![ping-container-success](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/ping-container-success.png) ![ping host success](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/ping-host-success.png) - Now if you ping the container1 again The ping is successful 😃✌️ - Let’s try to ping the host from the container1 voila 🎊😃, you made it. ## The final networking setup for a single container running on a host machine ![single-network-namespace](https://www.infraspec.dev/images/blog/container-networking-deep-dive-p1/single-network-namespace.png) ## Conclusion You just learned about network namespaces and about the elements that constitute container networking. You also set up the container networking from scratch using Linux commands. Both container1 and the host can send packets to each other. In [part 2](/blog/container-networking-deep-dive-p2/) , we will see how we can have multiple containers running on a single host communicate with each other. ## Other related articles - [Container Networking Deep Dive - Part 2](/blog/container-networking-deep-dive-p2/) - [Container Networking Deep Dive - Part 3](/blog/container-networking-deep-dive-p3/)