Upload 31 files
Browse filesmy drunkcoding blogs
- az-00-pulumi-private-aks-environments.md +163 -0
- az-01-pulumi-setup-developer-account.md +363 -0
- az-02-pulumi-private-ask-env-architecture.md +102 -0
- az-03-pulumi-private-ask-credential-log-management.md +239 -0
- az-04-pulumi-private-aks-hub-vnet-development.md +118 -0
- az-05-pulumi-private-aks-cluster-env.md +174 -0
- az-06-pulumi-private-aks-cloudpc-hub.md +165 -0
- az-07-setup-cloudPC-windows365-enterprise.md +116 -0
- az-08-pulumi-setup-deploy-cicd-pipeline.md +182 -0
- az-09-private-aks-acr-image-sync.md +106 -0
- az-10-private-aks-helm-deployment.md +165 -0
- az-11-private-aks-expose-public-app-with-cloudflare-tunnel.md +190 -0
- az-12-private-aks-enable-mdm-devices-cf-tunnel-warp.md +200 -0
- dotnet-01-mvc-anti-forgery-token-and-machine-key.md +144 -0
- dotnet-02-tool-for-azure-ad-to-adss-Users-writeback.md +70 -0
- dotnet-03-multi-platform-dockerfile.md +413 -0
- dotnet-04-aspire-local-env-tests.md +552 -0
- ks-00-series-k8s-setup-local-env-pi-cluster.md +72 -0
- ks-01-Install-k3s-on-pi-cluster.md +172 -0
- ks-02-Install-nginx-on-pi-cluster.md +187 -0
- ks-03-install-cert-manager-free-ssl-kubernetes-cluster.md +158 -0
- ks-04-cert-manager-alternative-with-cloudflare.md +146 -0
- ks-05-public-services-with-cloudflare-tunnel.md +178 -0
- ks-06-hosting-outline-vpn-kubernetes.md +392 -0
- ks-07-hosting-longhorn-on-kubernetes.md +279 -0
- ks-08-cert-manager-with-private-aks.md +256 -0
- tools-automate-letsencrypt-certification-with-azure-keyvault.md +255 -0
- tools-az-scan-and-disable-entra-accounts.md +497 -0
- tools-az-service-bus-dead-letters-cleanup.md +265 -0
- tools-devops-repositories-branches-cleanup.md +487 -0
- tools-sql-database-cleanup.md +110 -0
az-00-pulumi-private-aks-environments.md
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
title: "[Az] A Comprehensive Series of Articles on Setting Up a Private AKS Environment on Azure with Pulumi."
|
| 5 |
+
featured: true
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- AKS
|
| 9 |
+
- Helm
|
| 10 |
+
- CI/CD
|
| 11 |
+
- AzureDevOps
|
| 12 |
+
- Cloudflare
|
| 13 |
+
- Tunnel
|
| 14 |
+
description: "In these series, Embark on a comprehensive journey to set up a fully private Azure Kubernetes Service (AKS) environment using Pulumi. This series guides you through the creation of Virtual Networks, configuration of Azure Firewalls, deployment of private AKS clusters, and integration with private Azure DevOps agents and a private CloudPC environment. Additionally, learn how to securely expose select applications to the public internet via Cloudflare Tunnels. Ideal for those aiming to build secure, scalable, and consistent environments across development, sandbox, and production stages."
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
## Introduction
|
| 18 |
+
|
| 19 |
+
Setting up a completely private environment in the cloud is a complex, especially when striving to maintain consistency across DEV, SANDBOX, and PRODUCTION environments.
|
| 20 |
+
In this comprehensive series, I will share insights and strategies on how to establish an entirely private AKS environment on Azure using Pulumi.
|
| 21 |
+
|
| 22 |
+
We'll delve into:
|
| 23 |
+
|
| 24 |
+
- **Virtual Network Creation**: Building a secure network foundation for the environment.
|
| 25 |
+
- **Azure Firewall Configuration**: Implementing robust security measures to control network traffic.
|
| 26 |
+
- **Private AKS Cluster Deployment**: Setting up Kubernetes clusters that are isolated from the public internet.
|
| 27 |
+
- **Private Azure DevOps Agents**: Integrating continuous integration and deployment pipelines within a secure environment.
|
| 28 |
+
- **Private CloudPC Environment**: Establishing secure virtual desktop infrastructure for remote development using Windows 365 Enterprise.
|
| 29 |
+
- **Secure Application Exposure**: Using Cloudflare Tunnels to expose select internal applications to the public internet without compromising security.
|
| 30 |
+
|
| 31 |
+
This series aims to provide a step-by-step guide to help to build secure, scalable, and consistent private cloud environments on Azure.
|
| 32 |
+
Whether you're a cloud architect, DevOps engineer, or developer, these articles will equip you with the knowledge to tackle the challenges of private cloud infrastructure.
|
| 33 |
+
|
| 34 |
+
## Table of Contents
|
| 35 |
+
|
| 36 |
+
## Pulumi Account Setup
|
| 37 |
+
|
| 38 |
+
**[Day 01: Setup pulumi account and project](/posts/az-01-pulumi-setup-developer-account)**
|
| 39 |
+
|
| 40 |
+
Start the cloud journey with Pulumi by setting up a developer account and deploying the first Azure resources.
|
| 41 |
+
This guide walks you through creating a Pulumi account, installing the necessary CLI tools, and using TypeScript to manage Azure infrastructure as code.
|
| 42 |
+
|
| 43 |
+
## Private AKS Environments
|
| 44 |
+
|
| 45 |
+
**[Day 02: Designing the Private AKS Environment Architecture](/posts/az-02-pulumi-private-ask-env-architecture)**
|
| 46 |
+
|
| 47 |
+
In this tutorial, We will explore the design of a private AKS environment on Azure. We'll use multiple subnets, Azure Firewall, and other critical cloud services to construct a secure architecture.
|
| 48 |
+
This setup is designed to keep sensitive workloads isolated and shielded from exposure to the public internet.
|
| 49 |
+
|
| 50 |
+
**[Day 03: Secret Management and Centralized Log Monitoring on Azure](/posts/az-03-pulumi-private-ask-credential-log-management)**
|
| 51 |
+
|
| 52 |
+
In this tutorial, walk us through the process of establishing a secure and automated system for secret management using Azure Key Vault.
|
| 53 |
+
Additionally, we will cover how to implement centralized log monitoring using Azure Log Analytics and Application Insights, enhancing observability and operational efficiency.
|
| 54 |
+
|
| 55 |
+
**[Day 04: Develops a Virtual Network Hub for Private AKS on Azure](/posts/az-04-pulumi-private-aks-hub-vnet-development)**
|
| 56 |
+
|
| 57 |
+
In this tutorial, We'll walk through the process of developing the first Hub VNet for a private AKS environment using Pulumi.
|
| 58 |
+
We will demonstrate how to seamlessly integrate a VNet with an Azure Firewall, along with configuring outbound public IP addresses.
|
| 59 |
+
|
| 60 |
+
**[Day 05: Implementing Private AKS Clusters with Advanced Networking](/posts/az-05-pulumi-private-aks-cluster-env)**
|
| 61 |
+
|
| 62 |
+
In this tutorial, We'll build a private AKS cluster with advanced networking features.
|
| 63 |
+
We'll explore how to integrate the AKS cluster with the Hub VNet and apply the firewall policies we've created.
|
| 64 |
+
|
| 65 |
+
**[Day 06: Implements a private CloudPC and DevOps Agent Hub with Pulumi](/posts/az-06-pulumi-private-aks-cloudpc-hub)**
|
| 66 |
+
|
| 67 |
+
In this tutorial, guide us through setting up a secure CloudPC and DevOps agent hub, aimed at improving the management and operational capabilities of the private AKS environment using Pulumi.
|
| 68 |
+
|
| 69 |
+
## Progress Review After 06 Days
|
| 70 |
+
|
| 71 |
+
Let's take a moment to review our achievements. After completing six tutorials, we have successfully deployed our private AKS environment.
|
| 72 |
+
The illustration below provides a visual representation of our current environment after 6 days:
|
| 73 |
+

|
| 74 |
+
<p class="ml-44"><em>The illustration private AKS env</em></p>
|
| 75 |
+
|
| 76 |
+
## CloudPC environment (Windows 365 enterprise)
|
| 77 |
+
|
| 78 |
+
**[Day 07: Setup Windows 365 Enterprise as a private VDI](/posts/az-07-setup-cloudpc-windows365-enterprise)**
|
| 79 |
+
|
| 80 |
+
In this tutorial, We will explore how to configure a CloudPC with Windows 365 Enterprise to establish a secure and efficient Virtual Desktop Infrastructure (VDI) for accessing a private AKS environment.
|
| 81 |
+
|
| 82 |
+
## Azure DevOps Pipelines
|
| 83 |
+
|
| 84 |
+
**[Day 08: Setting Up a Deployment Pipeline for Pulumi Projects.](/posts/az-08-pulumi-setup-deploy-cicd-pipeline)**
|
| 85 |
+
|
| 86 |
+
In this tutorial, We will walk through creating a Continuous Integration and Continuous Deployment (CI/CD) pipeline on Azure DevOps for our Pulumi projects.
|
| 87 |
+
|
| 88 |
+
**[Day 09: Synchronizing Container Images to ACR for a Private AKS Cluster Using CI/CD Pipelines.](/posts/az-09-private-aks-acr-image-sync)**
|
| 89 |
+
|
| 90 |
+
In this tutorial, We explore the process of synchronizing container images with ACR for deployments in a private AKS cluster.
|
| 91 |
+
We'll cover how to configure and automate this synchronization using CI/CD pipelines, ensuring seamless updates and secure image management for private AKS environments.
|
| 92 |
+
|
| 93 |
+
**[Day 10: Implementing a Helm Deployment CI/CD AzureDevOps Pipeline for a Private AKS Cluster.](/posts/az-10-private-aks-helm-deployment)**
|
| 94 |
+
|
| 95 |
+
In this tutorial, We will create Helm charts for nginx-ingress and cert-manager, and set up a robust CI/CD pipeline using Azure DevOps for Helm deployments to a private AKS cluster.
|
| 96 |
+
|
| 97 |
+
## Progress Review After 10 Days
|
| 98 |
+
|
| 99 |
+
Let's take a moment to review our achievements. After completing 10 tutorials, we have successfully deployed our internal ingress, cert-manager and private DNS Zone.
|
| 100 |
+
The illustration below provides a visual representation of our current environment:
|
| 101 |
+

|
| 102 |
+
<p class="ml-14"><em>The illustration of AKS env with private ingress and DNS Zone</em></p>
|
| 103 |
+
|
| 104 |
+
## Public Apps with Cloudflare Tunnels
|
| 105 |
+
|
| 106 |
+
**[Day 11: Exposing a Private AKS Application via Cloudflare Tunnel.](/posts/az-11-private-aks-expose-public-app-with-cloudflare-tunnel)**
|
| 107 |
+
|
| 108 |
+
In this tutorial, We demonstrate how to securely expose an application running on a private AKS cluster to the internet using Cloudflare Tunnel, without the need for public IP addresses or open ports. We'll also show how to apply authentication to all exposed applications and centralize access control using Azure Entra ID Groups, ensuring only authorized users have access.
|
| 109 |
+
|
| 110 |
+
## Microsoft Intune (MDM) Devices and Cloudflare Tunnel
|
| 111 |
+
|
| 112 |
+
**[Day 12: Exposing a Private AKS Application via Cloudflare Tunnel.](/posts/az-12-private-aks-enable-mdm-devices-cf-tunnel-warp)**
|
| 113 |
+
|
| 114 |
+
In this final tutorial, We'll discover how to safely expose the private AKS cluster and applications to the internet with Cloudflare.
|
| 115 |
+
It'll delve into the benefits of using Cloudflare Tunnel and WARP, exploring alternative ways to provide secure access while maintaining the integrity of the corporate network.
|
| 116 |
+
|
| 117 |
+
## Conclusions
|
| 118 |
+
|
| 119 |
+
Throughout this comprehensive series, we've journeyed through the intricate process of setting up a private AKS environment on Azure using Pulumi.
|
| 120 |
+
|
| 121 |
+
Starting with the Pulumi account setup, we've built a secure and scalable infrastructure that includes Virtual Networks, Azure Firewall, private AKS clusters, and private Azure DevOps agents.
|
| 122 |
+
|
| 123 |
+
Additionally, we delved into the integration of a private CloudPC environment and demonstrated secure application exposure through Cloudflare Tunnels.
|
| 124 |
+
|
| 125 |
+
- Upon completing all 12 tutorials, we have effectively established a unified private infrastructure. This setup includes private AKS clusters, Azure DevOps agents, and a CloudPC environment, all seamlessly integrated with Cloudflare Tunnels and Entra ID SSO. This ensures secure access for MDM Intune devices.
|
| 126 |
+

|
| 127 |
+
|
| 128 |
+
- Throughout this series, we developed a total of six Azure DevOps pipelines, as shown below:
|
| 129 |
+

|
| 130 |
+
|
| 131 |
+
- In terms of expenses, we incurred approximately $200 in Azure resource costs, with estimated around 500 USD monthly for the entire environment. Detailed in the analytics below:
|
| 132 |
+

|
| 133 |
+
|
| 134 |
+
## Future Enhancements
|
| 135 |
+
|
| 136 |
+
As we reflect on our journey to establish a private AKS environment on Azure, there are several crucial areas that offer opportunities for enhancing performance, security, and scalability.
|
| 137 |
+
|
| 138 |
+
### Architectural Enhancements
|
| 139 |
+
|
| 140 |
+
- **Implement a Secure DMZ Network**: Establish a Demilitarized Zone (DMZ) to bolster security by isolating public-facing services like the Cloudflare Tunnel. Relocating the Cloudflare Tunnel outside the private AKS cluster and into the DMZ allows for better traffic management and monitoring, while protecting internal networks from direct exposure. Utilizing Azure Virtual Machine Scale Sets for services in the DMZ will enable automatic scaling of workloads, ensuring efficient resource utilization and enhanced security.
|
| 141 |
+
|
| 142 |
+
- **Refine Firewall Rules**: Enhance the firewall configurations with more granular rules, specifically tailored for the services operating within the DMZ. Restrict access by employing precise IP ranges and protocols, ensuring that only legitimate and necessary traffic is permitted, thereby improving security.
|
| 143 |
+
|
| 144 |
+
- **Leverage Auto-Scaling for Private Agents**: Optimize resource usage by employing Azure Virtual Machine Scale Sets to automatically adjust the number of private Azure DevOps agents based on demand. This approach not only ensures high availability during peak workloads but also conserves resources during periods of inactivity.
|
| 145 |
+
|
| 146 |
+
### Project Enhancements
|
| 147 |
+
|
| 148 |
+
- **Modularize Shared Components**: Increase maintainability and reusability by extracting shared components into separate, modular projects. This strategy fosters consistency and streamlines updates across various environments, reducing the complexity and risk of manual changes.
|
| 149 |
+
|
| 150 |
+
- **Optimize Build Processes with Pre-Built Binaries**: Accelerate deployment by pre-building shared components' binaries locally and committing them to the repository. This practice minimizes deployment times by avoiding repeated builds in CI/CD pipelines, leading to faster and more reliable integration and delivery processes.
|
| 151 |
+
|
| 152 |
+
By pursuing these enhancements, we aim to strengthen the security, efficiency, and scalability of our private AKS environment. Implementing these improvements will better prepare our infrastructure to meet emerging challenges and support continued business growth.
|
| 153 |
+
|
| 154 |
+
## References
|
| 155 |
+
|
| 156 |
+
The complete source code for this series is available on my [GitHub repository](https://github.com/baoduy/drunk-azure-pulumi-articles).
|
| 157 |
+
Feel free to clone the repository and contribute by submitting pull requests or raising issues.
|
| 158 |
+
|
| 159 |
+
## Thank You
|
| 160 |
+
|
| 161 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 162 |
+
|
| 163 |
+
**Steven** | _[GitHub](https://github.com/baoduy)_
|
az-01-pulumi-setup-developer-account.md
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-10-12T12:00:00Z
|
| 4 |
+
title: "[Az] Day 01: Setup pulumi developer account"
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- aks
|
| 9 |
+
- private
|
| 10 |
+
- pulumi
|
| 11 |
+
description: "Start the cloud journey with Pulumi by setting up a developer account and deploying the first Azure resources.
|
| 12 |
+
This guide walks you through creating a Pulumi account, installing the necessary CLI tools, and using TypeScript to manage Azure infrastructure as code."
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
## Introduction
|
| 16 |
+
|
| 17 |
+
Pulumi is a powerful open-source Infrastructure as Code (IaC) tool that allows us to define cloud resources using popular programming languages such as _TypeScript, Python, Go, and C#_.
|
| 18 |
+
By harnessing these tools, we can effectively manage our infrastructure across multiple cloud providers like **Azure, AWS, and Google Cloud**.
|
| 19 |
+
|
| 20 |
+
In this guide, we will explore:
|
| 21 |
+
|
| 22 |
+
- Registering for a Pulumi account
|
| 23 |
+
- Generating a Personal Access Token (PAT)
|
| 24 |
+
- Setting up the Pulumi and Azure CLI tools
|
| 25 |
+
- Creating our first Pulumi project using the TypeScript template for Azure
|
| 26 |
+
- Deploying our first Azure Resource Group and Storage Account
|
| 27 |
+
|
| 28 |
+
## Table of Contents
|
| 29 |
+
|
| 30 |
+
## Prerequisites
|
| 31 |
+
|
| 32 |
+
- **Node.js** installed on the machine
|
| 33 |
+
- An **Azure account** (you can [create a free account here](https://azure.microsoft.com/free/))
|
| 34 |
+
|
| 35 |
+
## Pulumi Setup
|
| 36 |
+
|
| 37 |
+
### Create a Pulumi Account
|
| 38 |
+
|
| 39 |
+
1. **Visit the Pulumi Website**
|
| 40 |
+
|
| 41 |
+
Let's navigate to the [Pulumi website](https://www.pulumi.com/) and click on the **"Sign Up"** button.
|
| 42 |
+
|
| 43 |
+
2. **Choose a Sign-Up Method**
|
| 44 |
+
|
| 45 |
+
Sign up using one of the following methods:
|
| 46 |
+
|
| 47 |
+
- **GitHub**
|
| 48 |
+
- **GitLab**
|
| 49 |
+
- **Bitbucket**
|
| 50 |
+
- **Email**
|
| 51 |
+
|
| 52 |
+
Follow the on-screen instructions to complete the registration.
|
| 53 |
+
|
| 54 |
+
3. **Confirm Your Email**
|
| 55 |
+
|
| 56 |
+
If you signed up using an email address, check your inbox for a confirmation email and verify your account.
|
| 57 |
+
|
| 58 |
+
### Generate a Personal Access Token (PAT)
|
| 59 |
+
|
| 60 |
+
A Personal Access Token (PAT) is required to authenticate the Pulumi CLI with your Pulumi account.
|
| 61 |
+
|
| 62 |
+
1. **Pulumi Dashboard**
|
| 63 |
+
|
| 64 |
+
Visit the [Pulumi Dashboard](https://app.pulumi.com/) and log in with your credentials.
|
| 65 |
+
|
| 66 |
+
2. **Access the Tokens Page**
|
| 67 |
+
|
| 68 |
+
- Click on your avatar or username in the top-right corner.
|
| 69 |
+
- Select **"Access Tokens"** from the dropdown menu.
|
| 70 |
+
|
| 71 |
+
3. **Create a New Token**
|
| 72 |
+
|
| 73 |
+
- Click on **"Create Token"**.
|
| 74 |
+
- Provide a description (e.g., "Pulumi CLI Token").
|
| 75 |
+
- Click **"Create"** and copy the generated token for later use.
|
| 76 |
+
|
| 77 |
+
### (Optional) Create a New Organization
|
| 78 |
+
|
| 79 |
+
If you'd like to manage your projects under a separate organization:
|
| 80 |
+
|
| 81 |
+
1. **Navigate to Organizations**
|
| 82 |
+
|
| 83 |
+
- In the Pulumi Console, click on your avatar or username.
|
| 84 |
+
- Select **"Organizations"**.
|
| 85 |
+
|
| 86 |
+
2. **Create a New Organization**
|
| 87 |
+
|
| 88 |
+
- Click on **"Create Organization"**.
|
| 89 |
+
- Follow the prompts to set up your organization.
|
| 90 |
+
|
| 91 |
+

|
| 92 |
+
|
| 93 |
+
## Install CLI Tools
|
| 94 |
+
|
| 95 |
+
### Install the Pulumi CLI
|
| 96 |
+
|
| 97 |
+
Follow the instructions [here](https://www.pulumi.com/docs/get-started/install/) to install the Pulumi CLI for your operating system.
|
| 98 |
+
|
| 99 |
+
### Install the Azure CLI
|
| 100 |
+
|
| 101 |
+
Next, Install the Azure CLI by following the instructions [here](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli).
|
| 102 |
+
|
| 103 |
+
**Here are the current versions after installed them successfully.**
|
| 104 |
+
|
| 105 |
+
```bash
|
| 106 |
+
> pulumi version
|
| 107 |
+
v3.133.0
|
| 108 |
+
|
| 109 |
+
> az -v
|
| 110 |
+
azure-cli 2.64.0
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
## Configure Pulumi for Azure
|
| 114 |
+
|
| 115 |
+
Before diving into coding, let's configure Pulumi to work with your Azure account. Run the following commands to set up your Pulumi stack with the correct Azure subscription details:
|
| 116 |
+
|
| 117 |
+
```bash
|
| 118 |
+
# Set the default Pulumi organization (replace with your organization name)
|
| 119 |
+
pulumi org set-default YOUR_PULUMI_ORGANIZATION
|
| 120 |
+
|
| 121 |
+
# Configure Azure settings
|
| 122 |
+
pulumi config set azure-native:tenantId YOUR_AZURE_TENANT_ID
|
| 123 |
+
pulumi config set azure-native:subscriptionId YOUR_AZURE_SUBSCRIPTION_ID
|
| 124 |
+
pulumi config set azure-native:location YOUR_AZURE_LOCATION # e.g., SoutheastAsia
|
| 125 |
+
|
| 126 |
+
# Optional: If you're using a service principal for authentication
|
| 127 |
+
pulumi config set azure-native:clientId YOUR_AZURE_CLIENT_ID
|
| 128 |
+
pulumi config set azure-native:clientSecret YOUR_AZURE_CLIENT_SECRET --secret
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
> **Note:**
|
| 132 |
+
>
|
| 133 |
+
> - Replace placeholders with your actual Azure details.
|
| 134 |
+
> - The `--secret` flag ensures sensitive information is encrypted using Pulumi stack encryption.
|
| 135 |
+
|
| 136 |
+
## Create Your First Pulumi Project
|
| 137 |
+
|
| 138 |
+
### Set Up a Git Repository
|
| 139 |
+
|
| 140 |
+
Create a new directory for our Pulumi project and initialize a Git repository:
|
| 141 |
+
|
| 142 |
+
```bash
|
| 143 |
+
mkdir pulumi-azure-start
|
| 144 |
+
cd pulumi-azure-start
|
| 145 |
+
git init
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
### Initialize a New Pulumi Project
|
| 149 |
+
|
| 150 |
+
Run the following command to create a new Pulumi project using the Azure TypeScript template:
|
| 151 |
+
|
| 152 |
+
```bash
|
| 153 |
+
pulumi new azure-typescript
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
We'll be prompted to provide:
|
| 157 |
+
|
| 158 |
+
- **Login**: Authenticate using the PAT token generated earlier.
|
| 159 |
+
- **Project name**: Accept the default or enter a custom name.
|
| 160 |
+
- **Project description**: The description of the project. (Optional)
|
| 161 |
+
- **Stack name**: The stack name, example: `dev`, `sandbox`, or `prd`
|
| 162 |
+
- **Package manager**: Choose the package manager (e.g., `npm`, `yarn`, `pnpm`).
|
| 163 |
+
- **Azure location**: The azure region location for the resources to be created on. e.g., `SoutheastAsia`
|
| 164 |
+
|
| 165 |
+
After the project is created, if you are using your own account for development, then ensure you're logged into Azure using Az CLI:
|
| 166 |
+
|
| 167 |
+
```bash
|
| 168 |
+
az login
|
| 169 |
+
|
| 170 |
+
# Sample Code
|
| 171 |
+
Retrieving tenants and subscriptions for the selection...
|
| 172 |
+
|
| 173 |
+
[Tenant and subscription selection]
|
| 174 |
+
|
| 175 |
+
No Subscription name Subscription ID Tenant
|
| 176 |
+
----- ------------------- ------------------------------------ -----------
|
| 177 |
+
[1] * DrunkCoding 54dbd16b-81cd-yyyy-xxxx-xxxyyyzzz000 DrunkCoding
|
| 178 |
+
|
| 179 |
+
```
|
| 180 |
+
|
| 181 |
+
> **Note**:
|
| 182 |
+
>
|
| 183 |
+
> - Pulumi supports various package managers, including `npm`, `yarn`, and `pnpm`. For consistency, this guide will use `pnpm` for all Pulumi projects.
|
| 184 |
+
> - By default, all pulumi stacks are encrypted with a randomly generated key. If you prefer to use a custom encryption key, refer to the [Pulumi documentation](https://www.pulumi.com/docs/iac/concepts/secrets/#configuring-secrets-encryption) for instructions.
|
| 185 |
+
|
| 186 |
+
## Understand the Project Structure
|
| 187 |
+
|
| 188 |
+
### Project files
|
| 189 |
+
|
| 190 |
+
The template generates several files:
|
| 191 |
+
|
| 192 |
+
- **Pulumi.yaml**: Contains project metadata.
|
| 193 |
+
- **Pulumi.dev.yaml**: Contains stack-specific configuration and secrets.
|
| 194 |
+
- **index.ts**: The main program file where you'll define your infrastructure.
|
| 195 |
+
|
| 196 |
+
### Review the Sample Code
|
| 197 |
+
|
| 198 |
+
Open `index.ts` in your preferred code editor and review the sample code. It typically includes the creation of a Resource Group and a Storage Account.
|
| 199 |
+
|
| 200 |
+
<details><summary><em>View Code:</em></summary>
|
| 201 |
+
|
| 202 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/day-0/day00_pulumi-azure-start/index.ts#1-1000)
|
| 203 |
+
|
| 204 |
+
</details>
|
| 205 |
+
|
| 206 |
+
> Note: Exporting the key here is just for demo purposes.
|
| 207 |
+
> In the real environment, all the connection string and credentials should be stored in the Key Vault instead.
|
| 208 |
+
|
| 209 |
+
## Preview and Deploy Pulumi Stack
|
| 210 |
+
|
| 211 |
+
### Preview the Changes
|
| 212 |
+
|
| 213 |
+
Before deploying, preview the changes to ensure everything is set up correctly:
|
| 214 |
+
|
| 215 |
+
```bash
|
| 216 |
+
pulumi up
|
| 217 |
+
```
|
| 218 |
+
|
| 219 |
+
<details><summary><em>Sample Output:</em></summary>
|
| 220 |
+
|
| 221 |
+
```bash
|
| 222 |
+
Previewing update (dev)
|
| 223 |
+
|
| 224 |
+
View in Browser (Ctrl+O): https://app.pulumi.com/drunkcoding/day00_pulumi-azure-start/dev/previews/xxxxxxxx-1f60-4ed9-bb35-xxxxxxxxxxxx
|
| 225 |
+
|
| 226 |
+
Type Name Plan
|
| 227 |
+
+ pulumi:pulumi:Stack day00_pulumi-azure-start-dev create
|
| 228 |
+
+ ├─ azure-native:resources:ResourceGroup resourceGroup create
|
| 229 |
+
+ └─ azure-native:storage:StorageAccount sa create
|
| 230 |
+
|
| 231 |
+
Outputs:
|
| 232 |
+
primaryStorageKey: output<string>
|
| 233 |
+
|
| 234 |
+
Resources:
|
| 235 |
+
+ 3 to create
|
| 236 |
+
|
| 237 |
+
Do you want to perform this update? [Use arrows to move, type to filter]
|
| 238 |
+
yes
|
| 239 |
+
> no
|
| 240 |
+
details
|
| 241 |
+
```
|
| 242 |
+
|
| 243 |
+
</details>
|
| 244 |
+
|
| 245 |
+
### Deploy the Stack
|
| 246 |
+
|
| 247 |
+
Deploy your resources to Azure:
|
| 248 |
+
|
| 249 |
+
```bash
|
| 250 |
+
pulumi up -y
|
| 251 |
+
```
|
| 252 |
+
|
| 253 |
+
<details><summary><em>Sample Output:</em></summary>
|
| 254 |
+
|
| 255 |
+
```bash
|
| 256 |
+
Updating (dev)
|
| 257 |
+
|
| 258 |
+
View Live: https://app.pulumi.com/YOUR_ORGANIZATION/day00_pulumi-azure-start/dev/updates/1
|
| 259 |
+
|
| 260 |
+
Type Name Status
|
| 261 |
+
+ pulumi:pulumi:Stack day00_pulumi-azure-start-dev created
|
| 262 |
+
+ ├─ azure-native:resources:ResourceGroup resourceGroup created
|
| 263 |
+
+ └─ azure-native:storage:StorageAccount storageaccount created
|
| 264 |
+
|
| 265 |
+
Outputs:
|
| 266 |
+
primaryStorageKey: "<secure>"
|
| 267 |
+
|
| 268 |
+
Resources:
|
| 269 |
+
+ 3 created
|
| 270 |
+
|
| 271 |
+
Duration: 35s
|
| 272 |
+
```
|
| 273 |
+
|
| 274 |
+
</details>
|
| 275 |
+
|
| 276 |
+
### Verify the Deployment
|
| 277 |
+
|
| 278 |
+
After deployment, We can verify the resources in the Azure Portal:
|
| 279 |
+
|
| 280 |
+
- Log in to the [Azure Portal](https://portal.azure.com/).
|
| 281 |
+
- Navigate to **Resource Groups** and locate your newly created resource group.
|
| 282 |
+
- Verify that the Storage Account is present within the resource group.
|
| 283 |
+
|
| 284 |
+

|
| 285 |
+
|
| 286 |
+
## Clean Up Resources
|
| 287 |
+
|
| 288 |
+
To avoid incurring unnecessary costs, destroy the resources when they're no longer needed:
|
| 289 |
+
|
| 290 |
+
```bash
|
| 291 |
+
pulumi destroy -y
|
| 292 |
+
```
|
| 293 |
+
|
| 294 |
+
<details><summary><em>Sample Output:</em></summary>
|
| 295 |
+
|
| 296 |
+
```bash
|
| 297 |
+
Destroying (dev)
|
| 298 |
+
|
| 299 |
+
View Live: https://app.pulumi.com/YOUR_ORGANIZATION/day00_pulumi-azure-start/dev/updates/2
|
| 300 |
+
|
| 301 |
+
Type Name Status
|
| 302 |
+
- pulumi:pulumi:Stack day00_pulumi-azure-start-dev deleted
|
| 303 |
+
- ├─ azure-native:storage:StorageAccount storageaccount deleted
|
| 304 |
+
- └─ azure-native:resources:ResourceGroup resourceGroup deleted
|
| 305 |
+
|
| 306 |
+
Outputs:
|
| 307 |
+
- primaryStorageKey: "<secure>"
|
| 308 |
+
|
| 309 |
+
Resources:
|
| 310 |
+
- 3 deleted
|
| 311 |
+
|
| 312 |
+
Duration: 25s
|
| 313 |
+
|
| 314 |
+
The resources in the stack have been deleted, but the history and configuration are still maintained.
|
| 315 |
+
If you want to remove the stack completely, run `pulumi stack rm dev`.
|
| 316 |
+
```
|
| 317 |
+
|
| 318 |
+
</details>
|
| 319 |
+
|
| 320 |
+
## Pulumi CLI commands
|
| 321 |
+
|
| 322 |
+
The most common commands in the CLI that you’ll be using are as follows:
|
| 323 |
+
|
| 324 |
+
- `pulumi new`: creates a new project using a template
|
| 325 |
+
- `pulumi stack select`: switching between the stacks (at least one is required to perform an update)
|
| 326 |
+
- `pulumi config`: configure variables such as keys, regions, and so on
|
| 327 |
+
- `pulumi up`: preview and deploy changes to your program and/or infrastructure
|
| 328 |
+
- `pulumi preview`: preview your changes explicitly before deploying
|
| 329 |
+
- `pulumi destroy`: destroy your program and its infrastructure when you’re done
|
| 330 |
+
|
| 331 |
+
> Refer [here for the details](https://www.pulumi.com/docs/iac/cli/commands/) of Pulumi commands
|
| 332 |
+
|
| 333 |
+
## Conclusion
|
| 334 |
+
|
| 335 |
+
Congratulations! You've successfully:
|
| 336 |
+
|
| 337 |
+
- Registered for a Pulumi account
|
| 338 |
+
- Generate a Personal Access Token
|
| 339 |
+
- Set up the Pulumi and Azure CLI tools
|
| 340 |
+
- Create your first Pulumi project using TypeScript for Azure
|
| 341 |
+
- Deployed an Azure Resource Group and Storage Account
|
| 342 |
+
|
| 343 |
+
Pulumi simplifies cloud resource management by allowing you to use familiar programming languages and tools. We can now explore adding more complex resources and configurations on the projects.
|
| 344 |
+
|
| 345 |
+
## References
|
| 346 |
+
|
| 347 |
+
- [Sample source code](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/day-0/day00_pulumi-azure-start#day-0)
|
| 348 |
+
- [Pulumi get started](https://www.pulumi.com/docs/iac/get-started/)
|
| 349 |
+
- [Pulumi Commands](https://www.pulumi.com/docs/iac/cli/commands/)
|
| 350 |
+
- [Pulumi Secret Config](https://www.pulumi.com/docs/iac/concepts/secrets/#configuring-secrets-encryption)
|
| 351 |
+
|
| 352 |
+
## Next
|
| 353 |
+
|
| 354 |
+
**[Day 02: Private Aks Environment Architecture.](/posts/az-02-pulumi-private-ask-env-architecture)**
|
| 355 |
+
|
| 356 |
+
In the next tutorial, We will discuss the architecture of private AKS that we are going to provision on Azure, leveraging multiple subnets, Azure Firewall, and other essential cloud services.
|
| 357 |
+
This architecture ensures that sensitive workloads remain isolated and protected from public internet exposure.
|
| 358 |
+
|
| 359 |
+
## Thank You
|
| 360 |
+
|
| 361 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 362 |
+
|
| 363 |
+
**Steven** | _[GitHub](https://github.com/baoduy)_
|
az-02-pulumi-private-ask-env-architecture.md
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-10-12T12:00:00Z
|
| 4 |
+
title: "[Az] Day 02: Private Azure Kubernetes (AKS) Environment Architecture."
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- AKS
|
| 9 |
+
- Private
|
| 10 |
+
- Pulumi
|
| 11 |
+
description: "
|
| 12 |
+
In this tutorial, We will explore the design of a private AKS environment on Azure. We'll use multiple subnets, Azure Firewall, and other critical cloud services to construct a secure architecture.
|
| 13 |
+
This setup is designed to keep sensitive workloads isolated and shielded from exposure to the public internet.
|
| 14 |
+
"
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
## Introduction
|
| 18 |
+
|
| 19 |
+
In today's cloud-centric world, security is paramount. By default, many cloud services are publicly accessible over the internet, which can pose significant risks for sensitive workloads.
|
| 20 |
+
|
| 21 |
+
When deploying a private AKS (AKS) environment, it's essential to protect all components while maintaining efficient network communication.
|
| 22 |
+
|
| 23 |
+
This post explains an architecture of private AKS that we are going to set up on Azure, leveraging multiple subnets, Azure Firewall, and other essential cloud services.
|
| 24 |
+
|
| 25 |
+

|
| 26 |
+
<p class="ml-44"><em>(Download the original draw.io file <a href="/assets/az-02-pulumi-private-ask-env-architecture/private-aks.drawio" download>here)</a></em></p>
|
| 27 |
+
|
| 28 |
+
## Table of Contents
|
| 29 |
+
|
| 30 |
+
## Architecture Overview
|
| 31 |
+
|
| 32 |
+
This architecture ensures that sensitive workloads remain isolated and protected from public internet exposure.
|
| 33 |
+
|
| 34 |
+
### Hub VNet
|
| 35 |
+
|
| 36 |
+
The Hub VNet acts as the central point for network security and communication management, utilizing a **hub-and-spoke** architecture. It includes:
|
| 37 |
+
|
| 38 |
+
- **Azure Firewall**: Positioned in dedicated subnets, it serves as the main security gateway, regulating all the network traffic.
|
| 39 |
+
It consolidates outbound traffic through a single public IP address for **easier control and third-party whitelisting**.
|
| 40 |
+
Security measures include:
|
| 41 |
+
- **Outbound Traffic Control**: Inspects and authorizes outgoing traffic to approved IP ranges or services.
|
| 42 |
+
- **No Inbound NAT Rules**: Blocks unsolicited inbound internet traffic, enhancing security.
|
| 43 |
+
- **Network Traffic Control**: Restricts direct access to the AKS cluster and other resources, allowing only legitimate internal interactions.
|
| 44 |
+
|
| 45 |
+
- **General Subnet**: Allocated for Azure resources with private links, such as Key Vault, SQL Server, and Storage Account. It is entirely internal with no public access, ensuring secure operations.
|
| 46 |
+
|
| 47 |
+
### AKS VNet
|
| 48 |
+
|
| 49 |
+
The AKS VNet is designed to host the private AKS cluster, ensuring secure and efficient communication with other network components:
|
| 50 |
+
|
| 51 |
+
- **AKS Subnet**: Hosts the AKS cluster within a dedicated subnet. The Kubernetes API server is accessible only via a private endpoint, and pod networking manages secure communication with services in the General Subnet.
|
| 52 |
+
- **Azure Firewall Rules:** only allows external access to necessary resources for AKS cluster.
|
| 53 |
+
|
| 54 |
+
### CloudPC VNet
|
| 55 |
+
|
| 56 |
+
The CloudPC VNet provides secure environments for virtual desktops and DevOps operations, maintaining isolation from critical infrastructure:
|
| 57 |
+
|
| 58 |
+
- **CloudPC Subnet**: Provides secure VDI environment (using Windows 365 enterprise) for internal resource access, eliminating public exposure.
|
| 59 |
+
- **DevOps Subnet**: Hosts resources for DevOps private agents, including CI/CD pipelines for private ASK deployment.
|
| 60 |
+
|
| 61 |
+
## Subnet IP Allocation
|
| 62 |
+
|
| 63 |
+
Here is the summary of the private IP address allocation for each subnet:
|
| 64 |
+
|
| 65 |
+
| VNet Name | Subnet Name | Address Prefix | Total | Usable |
|
| 66 |
+
|---------------------|--------------------------------|---------------------|-------|--------|
|
| 67 |
+
| **1. Hub VNet** | 1.1 Firewall Subnet | `192.168.30.0/26` | 64 | 59 |
|
| 68 |
+
| | 1.2 Firewall Management Subnet | `192.168.30.64/26` | 54 | 59 |
|
| 69 |
+
| | 1.3 General Subnet | `192.168.30.128/27` | 32 | 27 |
|
| 70 |
+
| **2. AKS VNet** | 2.1 AKS Subnet | `192.168.31.0/24` | 256 | 251 |
|
| 71 |
+
| **3. CloudPC VNet** | 3.1 CloudPC Subnet | `192.168.32.0/25` | 128 | 123 |
|
| 72 |
+
| | 3.2 DevOps Subnet | `192.168.32.128/27` | 32 | 27 |
|
| 73 |
+
|
| 74 |
+
> **Note**: Adjust the address space according to your environment, as this is intended for demonstration purposes.
|
| 75 |
+
|
| 76 |
+
## Conclusion
|
| 77 |
+
|
| 78 |
+
Designing the network architecture with a strong focus on security allows us to fully utilize Azure services while safeguarding our workloads from external threats. This private AKS environment offers a robust, scalable, and adaptable platform for deploying containerized applications.
|
| 79 |
+
|
| 80 |
+
- **Complete Isolation**: Essential resources remain shielded from the public internet. Service access is secured through private endpoints and managed by Azure Firewall.
|
| 81 |
+
- **Centralized Security Management**: Azure Firewall acts as a unified control point for overseeing and securing all network traffic and leaving the environment.
|
| 82 |
+
- **Scalability and Flexibility**: Each subnet can be scaled independently according to workload demands, offering flexibility in expanding the AKS cluster or integrating additional services.
|
| 83 |
+
- **Reduced Attack Surface**: By segmenting services into distinct subnets and employing Azure Firewall as a protective barrier, the attack surface is significantly minimized, reducing the risk of unauthorized access.
|
| 84 |
+
- **Efficient Communication**: Private endpoints and internal routing facilitate seamless communication between services without exposing them to external networks.
|
| 85 |
+
|
| 86 |
+
## References
|
| 87 |
+
|
| 88 |
+
- [Use Azure Firewall to help protect an AKS cluster](https://learn.microsoft.com/en-us/azure/architecture/guide/aks/aks-firewall)
|
| 89 |
+
- [Limit network traffic with Azure Firewall in AKS](https://learn.microsoft.com/en-us/azure/aks/limit-egress-traffic?tabs=aks-with-system-assigned-identities)
|
| 90 |
+
|
| 91 |
+
## Next
|
| 92 |
+
|
| 93 |
+
**[Day 03: Secret Management and Centralized Log Monitoring on Azure](/posts/az-03-pulumi-private-ask-credential-log-management)**
|
| 94 |
+
|
| 95 |
+
In the next article, we will guide you through the process of establishing a secure and automated system for secret management using Azure Key Vault.
|
| 96 |
+
Additionally, we will cover how to implement centralized log monitoring using Azure Log Analytics and Application Insights, enhancing observability and operational efficiency.
|
| 97 |
+
|
| 98 |
+
## Thank You
|
| 99 |
+
|
| 100 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 101 |
+
|
| 102 |
+
**Steven** | _[GitHub](https://github.com/baoduy)_
|
az-03-pulumi-private-ask-credential-log-management.md
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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title: "[Az] Day 03: Secret Management and Centralized Log Monitoring on Azure."
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- AKS
|
| 9 |
+
- Private
|
| 10 |
+
- Pulumi
|
| 11 |
+
description: "
|
| 12 |
+
In this tutorial, walk us through the process of establishing a secure and automated system for secret management using Azure Key Vault. Additionally, we will cover how to implement centralized log monitoring using Azure Log Analytics and Application Insights, enhancing observability and operational efficiency.
|
| 13 |
+
"
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
## Introduction
|
| 17 |
+
|
| 18 |
+
In this article, we will discuss the process of establishing a secure and automated system for secret management for the environment.
|
| 19 |
+
|
| 20 |
+
Additionally, we will cover how to implement centralized log monitoring enhancing observability and operational efficiency.
|
| 21 |
+
|
| 22 |
+
1. **Secret Management:**
|
| 23 |
+
Utilizes _Azure Key Vault_ to securely manage and store sensitive information such as credentials, certificates, and secrets. This guarantees consistent and secure access across all applications and services.
|
| 24 |
+
|
| 25 |
+
2. **Centralized Application Log Management:**
|
| 26 |
+
Implements a centralized logging system using _Azure Log Analytics_ and _Application Insights_ to collect and analyze logs from all applications. This setup allows for effective performance monitoring, issue troubleshooting, and operational insight maintenance across the environment.
|
| 27 |
+
|
| 28 |
+
3. **CI/CD flow:**
|
| 29 |
+

|
| 30 |
+
<p class="ml-44"><em>Illustration of the software CI/CD flow</em></p>
|
| 31 |
+
|
| 32 |
+
- The purpose of this CI/CD flow is to ensure that environment secrets, especially for production, are automatically generated by Pulumi and stored securely in Azure Key Vault.
|
| 33 |
+
- When developers need to deploy an application, they only need to specify the secret name in the deployment spec.
|
| 34 |
+
- During the deployment process, the CI/CD pipeline will automatically replace the secret name with the actual secret from Key Vault.
|
| 35 |
+
- This approach guarantees that sensitive production secrets remain secure and are not exposed to the team members.
|
| 36 |
+
|
| 37 |
+
## Table of Contents
|
| 38 |
+
|
| 39 |
+
## Configuration
|
| 40 |
+
|
| 41 |
+
Before we start coding, it's important to define our configuration settings. This involves specifying resource names and subnet address spaces that we'll use throughout the project.
|
| 42 |
+
|
| 43 |
+
### Resource Groups
|
| 44 |
+
|
| 45 |
+
We categorize our resources into different Azure resource groups for better organization and management:
|
| 46 |
+
|
| 47 |
+
| Resource Group | Description |
|
| 48 |
+
|---------------------------------|---------------------------------------------------------|
|
| 49 |
+
| **Shared Resource Group** | Where our Key Vault and logging components reside. |
|
| 50 |
+
| **Hub VNet Resource Group** | Contains our main VNet hub. |
|
| 51 |
+
| **AKS VNet Resource Group** | Contains resources specific to the AKS cluster. |
|
| 52 |
+
| **CloudPC VNet Resource Group** | For resources related to virtual desktops or cloud PCs. |
|
| 53 |
+
|
| 54 |
+
### Allocated Subnets
|
| 55 |
+
|
| 56 |
+
Again, this is the subnet Ip address spaces that we have defined in the [previous post](/posts/az-02-pulumi-private-ask-env-architecture#summary-of-allocated-subnets).
|
| 57 |
+
|
| 58 |
+
| VNet Name | Subnet Name | Address Prefix | Total | Usable |
|
| 59 |
+
|---------------------|--------------------------------|---------------------|-------|--------|
|
| 60 |
+
| **1. Hub VNet** | 1.1 Firewall Subnet | `192.168.30.0/26` | 64 | 59 |
|
| 61 |
+
| | 1.2 Firewall Management Subnet | `192.168.30.64/26` | 54 | 59 |
|
| 62 |
+
| | 1.3 General Subnet | `192.168.30.128/27` | 32 | 27 |
|
| 63 |
+
| **2. AKS VNet** | 2.1 AKS Subnet | `192.168.31.0/24` | 256 | 251 |
|
| 64 |
+
| **3. CloudPC VNet** | 3.1 CloudPC Subnet | `192.168.32.0/25` | 128 | 123 |
|
| 65 |
+
| | 3.2 DevOps Subnet | `192.168.32.128/27` | 32 | 27 |
|
| 66 |
+
|
| 67 |
+
### The configuration file
|
| 68 |
+
Here is the `config.ts` file will be used for all pulumi our projects:
|
| 69 |
+
|
| 70 |
+
<details><summary><em>View code:</em></summary>
|
| 71 |
+
|
| 72 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/config.ts#1-21)
|
| 73 |
+
|
| 74 |
+
</details>
|
| 75 |
+
|
| 76 |
+
> **Note:** Adding a number as a prefix to the Azure resource group names helps keep them sorted in sequence, making them easier to find and navigate.
|
| 77 |
+
|
| 78 |
+
## The `Common` Project
|
| 79 |
+
|
| 80 |
+
To promote code reusability and maintainability, we create a common project named `az-commons`.
|
| 81 |
+
This library contains utilities and helper functions that we'll use across all our Pulumi projects.
|
| 82 |
+
|
| 83 |
+
### The `azEnv` Module
|
| 84 |
+
|
| 85 |
+
This module provides functions to retrieve Azure environment configurations:
|
| 86 |
+
|
| 87 |
+
- **Tenant ID**: Identifies the Azure Active Directory (EntraID) tenant.
|
| 88 |
+
- **Subscription ID**: Identifies the Azure subscription where resources will be deployed.
|
| 89 |
+
- **Current Principal**: The object ID of the user or service principal executing the scripts.
|
| 90 |
+
- **Region Code**: The Azure region.
|
| 91 |
+
|
| 92 |
+
<details><summary><em>View code:</em></summary>
|
| 93 |
+
|
| 94 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-commons/azEnv.ts#1-1000)
|
| 95 |
+
|
| 96 |
+
</details>
|
| 97 |
+
|
| 98 |
+
### The `naming` Module
|
| 99 |
+
|
| 100 |
+
This module helps generate resource names with a consistent prefix based on the Pulumi stack name:
|
| 101 |
+
|
| 102 |
+
- **`getGroupName`**: Prepends the stack name to a resource group name.
|
| 103 |
+
- **`getName`**: uses to format the name with convention _{stack}-nameWithoutNumber-{suffix}_ and remove the numbers from the name.
|
| 104 |
+
|
| 105 |
+
<details><summary><em>View code:</em></summary>
|
| 106 |
+
|
| 107 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-commons/naming.ts#1-1000)
|
| 108 |
+
|
| 109 |
+
</details>
|
| 110 |
+
|
| 111 |
+
### The `stackEnv` Module
|
| 112 |
+
|
| 113 |
+
This module provides functions to retrieve Pulumi stack environment configurations:
|
| 114 |
+
|
| 115 |
+
- **`isDryRun`**: Indicates whether the current execution is a dry run (preview) or an actual deployment.
|
| 116 |
+
- **Organization**: The Pulumi organization name.
|
| 117 |
+
- **Project Name**: The name of the Pulumi project.
|
| 118 |
+
- **Stack**: The name of the Pulumi stack.
|
| 119 |
+
- **StackReference**: This helper function ensures that a project correctly references stacks within the same organization and environment.
|
| 120 |
+
For example, the `dev` stack of project `az-02-hub-vnet` will reference the `dev` stack of project `az-01-shared`.
|
| 121 |
+
This mechanism prevents cross-environment resource referencing, ensuring that resources from different environments (e.g., dev and prod) are kept isolated and properly aligned within the intended environment.
|
| 122 |
+
|
| 123 |
+
<details><summary><em>View code:</em></summary>
|
| 124 |
+
|
| 125 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-commons/stackEnv.ts#1-1000)
|
| 126 |
+
|
| 127 |
+
</details>
|
| 128 |
+
|
| 129 |
+
## The `Shared` Project
|
| 130 |
+
|
| 131 |
+
Following the instructions from [Day 01](/posts/az-01-pulumi-setup-developer-account), we create a new project named `az-01-shared`.
|
| 132 |
+
This project will include the following components:
|
| 133 |
+
|
| 134 |
+
### The `Vault` Module
|
| 135 |
+
|
| 136 |
+
Creating a `Azure Key Vault` is a secure storage solution for managing secrets, keys, and certificates. It helps safeguard cryptographic keys and secrets used by cloud applications and services.
|
| 137 |
+
|
| 138 |
+
- **Vault Options**:
|
| 139 |
+
- **enablePurgeProtection**: This option enables purge protection for the Key Vault. When enabled, it prevents the permanent deletion of the vault and its contents for a specified retention period, even if a delete operation is performed. This is crucial for compliance and recovery scenarios.
|
| 140 |
+
- **enabledForDiskEncryption**: This setting allows the Key Vault to be used for Azure Disk Encryption. It is necessary for encrypting virtual machine disks, ensuring that data at rest is protected.
|
| 141 |
+
- **softDeleteRetentionInDays**: This specifies the number of days that deleted vault items (like keys, secrets, and certificates) are retained in a "soft deleted" state. During this period, they can be recovered. The minimum value is 7 days, and the maximum is 90 days.
|
| 142 |
+
- **enableRbacAuthorization:** This enables Role-Based Access Control (RBAC) for managing access to the Key Vault. It requires authentication through EntraID, allowing for more granular and secure access management.
|
| 143 |
+
|
| 144 |
+
- **Vault Roles Management**: To implement the principle of least privilege, we create two EntraID groups:
|
| 145 |
+
- **AZ ROL DEV-SHARED-VLT READONLY**: For read-only access to the Key Vault.
|
| 146 |
+
- **AZ ROL DEV-SHARED-VLT WRITE**: For write access to the Key Vault.
|
| 147 |
+
|
| 148 |
+
<details><summary><em>View code:</em></summary>
|
| 149 |
+
|
| 150 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-01-shared/Vault.ts#1-1000)
|
| 151 |
+
|
| 152 |
+
</details>
|
| 153 |
+
|
| 154 |
+
### The `Log` Module
|
| 155 |
+
|
| 156 |
+
This module provisions a Log Analytics Workspace, which is used for collecting and analyzing telemetry data from various sources, providing insights into resource utilization and performance.
|
| 157 |
+
|
| 158 |
+
- **Workspace Options**:
|
| 159 |
+
- **immediatePurgeDataOn30Days**: which allows data to be purged immediately after 30 days.
|
| 160 |
+
- **workspaceCapping**: Sets a daily data ingestion quota to control costs and manage data volume.
|
| 161 |
+
- **sku**: Defines the pricing tier for the workspace, which affects cost and features.
|
| 162 |
+
|
| 163 |
+
<details><summary><em>View code:</em></summary>
|
| 164 |
+
|
| 165 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-01-shared/Log/Workspace.ts#1-1000)
|
| 166 |
+
|
| 167 |
+
</details>
|
| 168 |
+
|
| 169 |
+
### The `AppInsight` module
|
| 170 |
+
|
| 171 |
+
This module provisions an Application Insights component for monitoring web applications, linking it to a Log Analytics Workspace for data ingestion.
|
| 172 |
+
|
| 173 |
+
- **AppInsights Options**:
|
| 174 |
+
- **kind** and **applicationType**: Define the type of application being monitored, in this case, a web application.
|
| 175 |
+
- **retentionInDays**: Sets the data retention period to 30 days.
|
| 176 |
+
- **immediatePurgeDataOn30Days**: Allows data to be purged immediately after 30 days.
|
| 177 |
+
- **ingestionMode**: Specifies that data ingestion is done through Log Analytics.
|
| 178 |
+
|
| 179 |
+
<details><summary><em>View code:</em></summary>
|
| 180 |
+
|
| 181 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-01-shared/Log/AppInsight.ts#1-1000)
|
| 182 |
+
|
| 183 |
+
</details>
|
| 184 |
+
|
| 185 |
+
### The main `index.ts` module:
|
| 186 |
+
|
| 187 |
+
This is a main module for the `shared` project, and a similar structure is maintained across all related projects. This file is tasked with:
|
| 188 |
+
|
| 189 |
+
- Establishing Resource Groups.
|
| 190 |
+
- Deploying all the Azure Resources above.
|
| 191 |
+
- Exporting essential resource details for future use by other projects.
|
| 192 |
+
|
| 193 |
+
<details><summary><em>View code:</em></summary>
|
| 194 |
+
|
| 195 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-01-shared/index.ts#1-1000)
|
| 196 |
+
|
| 197 |
+
</details>
|
| 198 |
+
|
| 199 |
+
## Deployment and Cleanup
|
| 200 |
+
|
| 201 |
+
### Deploying the Stack
|
| 202 |
+
|
| 203 |
+
To deploy the stack, execute the `pnpm run up` command. This provisions the necessary Azure resources. We can verify the deployment as follows:
|
| 204 |
+
|
| 205 |
+
- EntraID groups configured for Key Vault access control:
|
| 206 |
+

|
| 207 |
+
|
| 208 |
+
- Successfully deployed Azure resources:
|
| 209 |
+

|
| 210 |
+
|
| 211 |
+
### Cleaning Up the Stack
|
| 212 |
+
|
| 213 |
+
To remove the stack and clean up all associated Azure resources, run the `pnpm run destroy` command. This ensures that any resources no longer needed are properly deleted.
|
| 214 |
+
|
| 215 |
+
## Conclusion
|
| 216 |
+
|
| 217 |
+
By following this guide, we have successfully automated the deployment of secure `secret management` and centralized `log management` using Azure Key Vault, Log Analytics, and Application Insights with Pulumi.
|
| 218 |
+
|
| 219 |
+
This setup ensures that sensitive data is securely stored and that we have real-time monitoring of application performance across our environment.
|
| 220 |
+
|
| 221 |
+
Implementing RBAC and the principle of least privilege enhances the security posture of our infrastructure. Centralized logging enables us to efficiently troubleshoot issues and gain operational insights.
|
| 222 |
+
|
| 223 |
+
## References
|
| 224 |
+
|
| 225 |
+
- [az-01-shared](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-01-shared).
|
| 226 |
+
- [az-commons](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-commons).
|
| 227 |
+
|
| 228 |
+
## Next
|
| 229 |
+
|
| 230 |
+
**[Day 04: Develops a Virtual Network Hub for Private AKS on Azure](/posts/az-04-pulumi-private-aks-hub-vnet-development)**
|
| 231 |
+
|
| 232 |
+
In the next article, We'll walk through the process of developing the first Hub VNet for a private AKS environment using Pulumi.
|
| 233 |
+
We will demonstrate how to seamlessly integrate a VNet with an Azure Firewall, along with configuring outbound public IP addresses.
|
| 234 |
+
|
| 235 |
+
## Thank You
|
| 236 |
+
|
| 237 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 238 |
+
|
| 239 |
+
**Steven** | _[GitHub](https://github.com/baoduy)_
|
az-04-pulumi-private-aks-hub-vnet-development.md
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-10-12T12:00:00Z
|
| 4 |
+
title: "[Az] Day 04: Develop a VNet Hub for Private AKS on Azure."
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- AKS
|
| 9 |
+
- Private
|
| 10 |
+
- Pulumi
|
| 11 |
+
description: "
|
| 12 |
+
In this tutorial, We’ll walk through the process of developing the first Hub VNet for a private AKS environment using Pulumi. We will demonstrate how to seamlessly integrate a VNet with an Azure Firewall, along with configuring outbound public IP addresses.
|
| 13 |
+
"
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
## Introduction
|
| 17 |
+
|
| 18 |
+
In this tutorial, we will guide you through the development of the initial Hub VNet for a private AKS environment using Pulumi.
|
| 19 |
+
|
| 20 |
+
We will demonstrate how to seamlessly integrate a VNet with an Azure Firewall, along with configuring outbound public IP addresses.
|
| 21 |
+
|
| 22 |
+
Security is paramount. Our focus will be on enhancing security by implementing network policies, firewalls, and encryption to safeguard our environment, all while maintaining cost-effectiveness on Azure.
|
| 23 |
+
|
| 24 |
+
## Table of Contents
|
| 25 |
+
|
| 26 |
+
## The Hub VNet modules
|
| 27 |
+
|
| 28 |
+
### The `VNet` Module
|
| 29 |
+
|
| 30 |
+
This module facilitates the creation of a Virtual Network, allowing for the specification of subnets as parameters. It also enables VNet encryption by default to enhance security.
|
| 31 |
+
|
| 32 |
+
<details><summary><em>View code:</em></summary>
|
| 33 |
+
|
| 34 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-02-hub-vnet/VNet.ts#1-1000)
|
| 35 |
+
|
| 36 |
+
</details>
|
| 37 |
+
|
| 38 |
+
### The `FirewallPolicy.ts` Module
|
| 39 |
+
|
| 40 |
+
This module is responsible for creating a FirewallPolicy resource, which serves as the root policy for the Azure Firewall. This root policy will be the foundation for linking additional policy groups in subsequent Pulumi projects.
|
| 41 |
+
|
| 42 |
+
<details><summary><em>View code:</em></summary>
|
| 43 |
+
|
| 44 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-02-hub-vnet/FirewallPolicy.ts#1-1000)
|
| 45 |
+
|
| 46 |
+
</details>
|
| 47 |
+
|
| 48 |
+
### The `Firewall.ts` Module
|
| 49 |
+
|
| 50 |
+
This module is designed to set up an Azure Firewall, including essential parts such as IP addresses and diagnostic settings.
|
| 51 |
+
It ensures the firewall is connected to the designated subnet within the VNet and is associated with the root policy resources.
|
| 52 |
+
|
| 53 |
+
<details><summary><em>View code:</em></summary>
|
| 54 |
+
|
| 55 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-02-hub-vnet/Firewall.ts#1-1000)
|
| 56 |
+
|
| 57 |
+
</details>
|
| 58 |
+
|
| 59 |
+
### Developing a Hub VNET
|
| 60 |
+
|
| 61 |
+
Our goal is to set up the main parts required for the Hub VNet, which include:
|
| 62 |
+
|
| 63 |
+
1. **Resource Group**: A container for managing related Azure resources.
|
| 64 |
+
2. **Virtual Network (VNet)**: The main network that hosts our subnets.
|
| 65 |
+
3. **Subnets**: Segments within the VNet to isolate and organize resources.
|
| 66 |
+
4. **Public IP Addresses**: For outbound internet connectivity and firewall management.
|
| 67 |
+
5. **Firewall Policy**: Defines rules to control network traffic.
|
| 68 |
+
6. **Azure Firewall**: A managed firewall service to protect our network.
|
| 69 |
+
|
| 70 |
+
<details><summary><em>View code:</em></summary>
|
| 71 |
+
|
| 72 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-02-hub-vnet/index.ts#1-1000)
|
| 73 |
+
|
| 74 |
+
</details>
|
| 75 |
+
|
| 76 |
+
> **Note:**
|
| 77 |
+
>
|
| 78 |
+
> - Properly setting the `dependsOn` property ensures that resources are created and destroyed in the correct sequence.
|
| 79 |
+
> - The code above demonstrates how to reuse the log workspace from the `az-01-shared` project for Firewall diagnostics, enabling effective tracing and monitoring of firewall rules.
|
| 80 |
+
|
| 81 |
+
## Deployment and Cleanup
|
| 82 |
+
|
| 83 |
+
### Deploying the Stack
|
| 84 |
+
|
| 85 |
+
To deploy the stack, execute the `pnpm run up` command. This provisions the necessary Azure resources. We can verify the deployment as follows:
|
| 86 |
+
|
| 87 |
+
- Successfully deployed Azure resources:
|
| 88 |
+

|
| 89 |
+
_Overview of successfully deployed Azure resources._
|
| 90 |
+
|
| 91 |
+
### Cleaning Up the Stack
|
| 92 |
+
|
| 93 |
+
To remove the stack and clean up all associated Azure resources, run the `pnpm run destroy` command. This ensures that any resources no longer needed are properly deleted.
|
| 94 |
+
|
| 95 |
+
## Conclusion
|
| 96 |
+
|
| 97 |
+
In this guide, we have successfully constructed a Hub Virtual Network (VNet) for our private AKS environment using Pulumi.
|
| 98 |
+
This Hub VNet serves as a crucial element in managing and securing access to all resources within our infrastructure, ensuring robust control and enhanced security measures.
|
| 99 |
+
|
| 100 |
+
## References
|
| 101 |
+
|
| 102 |
+
- [az-commons Source Code](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-commons/README.md)
|
| 103 |
+
- [az-02-hub-vnet Source Code](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-02-hub-vnet/README.md)
|
| 104 |
+
- [Azure DevOps IPs and FQDNs](https://learn.microsoft.com/en-us/azure/devops/organizations/security/allow-list-ip-url)
|
| 105 |
+
- [Pulumi for Azure](https://www.pulumi.com/docs/intro/cloud-providers/azure/)
|
| 106 |
+
|
| 107 |
+
## Next
|
| 108 |
+
|
| 109 |
+
**[Day 05: Implementing a Private AKS Cluster with Pulumi](/posts/az-05-pulumi-private-aks-cluster-env)**
|
| 110 |
+
|
| 111 |
+
In the next tutorial, We'll build a private AKS cluster with advanced networking features.
|
| 112 |
+
We'll explore how to integrate the AKS cluster with the Hub VNet and apply the firewall policies we've created.
|
| 113 |
+
|
| 114 |
+
## Thank You
|
| 115 |
+
|
| 116 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 117 |
+
|
| 118 |
+
**Steven** | _[GitHub](https://github.com/baoduy)_
|
az-05-pulumi-private-aks-cluster-env.md
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-10-12T12:00:00Z
|
| 4 |
+
title: "[Az] Day 05: Implementing a Private AKS Cluster with Pulumi."
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- AKS
|
| 9 |
+
- Private
|
| 10 |
+
- Pulumi
|
| 11 |
+
description: "
|
| 12 |
+
In this tutorial, We’ll build a private AKS cluster with advanced networking features. We’ll explore how to integrate the AKS cluster with the Hub VNet and apply the firewall policies we’ve created.
|
| 13 |
+
"
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
## Introduction
|
| 17 |
+
|
| 18 |
+
Building a private AKS cluster offers enhanced network security and complete control over ingress and egress traffic.
|
| 19 |
+
|
| 20 |
+
This tutorial will guide you through the setup of a private AKS cluster with advanced networking capabilities, integrating it into a sophisticated network architecture using Pulumi.
|
| 21 |
+
|
| 22 |
+
By the end of this guide, you'll know how to integrate the AKS cluster with a Hub VNet and apply firewall policies established in the [previous `az-02-hub-vnet` project](az-04-pulumi-private-aks-hub-vnet-development).
|
| 23 |
+
|
| 24 |
+
## Table of Contents
|
| 25 |
+
|
| 26 |
+
## The project modules
|
| 27 |
+
|
| 28 |
+
### The `ContainerRegistry.ts` Module
|
| 29 |
+
|
| 30 |
+
To enhance security and ensure that all Docker images deployed to our AKS cluster are verified, this module establishes a private Container Registry. By restricting AKS to pull images exclusively from this private registry, we eliminate the need to open firewalls on the public internet.
|
| 31 |
+
|
| 32 |
+
<details><summary><em>View code:</em></summary>
|
| 33 |
+
|
| 34 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-03-aks-cluster/ContainerRegistry.ts#1-1000)
|
| 35 |
+
|
| 36 |
+
</details>
|
| 37 |
+
|
| 38 |
+
### The `AksFirewallRules.ts` Module
|
| 39 |
+
|
| 40 |
+
This module sets up a **FirewallPolicyRuleCollectionGroup** with policies that enable controlled outbound communication for AKS nodes. The rules ensure that only necessary traffic is permitted, thus enhancing the security posture of our AKS cluster.
|
| 41 |
+
|
| 42 |
+
<details><summary><em>View code:</em></summary>
|
| 43 |
+
|
| 44 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-03-aks-cluster/AksFirewallRules.ts#1-1000)
|
| 45 |
+
|
| 46 |
+
</details>
|
| 47 |
+
|
| 48 |
+
### The `VNet.ts` Module
|
| 49 |
+
|
| 50 |
+
The Virtual Network (VNet) serves as the backbone for our AKS cluster. It provides the primary network environment that includes subnets dedicated to AKS nodes.
|
| 51 |
+
The VNet is peered with the Hub VNet to enable seamless integration with other services and to route all traffic through the Hub's firewall, ensuring all egress traffic is controlled.
|
| 52 |
+
|
| 53 |
+
1. **Security Group**: By default, the VNet allows resources in all subnets to access the internet. To enhance security, a security group is created with the following default rules:
|
| 54 |
+
|
| 55 |
+
- Block all internet access from all subnets.
|
| 56 |
+
- Allow VNet-to-VNet communication to enable hub-spoke connectivity.
|
| 57 |
+
- Additional security rules can be added through parameters.
|
| 58 |
+
|
| 59 |
+
<details><summary><em>View code:</em></summary>
|
| 60 |
+
|
| 61 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-03-aks-cluster/VNet.ts#1-1000)
|
| 62 |
+
|
| 63 |
+
</details>
|
| 64 |
+
|
| 65 |
+
2. **Route Table**: This VNet will peer with the hub, necessitating a route table to direct all traffic to the private IP address of the firewall.
|
| 66 |
+
|
| 67 |
+
<details><summary><em>View code:</em></summary>
|
| 68 |
+
|
| 69 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-03-aks-cluster/VNet.ts#1-1000)
|
| 70 |
+
|
| 71 |
+
</details>
|
| 72 |
+
|
| 73 |
+
3. **VNet**: Finally, the VNet is configured to create the route table and security group, injecting them into all provided subnets. Additionally, it establishes VNet peering with the hub VNet.
|
| 74 |
+
|
| 75 |
+
<details><summary><em>View code:</em></summary>
|
| 76 |
+
|
| 77 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-03-aks-cluster/VNet.ts#10-1000)
|
| 78 |
+
|
| 79 |
+
</details>
|
| 80 |
+
|
| 81 |
+
### The `AKS.ts` Module
|
| 82 |
+
|
| 83 |
+
1. **SSH Key Generation Custom Resource**: An SSH key is required for configuring an AKS cluster.
|
| 84 |
+
|
| 85 |
+
Due to Pulumi's lack of native SSH support, I use **[Dynamic Resource Providers](https://www.pulumi.com/docs/iac/concepts/resources/dynamic-providers/)** to create a custom component that dynamically generates an SSH key at runtime.
|
| 86 |
+
|
| 87 |
+
<details><summary><em>View SSH generator code:</em></summary>
|
| 88 |
+
|
| 89 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-03-aks-cluster/SshGenerator.ts#1-1000)
|
| 90 |
+
|
| 91 |
+
</details>
|
| 92 |
+
|
| 93 |
+
> This component also demonstrates how to securely store secrets within the Pulumi state.
|
| 94 |
+
|
| 95 |
+
Furthermore, a helper method uses the SSH generator alongside a random password to create an SSH public and private key pair and stored them in Key Vault for AKS.
|
| 96 |
+
|
| 97 |
+
<details><summary><em>View code:</em></summary>
|
| 98 |
+
|
| 99 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-03-aks-cluster/Aks.ts#78-116)
|
| 100 |
+
|
| 101 |
+
</details>
|
| 102 |
+
|
| 103 |
+
2. **AKS Identity Creation**: AKS can be configured to use Microsoft Entra ID for user authentication.
|
| 104 |
+
|
| 105 |
+
This setup allows users to sign in to an AKS cluster using a Microsoft Entra authentication to manage access to namespaces and cluster resources.
|
| 106 |
+
|
| 107 |
+
<details><summary><em>View code:</em></summary>
|
| 108 |
+
|
| 109 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-03-aks-cluster/Aks.ts#11-71)
|
| 110 |
+
|
| 111 |
+
</details>
|
| 112 |
+
|
| 113 |
+
3. **AKS Cluster Creation**: Finally, by integrating all components, we establish our AKS cluster. The source code contains several key elements worth noting.
|
| 114 |
+
<details><summary><em>View code:</em></summary>
|
| 115 |
+
|
| 116 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-03-aks-cluster/Aks.ts#121-1000)
|
| 117 |
+
|
| 118 |
+
</details>
|
| 119 |
+
|
| 120 |
+
## Developing a Private AKS Cluster
|
| 121 |
+
|
| 122 |
+
Our goal is to configure all necessary elements for the AKS Cluster, which include:
|
| 123 |
+
|
| 124 |
+
1. **Resource Group**: A container for organizing related Azure resources, simplifying management and cost tracking.
|
| 125 |
+
2. **Container Registry**: The main repository for all Docker images used by our private AKS, ensuring secure image deployment.
|
| 126 |
+
3. **AKS Firewall Policy**: To enable outbound internet connectivity, we must configure firewall rules that allow AKS nodes to communicate securely with essential Azure services.
|
| 127 |
+
4. **Virtual Network (VNet)**: The primary network hosting our AKS subnets, integrated with our Hub VNet to ensure secure and managed traffic flow.
|
| 128 |
+
5. **AKS Cluster**: An Azure-managed Kubernetes service, configured with advanced security and connectivity options.
|
| 129 |
+
|
| 130 |
+
<details><summary><em>View code:</em></summary>
|
| 131 |
+
|
| 132 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-03-aks-cluster/index.ts#1-1000)
|
| 133 |
+
|
| 134 |
+
</details>
|
| 135 |
+
|
| 136 |
+
## Deployment and Cleanup
|
| 137 |
+
|
| 138 |
+
### Deploying the Stack
|
| 139 |
+
|
| 140 |
+
To deploy the stack, execute the `pnpm run up` command. This provisions the necessary Azure resources. We can verify the deployment as follows:
|
| 141 |
+
|
| 142 |
+
- Successfully deployed Azure resources:
|
| 143 |
+

|
| 144 |
+
_Overview of successfully deployed Azure resources._
|
| 145 |
+
|
| 146 |
+
### Cleaning Up the Stack
|
| 147 |
+
|
| 148 |
+
To remove the stack and clean up all associated Azure resources, run the `pnpm run destroy` command. This ensures that any resources no longer needed are properly deleted.
|
| 149 |
+
|
| 150 |
+
## Conclusion
|
| 151 |
+
|
| 152 |
+
In this tutorial, we've successfully implemented a private AKS cluster with advanced networking features using Pulumi.
|
| 153 |
+
By setting up a private Container Registry, configuring firewall rules, and integrating the cluster with a Hub VNet, we have enhanced the security and manageability of our Kubernetes environment.
|
| 154 |
+
These steps ensure that the AKS cluster is well-secured and capable of meeting the demands of a production-grade infrastructure.
|
| 155 |
+
|
| 156 |
+
## References
|
| 157 |
+
|
| 158 |
+
- [Outbound network and FQDN rules for AKS clusters](https://learn.microsoft.com/en-us/azure/aks/outbound-rules-control-egress)
|
| 159 |
+
- [Dynamic resource providers](https://www.pulumi.com/docs/iac/concepts/resources/dynamic-providers/)
|
| 160 |
+
- [Use EntraID role-based access control for AKS](https://learn.microsoft.com/en-us/azure/aks/manage-azure-rbac?tabs=azure-cli)
|
| 161 |
+
- [Use a service principal with AKS](https://learn.microsoft.com/en-us/azure/aks/kubernetes-service-principal?tabs=azure-cli)
|
| 162 |
+
- [Best Practices for Private AKS Clusters](https://docs.microsoft.com/azure/aks/private-clusters)
|
| 163 |
+
|
| 164 |
+
## Next
|
| 165 |
+
|
| 166 |
+
**[Day 06: Implements a private CloudPC and DevOps Agent Hub with Pulumi](/posts/az-06-pulumi-private-aks-cloudpc-hub)**
|
| 167 |
+
|
| 168 |
+
In the next tutorial, it will guide us through setting up a secure CloudPC and DevOps agent hub, aimed at improving the management and operational capabilities of your private AKS environment using Pulumi.
|
| 169 |
+
|
| 170 |
+
## Thank You
|
| 171 |
+
|
| 172 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 173 |
+
|
| 174 |
+
**Steven** | _[GitHub](https://github.com/baoduy)_
|
az-06-pulumi-private-aks-cloudpc-hub.md
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-10-12T12:00:00Z
|
| 4 |
+
title: "[Az] Day 06: Implement a private CloudPC and DevOps Agent Hub with Pulumi."
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- AKS
|
| 9 |
+
- Private
|
| 10 |
+
- Pulumi
|
| 11 |
+
description: "
|
| 12 |
+
In this tutorial, guide us through setting up a secure CloudPC and DevOps agent hub, aimed at improving the management and operational capabilities of the private AKS environment using Pulumi.
|
| 13 |
+
"
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
## Introduction
|
| 17 |
+
|
| 18 |
+
Creating a secure private VNet for CloudPC (Windows 365 Enterprise) and Azure DevOps agent allows for an isolated network environment, enabling secure access, management, and control of cloud resources.
|
| 19 |
+
|
| 20 |
+
This guide will walk you through the process of setting up a private VNet using Pulumi, integrating it with the Hub VNet was created in the previous article.
|
| 21 |
+
|
| 22 |
+
## Table of Contents
|
| 23 |
+
|
| 24 |
+
## The project modules
|
| 25 |
+
|
| 26 |
+
### The `CloudPcFirewallRules` Module
|
| 27 |
+
|
| 28 |
+
This module defines the firewall policies for:
|
| 29 |
+
|
| 30 |
+
- **CloudPC**: We adhere to the recommended network rules for [Windows 365 Enterprise](https://learn.microsoft.com/en-us/windows-365/enterprise/requirements-network?tabs=enterprise%2Cent). Additionally, we ensure that all machines within the CloudPC subnet have access to AKS, DevOps subnets, and other Azure resources.
|
| 31 |
+
<details><summary><em>View code:</em></summary>
|
| 32 |
+
|
| 33 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-04-cloudPC/CloudPcFirewallRules/cloudpcPolicyGroup.ts#1-1000)
|
| 34 |
+
|
| 35 |
+
</details>
|
| 36 |
+
|
| 37 |
+
- **DevOps**: The current setup allows all machines in the DevOps subnet unrestricted access to all resources, including those on the internet. To improve security, it is recommended to restrict access to only necessary resources and implement more granular firewall rules.
|
| 38 |
+
<details><summary><em>View code:</em></summary>
|
| 39 |
+
|
| 40 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-04-cloudPC/CloudPcFirewallRules/devopsPolicyGroup.ts#1-1000)
|
| 41 |
+
|
| 42 |
+
</details>
|
| 43 |
+
|
| 44 |
+
- **Index File**: Combines CloudPC and DevOps rules into a unified `FirewallPolicyRuleCollectionGroup`, linking them to the root policy established in the `az-02-hub-vnet` project.
|
| 45 |
+
<details><summary><em>View code:</em></summary>
|
| 46 |
+
|
| 47 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-04-cloudPC/CloudPcFirewallRules/index.ts#1-1000)
|
| 48 |
+
|
| 49 |
+
</details>
|
| 50 |
+
|
| 51 |
+
### The `VNet.ts` Module
|
| 52 |
+
|
| 53 |
+
This module is responsible for creating a virtual network (VNet) with two subnets.
|
| 54 |
+
It also establishes peering with the Hub VNet that was set up in the previous project, similar to the VNet component used for AKS in `az-03-aks-cluster` project.
|
| 55 |
+
|
| 56 |
+
<details><summary><em>View code:</em></summary>
|
| 57 |
+
|
| 58 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-04-cloudPC/VNet.ts#78-172)
|
| 59 |
+
|
| 60 |
+
</details>
|
| 61 |
+
|
| 62 |
+
### The `DiskEncryptionSet.ts` Module
|
| 63 |
+
|
| 64 |
+
This module demonstrates how to encrypt Azure resources using a custom encryption key stored in Azure Key Vault. It includes the following components:
|
| 65 |
+
|
| 66 |
+
- **User Assigned Identity**: This identity is used to grant access to the Key Vault, allowing it to read the encryption key.
|
| 67 |
+
<details><summary><em>View code:</em></summary>
|
| 68 |
+
|
| 69 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-04-cloudPC/DiskEncryptionSet.ts#17-44)
|
| 70 |
+
|
| 71 |
+
</details>
|
| 72 |
+
|
| 73 |
+
- **Vault Encryption Key**: A custom encryption key with a size of 4096 bits, configured for automatic rotation every year within the Key Vault.
|
| 74 |
+
<details><summary><em>View code:</em></summary>
|
| 75 |
+
|
| 76 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-04-cloudPC/DiskEncryptionSet.ts#49-88)
|
| 77 |
+
|
| 78 |
+
</details>
|
| 79 |
+
|
| 80 |
+
- **Disk Encryption Set**: This component creates a `DiskEncryptionSet` using the User Assigned Identity and the custom encryption key mentioned above.
|
| 81 |
+
|
| 82 |
+
<details><summary><em>View code:</em></summary>
|
| 83 |
+
|
| 84 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-04-cloudPC/DiskEncryptionSet.ts#90-119)
|
| 85 |
+
|
| 86 |
+
</details>
|
| 87 |
+
|
| 88 |
+
### The `VM.ts` Module
|
| 89 |
+
|
| 90 |
+
This module facilitates the provisioning of a Linux virtual machine (VM)
|
| 91 |
+
on Azure with automatically generated login credentials and disk encryption and connects the VM to a subnet within the virtual network.
|
| 92 |
+
|
| 93 |
+
<details><summary><em>View code:</em></summary>
|
| 94 |
+
|
| 95 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-04-cloudPC/VM.ts#1-1000)
|
| 96 |
+
|
| 97 |
+
</details>
|
| 98 |
+
|
| 99 |
+
### The `PrivateDNS.ts` Module
|
| 100 |
+
|
| 101 |
+
To optimize internal network communication, we implement a DNS resolver. This module sets up a private DNS zone that facilitates efficient name resolution within our network infrastructure.
|
| 102 |
+
|
| 103 |
+
1. **Private DNS Zone**: Creates a dedicated DNS zone for internal use.
|
| 104 |
+
2. **VNet Links**: Establishes connections between the private DNS zone and both the Hub and CloudPC virtual networks.
|
| 105 |
+
3. **A Record**: Configures A record that points to the private IP address of our NGINX ingress controller.
|
| 106 |
+
> In the following topics, We will cover the NGINX ingress controller deployed on AKS as private ingress, and it will be assigned the internal IP address `192.168.31.250`. This IP must be within the AKS subnet range.
|
| 107 |
+
|
| 108 |
+
By linking this private DNS to both the Hub and CloudPC VNets, we ensure that all DNS requests for our internal services are correctly routed to the NGINX ingress controller. This setup enhances security and improves network performance by keeping internal traffic within our private network.
|
| 109 |
+
|
| 110 |
+
<details><summary><em>View code:</em></summary>
|
| 111 |
+
|
| 112 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-04-cloudPC/PrivateDNS.ts#1-1000)
|
| 113 |
+
|
| 114 |
+
</details>
|
| 115 |
+
|
| 116 |
+
## Developing the CloudPC Stack
|
| 117 |
+
|
| 118 |
+
Our objective is to establish a private Virtual Network (VNet) for CloudPC and Azure DevOps agents using Pulumi,
|
| 119 |
+
enabling us to provision the necessary Azure resources effectively.
|
| 120 |
+
|
| 121 |
+
1. **Firewall Policy**: Implement security policies to manage egress traffic for CloudPC and DevOps agents.
|
| 122 |
+
2. **VNet and Peering**: Develop the primary network infrastructure, including subnets for CloudPC and the Azure DevOps agent, with necessary VNet peering.
|
| 123 |
+
3. **Disk Encryption Set**: Integrate a disk encryption set to secure virtual machine data at rest.
|
| 124 |
+
4. **Deploy a Linux VM**: Provision a Linux virtual machine to host the Azure DevOps agent. The agent installation process will be covered in the following topic.
|
| 125 |
+
|
| 126 |
+
<details><summary><em>View code:</em></summary>
|
| 127 |
+
|
| 128 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/az-04-cloudPC/index.ts#1-1000)
|
| 129 |
+
|
| 130 |
+
</details>
|
| 131 |
+
|
| 132 |
+
## Deployment and Cleanup
|
| 133 |
+
|
| 134 |
+
### Deploying the Stack
|
| 135 |
+
|
| 136 |
+
To deploy the stack, run the `pnpm run up` command. This will provision all the necessary Azure resources, such as the Virtual Network (VNet), subnets, firewall, and private endpoints. Before executing the command, ensure you are logged into your Azure account using the Azure CLI and have configured Pulumi with the correct backend and credentials.
|
| 137 |
+
|
| 138 |
+

|
| 139 |
+
|
| 140 |
+
<p class="ml-44"><em>The deployed Azure resources</em></p>
|
| 141 |
+
|
| 142 |
+
### Cleaning Up the Stack
|
| 143 |
+
|
| 144 |
+
To remove all associated Azure resources and clean up the stack, execute the `pnpm run destroy` command. This will help avoid unnecessary costs and ensure that all resources are properly deleted after testing or development.
|
| 145 |
+
|
| 146 |
+
## References
|
| 147 |
+
|
| 148 |
+
- [Azure Virtual Network Documentation](https://learn.microsoft.com/en-us/azure/virtual-network/virtual-networks-overview)
|
| 149 |
+
- [Firewall Policies and Rule Collection Groups](https://learn.microsoft.com/en-us/azure/firewall/policy-overview)
|
| 150 |
+
- [Azure Bastion Configuration](https://learn.microsoft.com/en-us/azure/bastion/bastion-overview)
|
| 151 |
+
- [TeamServicesAgentLinux Extension](https://learn.microsoft.com/en-us/azure/devops/pipelines/release/deployment-groups/howto-provision-deployment-group-agents?view=azure-devops)
|
| 152 |
+
- [Network requirements For Windows 365 Enterprise](https://learn.microsoft.com/en-us/windows-365/enterprise/requirements-network?tabs=enterprise%2Cent)
|
| 153 |
+
- [AzureDevOps Allowed IP addresses and domain URLs](https://learn.microsoft.com/en-us/azure/devops/organizations/security/allow-list-ip-url?view=azure-devops&tabs=IP-V4)
|
| 154 |
+
|
| 155 |
+
## Next
|
| 156 |
+
|
| 157 |
+
**[Day 07: Setup Windows 365 Enterprise as a private VDI](/posts/az-07-setup-cloudpc-windows365-enterprise)**
|
| 158 |
+
|
| 159 |
+
In the next article, we will explore how to configure a CloudPC with Windows 365 Enterprise to establish a secure and efficient Virtual Desktop Infrastructure (VDI) for accessing a private AKS environment.
|
| 160 |
+
|
| 161 |
+
## Thank You
|
| 162 |
+
|
| 163 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 164 |
+
|
| 165 |
+
**Steven** | _[GitHub](https://github.com/baoduy)_
|
az-07-setup-cloudPC-windows365-enterprise.md
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-10-12T12:00:00Z
|
| 4 |
+
title: "[Az] Day 07: Setting Up a CloudPC with Windows 365 Enterprise."
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- AKS
|
| 9 |
+
- Private
|
| 10 |
+
- Pulumi
|
| 11 |
+
description: "
|
| 12 |
+
In this tutorial, We will explore how to configure a CloudPC with Windows 365 Enterprise to establish a secure and efficient Virtual Desktop Infrastructure (VDI) for accessing a private AKS environment.
|
| 13 |
+
"
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
## Introduction
|
| 17 |
+
|
| 18 |
+
In this article, we will learn how to set up a CloudPC with Windows 365 Enterprise to create a secure and efficient Virtual Desktop Infrastructure (VDI) for accessing a private AKS environment.
|
| 19 |
+
|
| 20 |
+
We will cover the essential steps, including configuring network settings, setting up provisioning profiles and policies with Microsoft Intune, and creating an Entra ID group to streamline the provisioning process.
|
| 21 |
+
|
| 22 |
+
## Obtaining a License
|
| 23 |
+
|
| 24 |
+
Before we begin the configuration, it is important to ensure that we have a `Windows 365 Enterprise license`. We can either purchase a new license or obtain a trial license through the [Microsoft 365 Admin Center](https://admin.microsoft.com).
|
| 25 |
+
|
| 26 |
+

|
| 27 |
+
|
| 28 |
+
> Note: A trial license is available, typically lasting one month, with the possibility of extending it for an additional month.
|
| 29 |
+
|
| 30 |
+
## Table of Contents
|
| 31 |
+
|
| 32 |
+
## Intune Configuration
|
| 33 |
+
|
| 34 |
+
Since Microsoft Intune is widely used for device management, we will not delve into its setup here. Instead, our focus will be on configuring Windows 365 Enterprise.
|
| 35 |
+
|
| 36 |
+
### Entra Provision Group
|
| 37 |
+
|
| 38 |
+
- First, we navigate to **Groups** in the [Microsoft Endpoint Manager Admin Center](https://intune.microsoft.com/#home) and create a new group named `MDM - IT Windows 365`.
|
| 39 |
+
|
| 40 |
+
<img alt="entra-windows365-group" src="/assets/az-07-pulumi-setup-cloudPC-windows365-enterprise/entra-windows365-group.png" width="550px">
|
| 41 |
+
|
| 42 |
+
- Then, we return to the **Microsoft 365 Admin Center** to assign the license to this group. This step automates the license assignment for all members within the group.
|
| 43 |
+
<img alt="entra-group-license-assignment" src="/assets/az-07-pulumi-setup-cloudPC-windows365-enterprise/entra-group-license-assignment.png" width="550px">
|
| 44 |
+
|
| 45 |
+
### Creating Provisioning Profiles
|
| 46 |
+
|
| 47 |
+
Once we have the license ready and assigned to our Entra ID group, we can proceed to create a provisioning profile for Windows 365 Enterprise.
|
| 48 |
+
|
| 49 |
+
- Navigate to **Devices** within Microsoft Intune, and then select **Provisioning** > **Windows 365**.
|
| 50 |
+
|
| 51 |
+
- Set up a new provisioning profile called `Windows 365 - IT Managed`.
|
| 52 |
+
- Join type: Select **Microsoft Entra Join**.
|
| 53 |
+
- Network: Choose **Azure network connection** and associate it with the previously established CloudPC subnet.
|
| 54 |
+
- Activate EntraID SSO: This will configure single sign-on (SSO) for the CloudPC.
|
| 55 |
+

|
| 56 |
+
|
| 57 |
+
### Provisioning CloudPC Devices
|
| 58 |
+
|
| 59 |
+
With our profile ready, we can start provisioning CloudPC devices for users. To do this, we need to make sure the target users are part of the `MDM - IT Windows 365` group.
|
| 60 |
+
|
| 61 |
+
- After adding users, the provisioning process will automatically start, and the devices will be ready for use within 1 hour.
|
| 62 |
+
|
| 63 |
+
- Once the provisioning is complete, the assigned users will be able to access their CloudPC through the Windows 365 portal.
|
| 64 |
+

|
| 65 |
+
|
| 66 |
+
## Accessing Windows 365
|
| 67 |
+
|
| 68 |
+
We can access our CloudPC in several ways:
|
| 69 |
+
|
| 70 |
+
1. **Online Portal Access**: We can access Windows 365 through the [online portal](https://windows365.microsoft.com).
|
| 71 |
+
|
| 72 |
+
This allows us to log in and launch the remote desktop directly within our web browser.
|
| 73 |
+
|
| 74 |
+

|
| 75 |
+
|
| 76 |
+
2. **Windows App Access**: Microsoft provides a _Windows App_ that enables us to launch Windows 365 natively.
|
| 77 |
+
|
| 78 |
+
This app is available for download from the Windows 365 online portal.
|
| 79 |
+
|
| 80 |
+

|
| 81 |
+
|
| 82 |
+
Once the app is installed, we can add the appropriate URL as a workspace and log in using our Entra ID. This setup allows us to launch and access Windows 365 natively on our platform.
|
| 83 |
+
|
| 84 |
+

|
| 85 |
+
|
| 86 |
+
3. **Private AKS Access**: with Windows 365 configured above, We can access to our private AKS cluster:
|
| 87 |
+
- **Through Azure Portal**: This allows us to access and manage AKS resources, including namespaces, pods, and deployments, directly in the browser.
|
| 88 |
+

|
| 89 |
+
|
| 90 |
+
- **Using Kubectl CLI**: To use the `kubectl` command locally, follow the Azure Portal instructions to set up our local environment. This setup requires the installation of `Azure CLI`, `kubectl`, and `kubelogin`.
|
| 91 |
+

|
| 92 |
+
|
| 93 |
+
- **Using Lens**: Lens is my favourite tool for managing Kubernetes clusters alternately for boring `kubectl` commands. You should be able to download it [here](https://k8slens.dev/).
|
| 94 |
+

|
| 95 |
+
|
| 96 |
+
## Conclusion
|
| 97 |
+
|
| 98 |
+
In this guide, we have successfully set up a CloudPC using Windows 365 Enterprise, configured the necessary provisioning profiles, and ensured secure access to our private AKS environment through a Virtual Desktop Infrastructure (VDI). This setup provides our teams with efficient, secure remote access that integrates seamlessly with our existing infrastructure.
|
| 99 |
+
|
| 100 |
+
## Reference
|
| 101 |
+
|
| 102 |
+
- [Overview of Windows 365 deployment](https://learn.microsoft.com/en-us/windows-365/enterprise/deployment-overview)
|
| 103 |
+
- [Start using Windows Autopatch](https://learn.microsoft.com/en-us/windows/deployment/windows-autopatch/prepare/windows-autopatch-feature-activation)
|
| 104 |
+
- [K8s Lens](https://k8slens.dev/)
|
| 105 |
+
|
| 106 |
+
## Next Topic
|
| 107 |
+
|
| 108 |
+
**[Day 08: Setting Up a Deployment Pipeline for Pulumi Projects.](/posts/az-08-pulumi-setup-deploy-cicd-pipeline)**
|
| 109 |
+
|
| 110 |
+
In the next article, we will walk through creating a Continuous Integration and Continuous Deployment (CI/CD) pipeline on Azure DevOps for our Pulumi projects.
|
| 111 |
+
|
| 112 |
+
## Thank You
|
| 113 |
+
|
| 114 |
+
Thank you for taking the time to read this guide! We hope it has been helpful. Feel free to explore further, and happy coding! 🌟✨
|
| 115 |
+
|
| 116 |
+
**Steven** | _[GitHub](https://github.com/baoduy)_
|
az-08-pulumi-setup-deploy-cicd-pipeline.md
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-10-12T12:00:00Z
|
| 4 |
+
title: "[Az] Day 08: Setting Up a Deployment Pipeline for Pulumi Projects."
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- AKS
|
| 9 |
+
- Private
|
| 10 |
+
- Pulumi
|
| 11 |
+
description: "
|
| 12 |
+
In this tutorial, We will walk through creating a Continuous Integration and Continuous Deployment (CI/CD) pipeline on Azure DevOps for our Pulumi projects.
|
| 13 |
+
"
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
## Introduction
|
| 17 |
+
In this tutorial, We will walk through creating a Continuous Integration and Continuous Deployment (CI/CD) pipeline on Azure DevOps for our Pulumi projects.
|
| 18 |
+
|
| 19 |
+
## Table of Contents
|
| 20 |
+
|
| 21 |
+
## Prerequisites
|
| 22 |
+
|
| 23 |
+
Ensure you have:
|
| 24 |
+
|
| 25 |
+
- An Azure DevOps account with a project.
|
| 26 |
+
- [Pulumi extensions](https://marketplace.visualstudio.com/items?itemName=pulumi.build-and-release-task) for Azure DevOps.
|
| 27 |
+
- Permissions to deploy resources in your Azure subscription.
|
| 28 |
+
|
| 29 |
+
## Preparation
|
| 30 |
+
|
| 31 |
+
### Pulumi Variable Group
|
| 32 |
+
|
| 33 |
+
Create a variable group in Azure DevOps **Libraries** named **pulumi**, and add the `PULUMI_ACCESS_TOKEN` variable:
|
| 34 |
+
<img alt="pulumi-variable-group" src="/assets/az-08-pulumi-setup-deploy-cicd-pipeline/pulumi-variable-group.png" width="450px">
|
| 35 |
+
|
| 36 |
+
### Setting Up Azure Resource Management Connection
|
| 37 |
+
|
| 38 |
+
1. Navigate to **Service connections** in Azure DevOps and create a new **Azure Workload Identity** connection named `az-pulumi` for **Azure Resource Management**:
|
| 39 |
+
<img alt="az-federation" src="/assets/az-08-pulumi-setup-deploy-cicd-pipeline/az-federation.png" width="450px">
|
| 40 |
+
|
| 41 |
+
> Note: Specifying a resource group is optional. This can be used to restrict the connection's access to a specific resource group if needed.
|
| 42 |
+
|
| 43 |
+
2. Once the service connection is established, verify the app registration presence in the Azure Portal here:
|
| 44 |
+

|
| 45 |
+
<p class="ml-44"><em>The app registration on Azure Portal</em></p>
|
| 46 |
+
|
| 47 |
+
3. Ensure the app registration has enough permissions for deployment:
|
| 48 |
+
- As an `Owner` and `Key Vault Administrator` roles at the **subscription** level.
|
| 49 |
+
- **Microsoft Graph** permissions to provide it with the necessary privileges for comprehensive deployment operations.
|
| 50 |
+

|
| 51 |
+
<p class="ml-40"><em>The API permission of the app registration</em></p>
|
| 52 |
+
- As member of `AZ ROL DEV-AKS-ADMIN` Entra Group: This is necessary for granting the permissions for Helm deployment on AzureDevOps.
|
| 53 |
+
|
| 54 |
+
## Deployment Templates
|
| 55 |
+
|
| 56 |
+
For reusability, several templates have been developed:
|
| 57 |
+
|
| 58 |
+
### Build Template: `build-template.yml`
|
| 59 |
+
|
| 60 |
+
- **Parameters**:
|
| 61 |
+
|
| 62 |
+
1. **stack**: Specifies the target Pulumi stack.
|
| 63 |
+
2. **workDir**: Defines the working directory of the Pulumi project.
|
| 64 |
+
|
| 65 |
+
- **Steps**:
|
| 66 |
+
|
| 67 |
+
1. **Install Node.js**: Install current Node LTS version.
|
| 68 |
+
2. **Setup pnpm**: Configures `pnpm` package management.
|
| 69 |
+
3. **Build Commons Project**: Installs dependencies and runs the build script for `az-commons`.
|
| 70 |
+
4. **Install Project Dependencies**: Installs dependencies for the specified `workDir`.
|
| 71 |
+
|
| 72 |
+
<details><summary><em>View yaml:</em></summary>
|
| 73 |
+
|
| 74 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/pipeline/pulumi/build-template.yml#1-1000)
|
| 75 |
+
|
| 76 |
+
</details>
|
| 77 |
+
|
| 78 |
+
### Deployment Template: `deploy-template.yml`
|
| 79 |
+
|
| 80 |
+
- **Parameters**:
|
| 81 |
+
|
| 82 |
+
1. **stack**: Specifies the target Pulumi stack.
|
| 83 |
+
2. **workDir**: Defines the working directory of the Pulumi project.
|
| 84 |
+
3. **azureSubscription**: Represents the Azure subscription connection.
|
| 85 |
+
|
| 86 |
+
- **Steps**:
|
| 87 |
+
|
| 88 |
+
1. **Install Pulumi CLI**: Install the latest version of the Pulumi CLI for Linux.
|
| 89 |
+
2. **Pulumi Refresh**: Refreshes the stack if the `pulumi.refresh` parameter is set to true.
|
| 90 |
+
3. **Pulumi Up After Refresh**: Executes `pulumi up` if `pulumi.refresh` is true, ensuring the stack is updated after a refresh.
|
| 91 |
+
4. **Pulumi Up**: Executes `pulumi up` to deploy the stack.
|
| 92 |
+
|
| 93 |
+
<details><summary><em>View yaml:</em></summary>
|
| 94 |
+
|
| 95 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/pipeline/pulumi/deploy-template.yml#1-1000)
|
| 96 |
+
|
| 97 |
+
</details>
|
| 98 |
+
|
| 99 |
+
> Using Pulumi refresh is essential for maintaining an accurate state. For more details, refer to [this article](https://www.pulumi.com/blog/repairing-state-with-pulumi-refresh/).
|
| 100 |
+
|
| 101 |
+
## Pulumi Deployment Pipeline
|
| 102 |
+
|
| 103 |
+
To establish a deployment pipeline in Azure DevOps, We'll create a new pipeline and use the `deploy.azure-pipelines.yml` file.
|
| 104 |
+
|
| 105 |
+
### YAML Configuration
|
| 106 |
+
|
| 107 |
+
1. **Trigger**: The pipeline is set to trigger automatically for branches matching the pattern _releases/\*_.
|
| 108 |
+
2. **Agent Pool**: We use the _ubuntu-latest_ agent pool for running our pipeline tasks.
|
| 109 |
+
3. **Variables**: The configuration includes several key variables:
|
| 110 |
+
- `pulumi`: A variable group containing essential Pulumi configuration settings.
|
| 111 |
+
- `azureSubscription`: The name of the Azure Resource Manager connection.
|
| 112 |
+
- `pnpm_config_cache`: The specified location for the pnpm cache.
|
| 113 |
+
- `env_name`: Dynamically derived from the branch name, determining the deployment environment.
|
| 114 |
+
|
| 115 |
+
### Pipeline Structure and Flow
|
| 116 |
+
|
| 117 |
+
Our pipeline consists of four distinct deployment stages. Each stage utilizes the `build-and-deploy.yml` template file, with appropriate parameters passed to it.
|
| 118 |
+
|
| 119 |
+
To initiate the pipeline:
|
| 120 |
+
|
| 121 |
+
1. Create a new branch named `releases/dev`
|
| 122 |
+
2. Push the changes to this branch
|
| 123 |
+
3. The pipeline will automatically trigger and run
|
| 124 |
+
|
| 125 |
+
Here's a visual representation of the deployment sequence:
|
| 126 |
+

|
| 127 |
+
|
| 128 |
+
<p class="ml-44"><em>Visualization of the Deployment Pipeline Stages</em></p>
|
| 129 |
+
|
| 130 |
+
The pipeline progresses through these stages in order, ensuring a systematic and controlled deployment process.
|
| 131 |
+
Each stage builds upon the previous one, allowing for a comprehensive and structured approach to deploying our Pulumi projects.
|
| 132 |
+
|
| 133 |
+
<details><summary><em>View yaml:</em></summary>
|
| 134 |
+
|
| 135 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/pipeline/pulumi/deploy.azure-pipelines.yml#1-1000)
|
| 136 |
+
|
| 137 |
+
</details>
|
| 138 |
+
|
| 139 |
+
## Pulumi Destroy Pipeline
|
| 140 |
+
|
| 141 |
+
This pipeline demonstrates how to safely destroy a Pulumi deployment stack. Exercise caution, as once a stack is destroyed, it cannot be restored.
|
| 142 |
+
|
| 143 |
+
To set up a destruction pipeline in Azure DevOps, use the `danger-destroy.azure-pipelines.yml` file.
|
| 144 |
+
The destruction states are reverted from the deployment state.
|
| 145 |
+
|
| 146 |
+
Here's a visual representation of the deployment sequence:
|
| 147 |
+

|
| 148 |
+
> Each stage in this process uses the `danger-build-and-destroy.yml` file with the necessary parameters.
|
| 149 |
+
|
| 150 |
+
<p class="ml-44"><em>Visualization of the Destroy Pipeline</em></p>
|
| 151 |
+
|
| 152 |
+
<details><summary><em>View yaml:</em></summary>
|
| 153 |
+
|
| 154 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/pipeline/pulumi/danger-destroy.azure-pipelines.yml#1-1000)
|
| 155 |
+
|
| 156 |
+
</details>
|
| 157 |
+
|
| 158 |
+
## Conclusion
|
| 159 |
+
|
| 160 |
+
In this tutorial, we've successfully set up a CI/CD pipeline using Pulumi and Azure DevOps.
|
| 161 |
+
This pipeline automates the deployment of infrastructure, ensuring that our environments are consistent, scalable, and easy to manage.
|
| 162 |
+
|
| 163 |
+
By leveraging Pulumi's abilities, we can integrate infrastructure as code into our development workflows, enhancing both efficiency and reliability.
|
| 164 |
+
|
| 165 |
+
## References
|
| 166 |
+
|
| 167 |
+
- [Pipeline Samples](https://github.com/baoduy/drunk-azure-pulumi-articles/tree/main/pipeline)
|
| 168 |
+
- [Pulumi extensions](https://marketplace.visualstudio.com/items?itemName=pulumi.build-and-release-task)
|
| 169 |
+
- [Pnpm Pipeline Config](https://pnpm.io/continuous-integration#azure-pipelines)
|
| 170 |
+
- [Repairing State With Pulumi Refresh](https://www.pulumi.com/blog/repairing-state-with-pulumi-refresh/).
|
| 171 |
+
|
| 172 |
+
## Next
|
| 173 |
+
|
| 174 |
+
**[Day 09: Synchronizing Container Images to ACR for a Private AKS Cluster Using CI/CD Pipelines.](/posts/az-09-private-aks-acr-image-sync)**
|
| 175 |
+
|
| 176 |
+
In the next article, We explore the process of synchronizing container images with ACR for deployments in a private AKS cluster. We'll cover how to configure and automate this synchronization using CI/CD pipelines, ensuring seamless updates and secure image management for private AKS environments.
|
| 177 |
+
|
| 178 |
+
## Thank You
|
| 179 |
+
|
| 180 |
+
Thank you for taking the time to read this guide! We hope it has been helpful. Feel free to explore further and happy coding! 🌟✨
|
| 181 |
+
|
| 182 |
+
**Steven** | _[GitHub](https://github.com/baoduy)_
|
az-09-private-aks-acr-image-sync.md
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-10-12T12:00:00Z
|
| 4 |
+
title: "[Az] Day 09: Synchronizing Container Images to ACR for a Private AKS Cluster Using CI/CD Pipelines."
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- AKS
|
| 9 |
+
- Pulumi
|
| 10 |
+
- CI/CD
|
| 11 |
+
- AzureDevOps
|
| 12 |
+
description: "
|
| 13 |
+
In this tutorial, We explore the process of synchronizing container images with ACR for deployments in a private AKS cluster. We’ll cover how to configure and automate this synchronization using CI/CD pipelines, ensuring seamless updates and secure image management for private AKS environments.
|
| 14 |
+
"
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
## Introduction
|
| 18 |
+
|
| 19 |
+
Deploying applications in a private AKS cluster presents unique challenges, especially when the cluster lacks direct internet access.
|
| 20 |
+
In such environments, the cluster cannot pull container images from public registries like Docker Hub or Quay.io.
|
| 21 |
+
Instead, all container images must be sourced from a private ACR accessible within the cluster's network.
|
| 22 |
+
|
| 23 |
+
To address this, we need a robust solution that not only synchronizes required images into the ACR but also integrates with Continuous Integration/Continuous Deployment (CI/CD) pipelines and adheres to Software Development Life Cycle (SDLC) best practices.
|
| 24 |
+
This ensures that all images are reviewed and approved before being imported, enhancing security and compliance.
|
| 25 |
+
|
| 26 |
+
## Table of Contents
|
| 27 |
+
|
| 28 |
+
## Implementation
|
| 29 |
+
|
| 30 |
+
By leveraging Azure DevOps CI/CD pipelines, we can automate the public image importing process as below.
|
| 31 |
+
|
| 32 |
+
### 1. Image Configuration File
|
| 33 |
+
|
| 34 |
+
The `images.txt` file lists all the container images that need to be imported into the private ACR.
|
| 35 |
+
|
| 36 |
+
Each line specifies the source image and the destination repository within the ACR, separated by `=>`. This format allows for easy maintenance and review of the images being imported.
|
| 37 |
+
|
| 38 |
+
<details><summary><em>Example <code>images.txt</code></em></summary>
|
| 39 |
+
|
| 40 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/pipeline/image-sync/images.txt#1-1000)
|
| 41 |
+
|
| 42 |
+
</details>
|
| 43 |
+
|
| 44 |
+
- **Source Image:** The full path to the image in the public registry, including the tag.
|
| 45 |
+
- **Destination Repository:** The repository path within the ACR where the image will be imported.
|
| 46 |
+
- **Comments:** Lines starting with `#` are treated as comments and ignored by the script.
|
| 47 |
+
|
| 48 |
+
### 2. Synchronization Script
|
| 49 |
+
|
| 50 |
+
The `sync-script.sh` script automates the process of importing images listed in `images.txt` into the ACR. It reads each line of the configuration file, processes the source and destination information, and uses the Azure CLI to import the images.
|
| 51 |
+
|
| 52 |
+
<details><summary><em>View code</em></summary>
|
| 53 |
+
|
| 54 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/pipeline/image-sync/sync-script.sh#1-1000)
|
| 55 |
+
|
| 56 |
+
</details>
|
| 57 |
+
|
| 58 |
+
### 3. Azure Pipeline
|
| 59 |
+
|
| 60 |
+
To streamline the synchronization process, we utilize a CI/CD pipeline. This pipeline is designed to automatically execute the synchronization script whenever there are updates to the `images.txt` file, ensuring that all container images in the ACR remain current.
|
| 61 |
+
|
| 62 |
+
<details><summary><em>View code</em></summary>
|
| 63 |
+
|
| 64 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/image-sync-pipeline/image-sync.azure-pipelines.yml#1-1000)
|
| 65 |
+
|
| 66 |
+
</details>
|
| 67 |
+
|
| 68 |
+
**Important Variables:**
|
| 69 |
+
|
| 70 |
+
- The `image-sync` variable group contains the `DOCKER_NAME` and `DOCKER_TOKEN`, which are essential for accessing Docker Hub and avoiding rate limits.
|
| 71 |
+
- The `azureSubscription` with a specific Azure service connection name in Azure DevOps.
|
| 72 |
+
- Replace `acrName` with the actual name of the Azure Container Registry.
|
| 73 |
+
|
| 74 |
+

|
| 75 |
+
|
| 76 |
+
Once the pipeline completes successfully, you can verify that all images have been correctly imported into the ACR.
|
| 77 |
+

|
| 78 |
+
|
| 79 |
+
<p class="ml-44"><em>The imported images on ACR repositories</em></p>
|
| 80 |
+
|
| 81 |
+
## Conclusion
|
| 82 |
+
|
| 83 |
+
Synchronizing container images for a private AKS cluster without direct internet access requires careful planning and automation. By leveraging a combination of an image configuration file, a synchronization script, and an Azure DevOps CI/CD pipeline, we can:
|
| 84 |
+
|
| 85 |
+
- Automate the import of necessary images into a private ACR.
|
| 86 |
+
- Ensure that all images are reviewed and approved according to SDLC practices.
|
| 87 |
+
- Maintain a secure and compliant deployment environment within the private AKS cluster.
|
| 88 |
+
|
| 89 |
+
This approach not only streamlines the deployment process but also integrates seamlessly with existing development workflows, promoting efficiency and reliability in managing containerized applications.
|
| 90 |
+
|
| 91 |
+
## References
|
| 92 |
+
|
| 93 |
+
- [Image importing pipeline](https://github.com/baoduy/drunk-azure-pulumi-articles/tree/main/image-sync-pipeline)
|
| 94 |
+
- [Azure Container Registry Documentation](https://docs.microsoft.com/azure/container-registry/)
|
| 95 |
+
|
| 96 |
+
## Next
|
| 97 |
+
|
| 98 |
+
**[Day 10: Implementing a Helm Deployment CI/CD AzureDevOps Pipeline for a Private AKS Cluster.](/posts/az-10-private-aks-helm-deployment)**
|
| 99 |
+
|
| 100 |
+
In the next article, We will create Helm charts for nginx-ingress and cert-manager, and set up a robust CI/CD pipeline using Azure DevOps for Helm deployments to a private AKS cluster.
|
| 101 |
+
|
| 102 |
+
## Thank You
|
| 103 |
+
|
| 104 |
+
Thank you for taking the time to read this guide! We hope it has been helpful. Feel free to explore further and happy coding! 🌟✨
|
| 105 |
+
|
| 106 |
+
**Steven** | _[GitHub](https://github.com/baoduy)_
|
az-10-private-aks-helm-deployment.md
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-10-12T12:00:00Z
|
| 4 |
+
title: "[Az] Day 10: Implementing a Helm Deployment CI/CD AzureDevOps Pipeline for a Private AKS Cluster."
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- AKS
|
| 9 |
+
- Helm
|
| 10 |
+
- CI/CD
|
| 11 |
+
- AzureDevOps
|
| 12 |
+
description: "
|
| 13 |
+
In this tutorial, We will create Helm charts for nginx-ingress and cert-manager, and set up a robust CI/CD pipeline using Azure DevOps for Helm deployments to a private AKS cluster.
|
| 14 |
+
"
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
## Introduction
|
| 18 |
+
|
| 19 |
+
In our previous article, we covered the process of importing Docker images into a private Azure Container Registry (ACR).
|
| 20 |
+
Building on that foundation, this guide will walk you through creating Helm charts for nginx-ingress and cert-manager, and setting up a comprehensive Helm deployment pipeline for your private Azure Kubernetes Service (AKS) cluster using Azure DevOps.
|
| 21 |
+
|
| 22 |
+
## Table of Contents
|
| 23 |
+
|
| 24 |
+
## Configuring an Azure DevOps Agent
|
| 25 |
+
|
| 26 |
+
To streamline the deployment process of your Helm charts, it's crucial to set up and configure an Azure DevOps agent on the virtual machine (VM) provisioned by the _az-04-cloudPC_ project.
|
| 27 |
+
This setup ensures that your CI/CD pipeline functions smoothly within a private network environment.
|
| 28 |
+
|
| 29 |
+
### Installing the Azure DevOps Agent
|
| 30 |
+
|
| 31 |
+
1. Log into your virtual machine using Windows 365 Virtual Desktop Infrastructure (VDI).
|
| 32 |
+
2. Follow the detailed instructions in the [Microsoft documentation](https://learn.microsoft.com/en-gb/azure/devops/pipelines/agents/linux-agent?view=azure-devops) to install the Azure DevOps agent on a Linux-based VM.
|
| 33 |
+
3. Once installed, assign the agent to the `aks-agents` pool to optimize resource allocation.
|
| 34 |
+
|
| 35 |
+
After installed, the agent should be listed under Azure DevOps project's agents as below:
|
| 36 |
+

|
| 37 |
+
|
| 38 |
+
### Installing Essential Tools
|
| 39 |
+
|
| 40 |
+
For effective Helm chart deployment, ensure the following tools are installed on the agent:
|
| 41 |
+
|
| 42 |
+
- **Azure CLI**: Required for managing Azure resources. Follow the installation guide [here](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli-linux?pivots=apt).
|
| 43 |
+
- **KubeLogin**: This is a client-go credential plugin implementing azure authentication and required for pipeline deployment to authenticate with AKS using Service Principal. Refer [here](https://azure.github.io/kubelogin/install.html).
|
| 44 |
+
- **Helm CLI**: Essential for managing Kubernetes applications. Refer to the installation instructions [here](https://helm.sh/docs/intro/install/).
|
| 45 |
+
- **Kubectl**: Necessary for Kubernetes cluster management. Installation guidance is available [here](https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/).
|
| 46 |
+
|
| 47 |
+
> Note: After installing these tools, restart the VM to ensure that the installations are correctly applied and effective.
|
| 48 |
+
|
| 49 |
+
### Azure DevOps Extensions
|
| 50 |
+
|
| 51 |
+
To facilitate our deployment process, we'll be using the [Replace Tokens](https://marketplace.visualstudio.com/items?itemName=qetza.replacetokens) extension for Azure Pipelines.
|
| 52 |
+
This task replaces tokens in text-based files with actual variable values, allowing for dynamic configuration of our Helm charts.
|
| 53 |
+
Ensure this extension is installed in your Azure DevOps environment before proceeding with the pipeline setup.
|
| 54 |
+
|
| 55 |
+
## Nginx and Cert Manager Helm Chart
|
| 56 |
+
|
| 57 |
+
Our Helm chart is designed to deploy three essential parts:
|
| 58 |
+
|
| 59 |
+
1. **Nginx Ingress Controller**: This internal ingress controller will service traffic at the IP address `192.168.31.250`, using the internal domain `drunkcoding.net`.
|
| 60 |
+
2. **Cert-Manager**: This component is responsible for generating SSL certificates for all internal subdomains. It also monitors certificate expiration and handles timely renewals.
|
| 61 |
+
3. **Let's Encrypt ClusterIssuer**: The chart includes templates to deploy a Let's Encrypt ClusterIssuer, enabling Cert-Manager to issue free SSL certificates from Let's Encrypt.
|
| 62 |
+
|
| 63 |
+
<details><summary><em>View the <code>Chart.yaml</code> file</em></summary>
|
| 64 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/pipeline/ingress-helm/Chart.yaml#1-1000)
|
| 65 |
+
|
| 66 |
+
</details>
|
| 67 |
+
|
| 68 |
+
### Env-Variables Values
|
| 69 |
+
|
| 70 |
+
We've created a `values-dev.yaml` file to configure our development environment.
|
| 71 |
+
- **Chart Variables**: Tokens in the format `${{Name}}` are placeholders for variables that will be populated from the pipeline during deployment. These variables can be sourced from library groups, Azure Key Vault, or inline variables.
|
| 72 |
+
- **Chart Images**: All chart images are configured to be pulled from our internal Azure Container Registry (ACR), which was set up in the previous topic.
|
| 73 |
+
|
| 74 |
+
<details><summary><em>View the <code>values-dev.yaml</code> file</em></summary>
|
| 75 |
+
|
| 76 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/pipeline/ingress-helm/values-dev.yaml#1-1000)
|
| 77 |
+
|
| 78 |
+
</details>
|
| 79 |
+
|
| 80 |
+
### Setting Up an Azure DevOps Pipeline
|
| 81 |
+
|
| 82 |
+
With our Helm charts prepared, it's time to create an Azure DevOps pipeline to deploy these to our secure AKS cluster.
|
| 83 |
+
|
| 84 |
+
**Pipeline Preparation:**
|
| 85 |
+
- First, go to your Git repository and start a new pipeline. Choose "Existing pipeline" and choose the `ingress-helm.azure-pipelines.yml` file.
|
| 86 |
+
- Next, We'll need to set up some variables for this pipeline:
|
| 87 |
+
1. `cf-dns`: This group includes two key details:
|
| 88 |
+
- `cf-domain`: This is the Cloudflare domain, used here for SSL verification since we are managing DNS internally.
|
| 89 |
+
- `cf-dns-token`: A token from Cloudflare that lets us edit DNS; it has certain permissions. You can refer [here](/posts/ks-08-cert-manager-with-private-aks) for guidance on setting this up.
|
| 90 |
+
<img alt="cf-variable-group" src="/assets/az-10-private-aks-helm-deployment/cf-variable-group.png" width="450px">
|
| 91 |
+
2. `env_name`: This should be the name of the branch from which the pipeline building.
|
| 92 |
+
3. `azureSubscription`: The name of your Azure subscription, set as _az-pulumi_ from previous steps. Make sure this account can manage Helm deployment and is part of the `AZ ROL DEV-AKS-ADMIN` group within AKS Admin Active Directory.
|
| 93 |
+
4. `rsGroup`: The name of the Azure resource group that contains your AKS cluster.
|
| 94 |
+
5. `aksName`: The name given to your AKS cluster.
|
| 95 |
+
6. `acrName`: The name of the Azure Container Registry.
|
| 96 |
+
7. `private-ip`: A dedicated private IP for the ingress controller.
|
| 97 |
+
8. `valueFile`: The specific Helm values file name only.
|
| 98 |
+
9. `chart`: The location of Helm chart.
|
| 99 |
+
10. `releaseName`: The name of the Helm release.
|
| 100 |
+
|
| 101 |
+
**Pipeline Deployment:**
|
| 102 |
+
- Once the deployment is successful:
|
| 103 |
+

|
| 104 |
+
|
| 105 |
+
- We'll find that the pods are now active within the `nginx-ingress` namespace.
|
| 106 |
+

|
| 107 |
+
|
| 108 |
+
<details><summary><em>View the <code>values-dev.yaml</code> here</em></summary>
|
| 109 |
+
|
| 110 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/pipeline/ingress-helm/ingress-helm.azure-pipelines.yml#1-1000)
|
| 111 |
+
|
| 112 |
+
</details>
|
| 113 |
+
|
| 114 |
+
## Application Helm Chart
|
| 115 |
+
|
| 116 |
+
Now, let's create another Helm chart to deploy our applications. For this example, we'll use a Helm chart to deploy the `azuredocs/aks-helloworld:v1` image, provided by the Microsoft AKS team for demonstration purposes. Once deployed, the cert-manager will automatically issue an SSL certificate for the subdomain `hello.drunkcoding.net`, enabling us to access the application via Windows 365 VDI.
|
| 117 |
+
**Pipeline Deployment:**
|
| 118 |
+
- Upon successful deployment:
|
| 119 |
+

|
| 120 |
+
|
| 121 |
+
- The application pods should now be active within the `drunk-apps` namespace.
|
| 122 |
+

|
| 123 |
+
|
| 124 |
+
- The SSL certificate `tls-hello-world-lets` should be successfully issued and stored in the `drunk-apps` namespace's secrets.
|
| 125 |
+

|
| 126 |
+
|
| 127 |
+
**Application Access:**
|
| 128 |
+
- Access the app via Windows 365 VDI:
|
| 129 |
+

|
| 130 |
+
|
| 131 |
+
<details><summary><em>View the app helm chart here</em></summary>
|
| 132 |
+
|
| 133 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/pipeline/drunk-apps-helm/drunk-apps-helm.azure-pipelines.yml#1-1000)
|
| 134 |
+
|
| 135 |
+
</details>
|
| 136 |
+
|
| 137 |
+
## Conclusion
|
| 138 |
+
|
| 139 |
+
In this guide, we've walked through the process of creating Helm charts for nginx-ingress and cert-manager, and setting up an Azure DevOps pipeline to deploy these charts to a private AKS cluster. This approach allows for easy management and deployment of these critical components in your Kubernetes infrastructure.
|
| 140 |
+
|
| 141 |
+
By leveraging Helm and Azure DevOps, We can ensure consistent and repeatable deployments across your environments, making it easier to manage and scale your applications in a private AKS cluster.
|
| 142 |
+
|
| 143 |
+
Remember to always follow security best practices, such as using Azure Key Vault for storing sensitive information and regularly updating your deployments with the latest security patches.
|
| 144 |
+
|
| 145 |
+
## References
|
| 146 |
+
|
| 147 |
+
- [Nginx Helm Chart](https://github.com/baoduy/drunk-azure-pulumi-articles/tree/main/pipeline/ingress-helm)
|
| 148 |
+
- [Drunk Apps Helm Chart](https://github.com/baoduy/drunk-azure-pulumi-articles/tree/main/pipeline/drunk-apps-helm)
|
| 149 |
+
- [Self-hosted Linux agents](https://learn.microsoft.com/en-gb/azure/devops/pipelines/agents/linux-agent?view=azure-devops)
|
| 150 |
+
- [Helm Documentation](https://helm.sh/docs/)
|
| 151 |
+
- [Nginx Ingress Controller Documentation](https://kubernetes.github.io/ingress-nginx/)
|
| 152 |
+
- [Cert-Manager Documentation](https://cert-manager.io/docs/)
|
| 153 |
+
- [AzureDevOps Replace Token Extension](https://marketplace.visualstudio.com/items?itemName=qetza.replacetokens&targetId=aed13a53-890d-4411-a029-49b8b9bf9004&utm_source=vstsproduct&utm_medium=ExtHubManageList)
|
| 154 |
+
|
| 155 |
+
## Next
|
| 156 |
+
|
| 157 |
+
**[Day 11: Exposing a Private AKS Application via Cloudflare Tunnel.](/posts/az-11-private-aks-expose-public-app-with-cloudflare-tunnel)**
|
| 158 |
+
|
| 159 |
+
In the next article, We demonstrate how to securely expose an application running on a private AKS cluster to the internet using Cloudflare Tunnel, without the need for public IP addresses or open ports. We'll also show how to apply authentication to all exposed applications and centralize access control using Azure Entra ID Groups, ensuring only authorized users have access.
|
| 160 |
+
|
| 161 |
+
## Thank You
|
| 162 |
+
|
| 163 |
+
Thank you for taking the time to read this guide! We hope it has been helpful in setting up your Helm deployment pipeline for a private AKS cluster. Feel free to explore further and happy deploying! 🚀🌟
|
| 164 |
+
|
| 165 |
+
**Steven** | _[GitHub](https://github.com/baoduy)_
|
az-11-private-aks-expose-public-app-with-cloudflare-tunnel.md
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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12T12:00:00Z
|
| 4 |
+
title: "[Az] Day 11: Exposing a Private AKS Application via Cloudflare Tunnel."
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- AKS
|
| 9 |
+
- Helm
|
| 10 |
+
- CI/CD
|
| 11 |
+
- AzureDevOps
|
| 12 |
+
- Cloudflare
|
| 13 |
+
- Tunnel
|
| 14 |
+
description: "
|
| 15 |
+
In this tutorial, We demonstrate how to securely expose an application running on a private AKS cluster to the internet using Cloudflare Tunnel, without the need for public IP addresses or open ports. We’ll also show how to apply authentication to all exposed applications and centralize access control using Azure Entra ID Groups, ensuring only authorized users have access.
|
| 16 |
+
"
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
## Introduction
|
| 20 |
+
In environments with stringent security policies, exposing applications hosted on private AKS clusters to the internet without compromising security can be challenging. These environments often have **no inbound internet access** and **no open ports**, limiting conventional methods of application exposure.
|
| 21 |
+
|
| 22 |
+
In this guide, we’ll walk through how to securely expose an application hosted on a private AKS cluster to the internet using **Cloudflare Tunnel**, a solution that eliminates the need for public IP addresses or open ports. Additionally, we’ll demonstrate how to secure the application with **Cloudflare Access** integrated with **Azure EntraID Single Sign-On (SSO)**.
|
| 23 |
+
|
| 24 |
+
## Table of Contents
|
| 25 |
+
|
| 26 |
+
## Prerequisites
|
| 27 |
+
|
| 28 |
+
Before diving into Cloudflare Tunnel, make sure you have the following set-up:
|
| 29 |
+
|
| 30 |
+
- **Cloudflare Zero Trust:** You need an active Cloudflare account with the [Zero Trust feature](https://developers.cloudflare.com/cloudflare-one/setup/) enabled to set up a Cloudflare Tunnel.
|
| 31 |
+
|
| 32 |
+
## Setting Up Cloudflare Tunnel
|
| 33 |
+
|
| 34 |
+
**Cloudflare Tunnel** (formerly Argo Tunnel) provides a secure connection between your services and Cloudflare without the need for public IP addresses or inbound firewall rules.
|
| 35 |
+
|
| 36 |
+
### Generate Tunnel Token
|
| 37 |
+
|
| 38 |
+
To get started, follow these steps to create a Cloudflare Tunnel token:
|
| 39 |
+
|
| 40 |
+
1. **Sign in to Cloudflare**
|
| 41 |
+
Log in to your Cloudflare account and navigate to the [Zero Trust dashboard](https://one.dash.cloudflare.com).
|
| 42 |
+
|
| 43 |
+
2. **Create a Tunnel**
|
| 44 |
+
Go to **Network** and select **Tunnels**. Click **Create a tunnel** and choose the `cloudflared` option.
|
| 45 |
+

|
| 46 |
+
|
| 47 |
+
3. **Name and Save the Tunnel**
|
| 48 |
+
Name your tunnel `private-aks-tunnel` and click **Save**.
|
| 49 |
+
|
| 50 |
+
4. **Copy Tunnel Token**
|
| 51 |
+
Once the tunnel is created, a token will be generated. Copy the tunnel token and securely store it in **Azure Key Vault** as a secret named `cf-tunnel-token`.
|
| 52 |
+

|
| 53 |
+
> Ensure that the token is accurately stored in the Key Vault. This token will be used when deploying the `cloudflared` Helm chart.
|
| 54 |
+
|
| 55 |
+
### Deploying **Cloudflared** with Helm
|
| 56 |
+
|
| 57 |
+
With the secure storage of the tunnel token in Key Vault, follow these refined steps to deploy **cloudflared** on the AKS cluster using Helm:
|
| 58 |
+
|
| 59 |
+
1. **Cloudflared Chart:**
|
| 60 |
+
|
| 61 |
+
I created the [cloudflared Helm chart](https://github.com/baoduy/drunk-azure-pulumi-articles/tree/main/pipeline/cf-tunnel-helm), expanding upon the previous chart template.
|
| 62 |
+
This implementation establishes an AKS network policy that blocks inbound traffic to the namespace while allowing only the necessary outbound traffic to the internal Nginx Ingress using the private IP `192.168.31.250`.
|
| 63 |
+
|
| 64 |
+
<details><summary><em>View the <code>values-dev.yaml</code> file</em></summary>
|
| 65 |
+
|
| 66 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/pipeline/cf-tunnel-helm/values-dev.yaml#1-1000)
|
| 67 |
+
|
| 68 |
+
</details>
|
| 69 |
+
|
| 70 |
+
2. **Cloudflared Deployment Pipeline:**
|
| 71 |
+
|
| 72 |
+
This pipeline mirrors the previous pipeline, with an additional enhancement to directly retrieve secrets from the Key Vault, bypassing the need for a Variable Group.
|
| 73 |
+
|
| 74 |
+
<details><summary><em>View the <code>network-rule.yaml</code> file</em></summary>
|
| 75 |
+
|
| 76 |
+
[inline](https://github.com/baoduy/drunk-azure-pulumi-articles/blob/main/pipeline/cf-tunnel-helm/templates/network-rule.yaml#1-1000)
|
| 77 |
+
|
| 78 |
+
</details>
|
| 79 |
+
|
| 80 |
+
> **Important:**
|
| 81 |
+
> - To optimize the Cloudflare Tunnel's outbound operations, adjust the AKS firewall settings in accordance with [Cloudflare's recommendations](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/deploy-tunnels/tunnel-with-firewall).
|
| 82 |
+
> - These settings are required for the tunnel's ability to establish and maintain effective communication with Cloudflare servers, handling inbound requests seamlessly.
|
| 83 |
+
|
| 84 |
+
### Deploying the Cloudflare Tunnel
|
| 85 |
+
|
| 86 |
+
1. Create a new pipeline named `cf-tunnel-helm` with the `cf-tunnel-helm.azure-pipelines.yml` file, enabling the deployment
|
| 87 |
+
of this Helm chart to AKS.
|
| 88 |
+
|
| 89 |
+

|
| 90 |
+
|
| 91 |
+
2. Once deployment is successful, the Cloudflare Tunnel pods should be running within the `cf-system` namespace.
|
| 92 |
+

|
| 93 |
+
|
| 94 |
+
3. Return to the [Cloudflare Zero Trust](https://one.dash.cloudflare.com) dashboard to verify the tunnel status, which should display as healthy.
|
| 95 |
+

|
| 96 |
+
|
| 97 |
+
## Exposing the Application
|
| 98 |
+
|
| 99 |
+
With all preparations complete, we can now expose the application to the internet follow these steps:
|
| 100 |
+
|
| 101 |
+
1. Go to the Cloudflare Tunnel created previously and click "Edit."
|
| 102 |
+
2. Navigate to the "Public Hostname" section and configure it as follows:
|
| 103 |
+
- **Subdomain**: The subdomain of the app. in this example, `hello` is used.
|
| 104 |
+
- **Domain**: Choose any available domain; in this example, `st24.dev` is used.
|
| 105 |
+
- **Service Type**: HTTP
|
| 106 |
+
- **URL**: Enter the internal Nginx ingress IP address and application port, e.g., `192.168.31.250:80`.
|
| 107 |
+
- **HTTP Host Header**: This should match the internal ingress domain associated with the application, e.g., `hello.drunkcoding.net`.
|
| 108 |
+
|
| 109 |
+

|
| 110 |
+
|
| 111 |
+
3. Save the configuration. After saving, The application should be able to access publicly via `hello.st24.dev`.
|
| 112 |
+
|
| 113 |
+

|
| 114 |
+
|
| 115 |
+
## Securing the Application with Authentication
|
| 116 |
+
|
| 117 |
+
Once the application is exposed to the internet, it becomes accessible to everyone, posing security concerns.
|
| 118 |
+
To enhance security, we need to restrict access to authorized personnel only, such as company staff or specific group members.
|
| 119 |
+
Cloudflare provides a robust solution for securing applications accessible via tunnels.
|
| 120 |
+
|
| 121 |
+
### Configuring Cloudflare SSO with EntraID
|
| 122 |
+
|
| 123 |
+
First, logging into the [Cloudflare Zero Trust](https://one.dash.cloudflare.com) dashboard, Navigate to **Settings** > **Authentication**, and select "Add New" under the **Login methods** section.
|
| 124 |
+
|
| 125 |
+
1. **Login providers:** Cloudflare offers multiple login providers; choose **Azure AD** for this configuration.
|
| 126 |
+

|
| 127 |
+
|
| 128 |
+
2. **EntraID SSO:** Follow the provided instructions to integrate Azure AD (EntraID) authentication.
|
| 129 |
+

|
| 130 |
+
|
| 131 |
+
3. **Verification:** Test the configuration to verify that authentication can successfully retrieve the `name` and `id` of EntraID groups.
|
| 132 |
+

|
| 133 |
+
|
| 134 |
+
### Creating a New EntraID Group
|
| 135 |
+
|
| 136 |
+
Next, log into the Azure Portal and create a new EntraID group named `DRUNK CF APPS` with the ID `f8863b0f-3376-4d14-85ba-b376a7d5aeca`. This group will be used to control access to the exposed application.
|
| 137 |
+

|
| 138 |
+
|
| 139 |
+
### The `hello` App Access Policy
|
| 140 |
+
|
| 141 |
+
Finally, return to the [Cloudflare Zero Trust](https://one.dash.cloudflare.com) dashboard and go to **Access** > **Applications**. Click "Add an Application" and select the `Self-hosted` type.
|
| 142 |
+
|
| 143 |
+
1. **App Configuration**: Ensure the domain matches the application you wish to protect. In this example, we'll protect the `hello.st24.dev` application previously exposed.
|
| 144 |
+

|
| 145 |
+
|
| 146 |
+
2. **App Identity**: Choose the login provider configured earlier.
|
| 147 |
+

|
| 148 |
+
|
| 149 |
+
3. **App Policy**: Configure a policy that requires authentication via required provider and restricts access to users in the specified EntraID group ids.
|
| 150 |
+

|
| 151 |
+
> The list of permitted Azure Groups should include the EntraID Group IDs that are allowed access to this app. Without this configuration, the app would be accessible to anyone with an EntraID account in the organization.
|
| 152 |
+
|
| 153 |
+
4. **Testing the App Policy**: After creating the application, click "Test Your Policy" to ensure it functions as intended using a specific account.
|
| 154 |
+

|
| 155 |
+
|
| 156 |
+
## Accessing the Protected App
|
| 157 |
+
|
| 158 |
+
1. Visit `hello.st24.dev`, and We should encounter a login dialog requesting Azure AD authentication before accessing the application.
|
| 159 |
+

|
| 160 |
+
|
| 161 |
+
2. After logged in, users will gain normal access to the application.
|
| 162 |
+

|
| 163 |
+
|
| 164 |
+
## Conclusion
|
| 165 |
+
|
| 166 |
+
In this guide, we've explored how to securely expose an application running on a private AKS cluster to the internet without relying on public IP addresses or open ports. By leveraging **Cloudflare Tunnel**, we established a secure outbound-only connection that adheres to stringent security policies. This method eliminates the risks associated with inbound internet access while providing a seamless way to make internal services accessible externally.
|
| 167 |
+
|
| 168 |
+
We also implemented **Cloudflare Access** integrated with **Azure Entra ID Single Sign-On (SSO)** to add an authentication layer to all exposed applications. This integration ensures that only authorized users within your organization can access the applications, enhancing security by centralizing access control through Entra ID Groups. By doing so, we simplified user management and strengthened compliance with organizational policies.
|
| 169 |
+
|
| 170 |
+
This approach not only maintains the security integrity of your infrastructure but also offers a scalable solution for exposing multiple applications securely. It demonstrates how modern cloud services can be combined to meet complex security requirements without compromising accessibility or user experience.
|
| 171 |
+
|
| 172 |
+
## Reference
|
| 173 |
+
|
| 174 |
+
- [Cloudflared Helm Chart](https://github.com/baoduy/drunk-azure-pulumi-articles/tree/main/pipeline/cf-tunnel-helm)
|
| 175 |
+
- [Tunnel with firewall](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/deploy-tunnels/tunnel-with-firewall)
|
| 176 |
+
- [Configure Cloudflare with Microsoft Entra ID](https://learn.microsoft.com/en-us/entra/identity/enterprise-apps/cloudflare-integration)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
## Next
|
| 180 |
+
|
| 181 |
+
**[Day 12: Exposing a Private AKS Application via Cloudflare Tunnel.](/posts/az-12-private-aks-enable-mdm-devices-cf-tunnel-warp)**
|
| 182 |
+
|
| 183 |
+
In the next and final tutorial, We'll discover how to safely expose the private AKS cluster and applications to the internet with Cloudflare.
|
| 184 |
+
It'll delve into the benefits of using Cloudflare Tunnel and WARP, exploring alternative ways to provide secure access while maintaining the integrity of the corporate network.
|
| 185 |
+
|
| 186 |
+
## Thank You
|
| 187 |
+
|
| 188 |
+
Thank you for taking the time to read this guide! We hope it has been helpful. Feel free to explore further, and happy coding! 🌟✨
|
| 189 |
+
|
| 190 |
+
**Steven** | _[GitHub](https://github.com/baoduy)_
|
az-12-private-aks-enable-mdm-devices-cf-tunnel-warp.md
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-10-12T12:00:00Z
|
| 4 |
+
title: "[Az] Day 12: Enabling MDM Devices by leverage Cloudflare Tunnel and WARP."
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- AKS
|
| 9 |
+
- private cluster
|
| 10 |
+
- Cloudflare
|
| 11 |
+
- Tunnel
|
| 12 |
+
- warp
|
| 13 |
+
description: "
|
| 14 |
+
In this final tutorial, We'll discover how to safely expose the private AKS cluster and applications to the internet with Cloudflare. It'll delve into the benefits of using Cloudflare Tunnel and WARP, exploring alternative ways to provide secure access while maintaining the integrity of the corporate network.
|
| 15 |
+
"
|
| 16 |
+
---
|
| 17 |
+
## Introduction
|
| 18 |
+
|
| 19 |
+
In the final tutorial of our series on establishing a private AKS environment on Azure with Pulumi, we confront a critical balancing act: ensuring secure access for developers and users without compromising the environment's integrity.
|
| 20 |
+
|
| 21 |
+
While stringent security is paramount for compliance, excessive restrictions can hinder developer productivity by obstructing access to essential tools. This challenge is compounded by the rise of remote work, which necessitates robust solutions for managing devices and enforcing security policies beyond traditional network boundaries.
|
| 22 |
+
|
| 23 |
+
This is where Cloudflare WARP and its Zero Trust model come into play. WARP empowers us to grant secure, private access to corporate applications while meticulously verifying device health before connection. By routing traffic through Cloudflare's global network, the WARP client allows for granular web filtering and robust security measures enforced by Cloudflare Gateway.
|
| 24 |
+
|
| 25 |
+
This approach offers a compelling solution for organizations with remote workforces, enhancing security while minimizing friction for users. By integrating Cloudflare Tunnel and WARP into our private AKS environment, we can strike a balance: enabling seamless developer access while upholding the integrity and security of our corporate network.
|
| 26 |
+
|
| 27 |
+
## Table of Contents
|
| 28 |
+
|
| 29 |
+
## Prerequisites
|
| 30 |
+
|
| 31 |
+
Before diving into Cloudflare Tunnel and WARP, make sure you have the following set-up:
|
| 32 |
+
|
| 33 |
+
- **Cloudflare Zero Trust:** You need an active Cloudflare account with the [Zero Trust feature](https://developers.cloudflare.com/cloudflare-one/setup/) enabled to set up a Cloudflare Tunnel.
|
| 34 |
+
- **Microsoft Intune:** Ensure Microsoft Intune is configured for Mobile Device Management (MDM) to manage your devices effectively.
|
| 35 |
+
- **Test Device:** We'll demonstrate using a macOS virtual machine enrolled in the organization's MDM. You can test with your enrolled device by following similar steps.
|
| 36 |
+

|
| 37 |
+
|
| 38 |
+
## WARP Configuration
|
| 39 |
+
|
| 40 |
+
To begin, log into the [Cloudflare Zero Trust](https://one.dash.cloudflare.com) dashboard and navigate to **Settings** > **WARP Client** and configure the following settings:
|
| 41 |
+
|
| 42 |
+
1. **Device Enrollment Permissions:**
|
| 43 |
+
- **Device Enrollment Rules**: Click the "Manage" button under the Device enrollment permissions section to add the necessary _Device enrollment rules_ as depicted below.
|
| 44 |
+

|
| 45 |
+
|
| 46 |
+
- **Authentication**: Ensure that the authentication tab exclusively enables the _Azure AD_ provider, with both _WARP authentication identity_ and _Apply to all Access applications_ activated.
|
| 47 |
+

|
| 48 |
+
|
| 49 |
+
2. **Global Settings**: Activate the Admin override feature, setting the timeout appropriately—6 hours is a recommended.
|
| 50 |
+

|
| 51 |
+
|
| 52 |
+
3. **Device Posture:** This section is crucial for defining device validation rules.
|
| 53 |
+
- **WARP Client Check**: Activate both the _Gateway_ and _WARP_ checking rules.
|
| 54 |
+
- **Third-Party Service Providers**: Click the "Add new" button and select _Microsoft Endpoint Manager_. Follow the provided instructions to implement the Microsoft Intune MDM validation check.
|
| 55 |
+
- **Service Provider Check**: Create a new rule named `Device-Compliant`, assigning it a value of `Compliant`. Avoid selecting an operation unless the rule is intended for a specific OS.
|
| 56 |
+

|
| 57 |
+
|
| 58 |
+
4. **Virtual Network Configuration**: Navigate to the "Virtual Network" section to establish two distinct virtual networks:
|
| 59 |
+
- **default:** This network is automatically generated by Cloudflare and serves as the primary network for _organizational_ access, allowing connection to internal applications across the entire organization.
|
| 60 |
+
- **it-internal-net:** This is a dedicated network tailored for the _IT department_, providing access to specific internal services such as SSH connections to DevOps agent virtual machines.
|
| 61 |
+

|
| 62 |
+
|
| 63 |
+
## WARP Profile Configuration
|
| 64 |
+
|
| 65 |
+
Upon navigating to Device Settings, you'll find a default profile. This profile can be enhanced with the following customizations:
|
| 66 |
+
|
| 67 |
+
1. **Configuration Options:**
|
| 68 |
+
Adjust the settings as outlined below:
|
| 69 |
+
- **Captive Portal Detection:** Enable with a 3-minute timeout. This feature allows the WARP client to temporarily deactivate when encountering a captive portal, facilitating connection to networks like those in hotels, airplanes, or other public environments.
|
| 70 |
+
- **Lock WARP Switch:** Ensure that users cannot disable the WARP switch, preventing them from disconnecting the client.
|
| 71 |
+
- **Allow Updates:** Permit local administrators to receive update notifications for the client and initiate the updates.
|
| 72 |
+
- **Automatic Reconnection:** Set to enable with a 3-minute timeout. This ensures the WARP client automatically reconnects after the specified duration.
|
| 73 |
+
- **Service Mode:** Default to **Gateway with WARP**. This should not be altered.
|
| 74 |
+

|
| 75 |
+
|
| 76 |
+
2. **Split Tunneling:**
|
| 77 |
+
It should be in **Exclude IPs and Domains** mode, configure traffic routing preferences within Cloudflare Zero Trust.
|
| 78 |
+
|
| 79 |
+
By default, all private IP address spaces are excluded. To allow remote devices to access AKS and DevOps subnets, adjust the exclusion rules. Click the "Manage" button to ensure these subnets are included for access.
|
| 80 |
+

|
| 81 |
+
|
| 82 |
+
3. **Microsoft 365 Traffic Routing:**
|
| 83 |
+
If your organization uses Microsoft 365, it's advisable to enable direct routing for its traffic to ensure optimal performance.
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
## WARP Team Domain Management
|
| 87 |
+
|
| 88 |
+
Upon registering for Cloudflare Zero Trust, you will need to specify a **Team Domain**. If you do not recall your current team domain or wish to modify it, head over to **Settings** > **Custom Pages**. Here, you can view and update your team domain, as well as customize the appearance of login and error pages to better fit your organization’s branding needs.
|
| 89 |
+

|
| 90 |
+
|
| 91 |
+
## Deploying the WARP Client with Intune
|
| 92 |
+
|
| 93 |
+
1. **Deploy via Intune:** To streamline the deployment of the WARP Client across all devices, follow the [guide here](https://developers.cloudflare.com/cloudflare-one/connections/connect-devices/warp/deployment/mdm-deployment/partners/intune/).
|
| 94 |
+
This resource details how to onboard the WARP client app with Intune for efficient distribution to widely selected devices.
|
| 95 |
+
|
| 96 |
+
2. **Activating WARP:**
|
| 97 |
+
- After installing the WARP client, the Cloudflare icon will appear in the Taskbar/MenuBar, and a browser window will automatically open, prompting users to log in with Azure AD credentials.
|
| 98 |
+

|
| 99 |
+
- Upon successful login, the WARP client will register the device with Cloudflare Zero Trust and display a "Protected" status, indicating that the device is secured.
|
| 100 |
+

|
| 101 |
+
- The device will also appear on the Zero Trust portal under **My Team** > **Devices**, with its posture status visible as shown below:
|
| 102 |
+

|
| 103 |
+
|
| 104 |
+
> Important: Cloudflare Zero Trust is complimentary for up to the first 50 users. Fees apply for additional users. For more information, visit the [pricing page](https://www.cloudflare.com/en-gb/plans/zero-trust-services/).
|
| 105 |
+
|
| 106 |
+
## Network Policy
|
| 107 |
+
|
| 108 |
+
To ensure secure access to the AKS Subnet `192.168.31.0/24` and DevOps Subnet `192.168.32.128/27`. Here’s how to set up the necessary network policies to permit only compliant devices:
|
| 109 |
+
1. **Blocking Non-compliant Devices:**
|
| 110 |
+
|
| 111 |
+
Configure a network firewall policy to restrict access for non-compliant devices. Follow these instructions to establish this rule:
|
| 112 |
+
Go to **Gateway** > **Firewall Policies** and create a new entry named `Block Non-Compliant Devices` with the parameters below:
|
| 113 |
+
- **Name**: Block Non-Compliant Devices
|
| 114 |
+
- **Traffic**:
|
| 115 |
+
- **Selector**: `Destination IP`
|
| 116 |
+
- **Operator**: `in`
|
| 117 |
+
- **Value**: `192.168.31.0/24`, `192.168.32.128/27`
|
| 118 |
+
- **Device Posture**:
|
| 119 |
+
- **Selector**: `Passed Device Posture`
|
| 120 |
+
- **Operator**: `is not`
|
| 121 |
+
- **Value**: `device-compliant (Intune)`
|
| 122 |
+
- **Action**: `Block`
|
| 123 |
+
- **Enable Block Notification for WARP Client**: Activate this to alert users when their device fails compliance checks.
|
| 124 |
+
|
| 125 |
+
2. **Securing IT Department Access**:
|
| 126 |
+
|
| 127 |
+
We previously established an `it-internal-net` specifically for the IT department. To prevent unauthorized access to this network by non-IT personnel, configure an additional firewall policy:
|
| 128 |
+
- Create an Entra Group named `DRUNK IT DEVELOPERS` with the ID `8a176875-cc7c-4524-86b9-e47573380fe0`.
|
| 129 |
+
- Set up a new policy with the following specifications:
|
| 130 |
+
- **Name**: Block IT Network
|
| 131 |
+
- **Traffic**:
|
| 132 |
+
- **Selector**: `Destination IP`
|
| 133 |
+
- **Operator**: `in`
|
| 134 |
+
- **Value**: `192.168.31.0/24`, `192.168.32.128/27`
|
| 135 |
+
- **AND**
|
| 136 |
+
- **Selector**: `Virtual Network`
|
| 137 |
+
- **Operator**: `is`
|
| 138 |
+
- **Value**: `it-internal-net`
|
| 139 |
+
- **Identity**:
|
| 140 |
+
- **Selector**: `User Group Names`
|
| 141 |
+
- **Operator**: `not in`
|
| 142 |
+
- **Value**: `DRUNK IT DEVELOPERS`
|
| 143 |
+
- **Action**: `Block`
|
| 144 |
+
- **Enable Block Notification for WARP Client**: Activate this to notify users who attempt unauthorized access.
|
| 145 |
+
|
| 146 |
+
3. **Policy Order:** Ensure the policies are applied in the correct sequence as shown in the interface image.
|
| 147 |
+

|
| 148 |
+
|
| 149 |
+
## Enhancing Application Access Security Policy
|
| 150 |
+
|
| 151 |
+
With all previous configurations in place, the tunnel is ready for use. The next crucial step is to enhance the security of the Access application, created earlier, to ensure robust protection.
|
| 152 |
+
|
| 153 |
+
While the existing `hello` application is secured with Azure AD authentication, it remains accessible from any device as long as users can log into Azure AD. This situation presents a security risk, as compromised user accounts could be exploited.
|
| 154 |
+
|
| 155 |
+
- To increase security, we can restrict application access exclusively to corporate-compliant devices. This is achieved by updating the policy, as shown below:
|
| 156 |
+

|
| 157 |
+
|
| 158 |
+
- Users attempting to access the application from non-compliant devices will receive a blocking message, as illustrated here:
|
| 159 |
+

|
| 160 |
+
|
| 161 |
+
## Accessing Private Resources
|
| 162 |
+
|
| 163 |
+
Accessing private network resources through WARP is a critical feature that I find extremely valuable. By configuring Cloudflare Tunnel, we can enable WARP devices to securely access private network ranges.
|
| 164 |
+
|
| 165 |
+
1. **Configure Private Network Tunnel:**
|
| 166 |
+
To start, navigate to the Cloudflare Tunnel settings. Click "Edit" next to your tunnel, select the "Private Network" tab, and add the specific private IP ranges wish to be exposed. Refer to the screenshot below for guidance:
|
| 167 |
+

|
| 168 |
+
|
| 169 |
+
2. **Switch WARP Network:**
|
| 170 |
+
On the WARP-enabled device, switch the network to `it-internal-net` to gain access to the designated internal resources.
|
| 171 |
+

|
| 172 |
+
|
| 173 |
+
3. **SSH into DevOps Agent:**
|
| 174 |
+
With the WARP device configured, We can now establish an SSH connection to the DevOps virtual machine, as though direct local network.
|
| 175 |
+

|
| 176 |
+
|
| 177 |
+
> If you encounter any issues, ensure that your Azure firewall settings, CloudPC Security Group, and Cloudflare Tunnel network policies are properly configured to permit access to the DevOps subnet from the AKS subnet.
|
| 178 |
+
|
| 179 |
+
## Conclusion
|
| 180 |
+
|
| 181 |
+
In this final tutorial of our series on establishing a private AKS environment on Azure with Pulumi, we've successfully integrated Cloudflare Tunnel and WARP into our secure network infrastructure. By leveraging Cloudflare Tunnel and WARP, we've been able to strike a balance between enabling seamless developer access and upholding the integrity and security of our corporate network.
|
| 182 |
+
|
| 183 |
+
The implementation of Cloudflare Tunnel and WARP has provided us with numerous benefits, including:
|
| 184 |
+
|
| 185 |
+
* Granular web filtering and robust security measures enforced by Cloudflare Gateway
|
| 186 |
+
* Zero Trust model for secure, private access to corporate applications
|
| 187 |
+
* Enhanced security while minimizing friction for users
|
| 188 |
+
* Simplified deployment and management of the WARP client application
|
| 189 |
+
|
| 190 |
+
## Reference
|
| 191 |
+
|
| 192 |
+
- [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/setup/)
|
| 193 |
+
- [The Cloudflare WARP client](https://developers.cloudflare.com/cloudflare-one/connections/connect-devices/warp/)
|
| 194 |
+
- [Download WARP](https://developers.cloudflare.com/cloudflare-one/connections/connect-devices/warp/download-warp/)
|
| 195 |
+
|
| 196 |
+
## Thank You
|
| 197 |
+
|
| 198 |
+
Thank you for taking the time to read this guide! We hope it has been helpful. Feel free to explore further, and happy coding! 🌟✨
|
| 199 |
+
|
| 200 |
+
**Steven** | _[GitHub](https://github.com/baoduy)_
|
dotnet-01-mvc-anti-forgery-token-and-machine-key.md
ADDED
|
@@ -0,0 +1,144 @@
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 6 |
+
featured: false
|
| 7 |
+
draft: false
|
| 8 |
+
tags:
|
| 9 |
+
- dotnet
|
| 10 |
+
- MVC
|
| 11 |
+
- web-farm
|
| 12 |
+
- iis
|
| 13 |
+
ogImage: ""
|
| 14 |
+
description:
|
| 15 |
+
The Medium post explains the importance of anti-forgery tokens and machine keys in web application security against CSRF attacks.
|
| 16 |
+
It provides implementation details for ASP.NET, including the use of AntiForgeryToken and configuring the machine key.
|
| 17 |
+
The post emphasizes the necessity of implementing both measures to enhance overall security.
|
| 18 |
+
---
|
| 19 |
+
|
| 20 |
+
If you're developing using ASP.NET MVC, it's highly likely that you've come across the concept of anti-forgery tokens.
|
| 21 |
+
These tokens play a critical role in bolstering the security of our web applications and safeguarding them against Cross-Site Request Forgery (CSRF) attacks.
|
| 22 |
+
|
| 23 |
+
In this attack vector, unauthorized commands are transmitted from a user that the website trusts.
|
| 24 |
+
CSRF attacks exploit the trust that a site has for a user, and
|
| 25 |
+
the anti-forgery token mitigates this by ensuring that the unauthorized commands do not execute.
|
| 26 |
+
|
| 27 |
+
To leverage this security feature in your ASP.NET MVC application, two key steps are involved:
|
| 28 |
+
|
| 29 |
+
1. Implement the `AntiForgeryToken` method directly within the form you wish to protect.
|
| 30 |
+
This method generates the token that will be validated upon form submission.
|
| 31 |
+
|
| 32 |
+
```csharp
|
| 33 |
+
@using (Html.BeginForm())
|
| 34 |
+
{
|
| 35 |
+
@Html.AntiForgeryToken()
|
| 36 |
+
....
|
| 37 |
+
}
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
2. Adorn the corresponding action method in your controller with the ValidateAntiForgeryToken attribute.
|
| 41 |
+
This ensures that the ASP.NET MVC framework validates the token included in the request against the token stored in the form body.
|
| 42 |
+
|
| 43 |
+
```csharp
|
| 44 |
+
[HttpPost]
|
| 45 |
+
[ValidateAntiForgeryToken]
|
| 46 |
+
public ActionResult Create(FormCollection collection)
|
| 47 |
+
{
|
| 48 |
+
...
|
| 49 |
+
}
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
## How does it work?
|
| 53 |
+
|
| 54 |
+
When utilizing the `AntiForgeryToken` method within a form, ASP.NET generates an encrypted `AntiForgeryToken`.
|
| 55 |
+
This token is placed into a hidden field and then transmitted to the client browser.
|
| 56 |
+
Upon submitting the form back to the server, this token is decrypted and validated to confirm the authenticity of the request.
|
| 57 |
+
Only upon successful validation will the targeted action method be executed.
|
| 58 |
+
However, this validation occurs only if the action method is adorned with the `ValidateAntiForgeryTokenAttribute`.
|
| 59 |
+
|
| 60 |
+
The generated token structure resembles:
|
| 61 |
+
|
| 62 |
+
```html
|
| 63 |
+
<form action="Create" method="post">
|
| 64 |
+
<input
|
| 65 |
+
name="__RequestVerificationToken"
|
| 66 |
+
type="hidden"
|
| 67 |
+
value="Kw1D9Co5OuHbp2TajfwB2xdR-lABEkjtwwMs0tLr9K8Y-dycbbRQU904HljeF4rBu0DnMpZpCtf1TrAoGmgnMxpeapzJtdR-P0BC3wuAc1-ZaHGSnYeEKoTa9fbMUOFx0"
|
| 68 |
+
/>
|
| 69 |
+
</form>
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
## What is the issue?
|
| 73 |
+
|
| 74 |
+
While deploying your website in an environment comprising multiple load-balanced servers (aka a web farm),
|
| 75 |
+
you may encounter the following issue when clicking the `submit` button:
|
| 76 |
+
|
| 77 |
+
> The anti-forgery token could not be decrypted.
|
| 78 |
+
> If this application is hosted by a Web Farm or cluster,
|
| 79 |
+
> ensure that all machines are running the same version of ASP.NET Web Pages
|
| 80 |
+
> and that the configuration specifies explicit encryption and validation keys.
|
| 81 |
+
> AutoGenerate cannot be used in a cluster.
|
| 82 |
+
|
| 83 |
+
## Why did this issue happen?
|
| 84 |
+
|
| 85 |
+
Consider a setup where the environment consists of two servers performing load balancing as illustrated in the given diagram:
|
| 86 |
+

|
| 87 |
+
|
| 88 |
+
In this setup, the ASP.NET application utilizes two unique keys (decryptionKey and validationKey) for token encryption/decryption and token validation.
|
| 89 |
+
By default, these keys are randomly generated each time the website starts.
|
| 90 |
+
|
| 91 |
+
In our diagram, we have two instances of the same website hosted on different servers forming a single web farm.
|
| 92 |
+
When the website starts on both servers, two different sets of keys are independently generated for each instance.
|
| 93 |
+
|
| 94 |
+
Let's say a user, denoted here as user A, sends a request that is redirected to server 1 by the load balancer.
|
| 95 |
+
The website responds by providing a view along with an encrypted AntiForgeryToken.
|
| 96 |
+
Later user A submits the form back to the load balancer, expecting the form to be processed by server 1.
|
| 97 |
+
|
| 98 |
+
However, if the load balancer redirects the request to server 2, there’s a problem.
|
| 99 |
+
The token encrypted by Server 1 cannot be decrypted on Server 2 as the decryptionKey on Server 2 differs from the one on Server 1.
|
| 100 |
+
This mismatch of keys results in an error.
|
| 101 |
+
|
| 102 |
+
To prevent such issues, ensure consistency in keys for every instance of the website inside a single web farm
|
| 103 |
+
needs to use the same set of keys for token encryption/decryption and validation.
|
| 104 |
+
|
| 105 |
+
However, when dealing with multiple websites hosted on the same server,
|
| 106 |
+
these keys need to be unique for each website. Similarly, when the same website is hosted in multiple environments,
|
| 107 |
+
the keys employed in each environment should be different.
|
| 108 |
+
This is to maintain the secure and independent identity of each website and environment.
|
| 109 |
+
|
| 110 |
+
## The solution for IIS
|
| 111 |
+
|
| 112 |
+
The goal is to establish a mechanism to share a set of keys across multiple servers within a single farm.
|
| 113 |
+
This will ensure successful encryption and decryption regardless of the server performing the task.
|
| 114 |
+
|
| 115 |
+
For an AspNet MVC website hosted on IIS, a set of keys can be generated following these steps:
|
| 116 |
+
|
| 117 |
+
1. Select the website on IIS.
|
| 118 |
+
2. Double-click on "Machine Key."
|
| 119 |
+
3. De-select all checkboxes, click on the "Generate" button on the right side, and then hit "Apply."
|
| 120 |
+
|
| 121 |
+

|
| 122 |
+
|
| 123 |
+
Once generated, the keys are saved in the "web.config" file of the website.
|
| 124 |
+
You can distribute these keys to all website instances on all the servers in the farm as follows:
|
| 125 |
+
|
| 126 |
+
1. Open the "web.config" file and locate the keys,
|
| 127 |
+
2. Copy these keys and distribute them across all website instances within the farm.
|
| 128 |
+
|
| 129 |
+
```xml
|
| 130 |
+
<system.web>
|
| 131 |
+
<machineKey decryptionKey="13C9825F6B5ABB0622CF09B6C7F949F83D113B3CC2351438"
|
| 132 |
+
validationKey="DA39AFED706512A688EDD4FA5898FABF2D8A0D6897465093B1237C1D46E34F8E7B0E9A09FFE647CAC32DEFE9AFAEDDE6EFE8FF6CDE0BF27C883277BB3566BFA6" />
|
| 133 |
+
</system.web>
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
After accomplishing this, try submitting your website again. These measures should resolve the initial issue.
|
| 137 |
+
|
| 138 |
+
---
|
| 139 |
+
|
| 140 |
+
## Thank You
|
| 141 |
+
|
| 142 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 143 |
+
|
| 144 |
+
**Steven** | *[GitHub](https://github.com/baoduy)*
|
dotnet-02-tool-for-azure-ad-to-adss-Users-writeback.md
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2021-10-13T00:00:00Z
|
| 4 |
+
title: "[.NET] Small tool for Azure AD to AD User Write back"
|
| 5 |
+
postSlug: azure-ad-to-adss-users-write-back
|
| 6 |
+
featured: false
|
| 7 |
+
draft: false
|
| 8 |
+
tags:
|
| 9 |
+
- dotnet
|
| 10 |
+
- tools
|
| 11 |
+
- azureAD
|
| 12 |
+
- sync
|
| 13 |
+
ogImage: ""
|
| 14 |
+
description: Sharing a small tool-self developed to sync the users from AzureAD to on=premise Active Directory Service.
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
Azure AD Sync is an instrumental resource for forging a hybrid cloud model and facilitating password write-back.
|
| 18 |
+
However, if your organization requires user write-back functionality, Azure AD Sync alone will not suffice.
|
| 19 |
+
|
| 20 |
+
## Solution
|
| 21 |
+
|
| 22 |
+
To address this need, I have developed a tool that implements user write-back functionality. With this self-contained tool, you can specify which users in which Azure groups should be written back and determine the Organizational Unit (OU) and AD group where users should be assigned.
|
| 23 |
+
|
| 24 |
+
## Configuration
|
| 25 |
+
|
| 26 |
+
1. Create an Application Registration (e.g., named 'azure-adds-user-write-back') with Microsoft Graph API permission set to `Group.Read.All` and `User.Read.All`.
|
| 27 |
+
2. Update the information in `appsettings.json` as follows:
|
| 28 |
+
|
| 29 |
+
```json
|
| 30 |
+
{
|
| 31 |
+
"AzAdSync": {
|
| 32 |
+
"Authority": "https://login.microsoftonline.com/[TenantId]",
|
| 33 |
+
"ClientId": "[ClientId]",
|
| 34 |
+
"ClientSecret": "[ClientSecret]",
|
| 35 |
+
"AzureAdGroups": ["The Azure AD groups would like to write back"],
|
| 36 |
+
"AdOrgUnit": "The OU of ADDS for write-back users."
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
## Tool Tech-stack
|
| 42 |
+
|
| 43 |
+
This application is developed using the .NET Core framework.
|
| 44 |
+
You can build the project as a Window-x64 single file, self-contained.
|
| 45 |
+
After that, you will be able to copy and run it on any domain-joined computer without needing the .NET runtime.
|
| 46 |
+
|
| 47 |
+
To install the app as a window service, run `sc.exe create "AADS Users WriteBack" binpath=[Path To]\Azure.ADDS.UserWriteBack.exe`.
|
| 48 |
+
Ensure that the Logon account is updated with a Windows account with permission to create ADDS objects,
|
| 49 |
+
and switch the start type to `Automatic`.
|
| 50 |
+
|
| 51 |
+
> Please note that the log files will be writing to the `C:\Windows\System32\Logs folder.`
|
| 52 |
+
|
| 53 |
+
The application will check and sync users from AzureAdGroups every 1 hour.
|
| 54 |
+
Upon successful write-back of the user account to ADDS,
|
| 55 |
+
the account owner must reset their password since the application generates a random password of 50 length characters.
|
| 56 |
+
|
| 57 |
+
> This password is just a temporary password as it will be overwritten with the latest password once users changed their password in Azure AD by the password write-back of AD-AAD Sync.
|
| 58 |
+
|
| 59 |
+
## Source Code
|
| 60 |
+
|
| 61 |
+
The source code is accessible at this Github repository: https://github.com/baoduy/Azure.ADDS.UserWriteBack.
|
| 62 |
+
Please adjust the steps and instructions to match your actual tool's requirements and behavior.
|
| 63 |
+
|
| 64 |
+
---
|
| 65 |
+
|
| 66 |
+
## Thank You
|
| 67 |
+
|
| 68 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 69 |
+
|
| 70 |
+
**Steven** | *[GitHub](https://github.com/baoduy)*
|
dotnet-03-multi-platform-dockerfile.md
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2023-09-10T00:00:00Z
|
| 4 |
+
title: "[.NET] Optimising .NET Core with Multi-Platform Docker Images: A Complete Guide"
|
| 5 |
+
postSlug: dotnet-dockerfile-multi-platform
|
| 6 |
+
featured: false
|
| 7 |
+
draft: false
|
| 8 |
+
tags:
|
| 9 |
+
- dotnet
|
| 10 |
+
- dockerfile
|
| 11 |
+
- multi-platform
|
| 12 |
+
- arm
|
| 13 |
+
ogImage: ""
|
| 14 |
+
description:
|
| 15 |
+
In this post, sharing about Docker optimisation for the .NET Core framework
|
| 16 |
+
and build a multi-platform image using the capabilities of Docker buildx,
|
| 17 |
+
enabling us to create multi-platform images that can seamlessly run on diverse architectures.
|
| 18 |
+
Moreover, we will discuss the integration of GitAction into the image-building process, empowering us to automate creating and publishing multi-platform Docker images.
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
## Built-in template
|
| 22 |
+
|
| 23 |
+
Let's start with a simple API for a .NET application with Docker support.
|
| 24 |
+
Once begun, a Dockerfile will automatically be generated for the project.
|
| 25 |
+
|
| 26 |
+
Here's how a basic Dockerfile might look.
|
| 27 |
+
|
| 28 |
+
```ps
|
| 29 |
+
FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base
|
| 30 |
+
WORKDIR /app
|
| 31 |
+
EXPOSE 80
|
| 32 |
+
EXPOSE 443
|
| 33 |
+
|
| 34 |
+
FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
|
| 35 |
+
WORKDIR /src
|
| 36 |
+
COPY ["SampleApi/SampleApi.csproj", "SampleApi/"]
|
| 37 |
+
RUN dotnet restore "SampleApi/SampleApi.csproj"
|
| 38 |
+
COPY . .
|
| 39 |
+
WORKDIR "/src/SampleApi"
|
| 40 |
+
RUN dotnet build "SampleApi.csproj" -c Release -o /app/build
|
| 41 |
+
|
| 42 |
+
FROM build AS publish
|
| 43 |
+
RUN dotnet publish "SampleApi.csproj" -c Release -o /app/publish /p:UseAppHost=false
|
| 44 |
+
|
| 45 |
+
FROM base AS final
|
| 46 |
+
WORKDIR /app
|
| 47 |
+
COPY --from=publish /app/publish .
|
| 48 |
+
ENTRYPOINT ["dotnet", "SampleApi.dll"]
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
Utilizing the provided Dockerfile, we can seamlessly build and execute the application in a Docker environment successfully.
|
| 52 |
+

|
| 53 |
+
|
| 54 |
+
### What is the issue?
|
| 55 |
+
|
| 56 |
+
The resulting image generated from the Dockerfile previously illustrated exceeds **215 MB** in size.
|
| 57 |
+
Although this might not prove troublesome, when executing on systems abundant in storage capacity,
|
| 58 |
+
it can lead to rapid depletion of SD card storage space on platforms with lower specifications or IOT devices,
|
| 59 |
+
such as a Raspberry K3s cluster.
|
| 60 |
+
|
| 61 |
+
Our next step involves optimizing this Dockerfile to minimize its footprint.
|
| 62 |
+
|
| 63 |
+
## Dockerfile optimisation
|
| 64 |
+
|
| 65 |
+
Let's proceed by transitioning the .NET image to the alpine image by adding `-alpine` at the end of the image version.
|
| 66 |
+
|
| 67 |
+
Remarkably, the updated image size has contracted substantially to approximately **110 MB**,
|
| 68 |
+
signifying a reduction of almost half from its original dimensions.
|
| 69 |
+
|
| 70 |
+
```ps
|
| 71 |
+
# 1. Changes this image from 'aspnet:7.0' to 'aspnet:7.0-alpine'
|
| 72 |
+
FROM mcr.microsoft.com/dotnet/aspnet:7.0-alpine AS base
|
| 73 |
+
WORKDIR /app
|
| 74 |
+
EXPOSE 80
|
| 75 |
+
EXPOSE 443
|
| 76 |
+
|
| 77 |
+
# 2. Changes this image from 'sdk:7.0' to 'sdk:7.0-alpine'
|
| 78 |
+
FROM mcr.microsoft.com/dotnet/sdk:7.0-alpine AS build
|
| 79 |
+
WORKDIR /src
|
| 80 |
+
COPY ["SampleApi/SampleApi.csproj", "SampleApi/"]
|
| 81 |
+
RUN dotnet restore "SampleApi/SampleApi.csproj"
|
| 82 |
+
COPY . .
|
| 83 |
+
WORKDIR "/src/SampleApi"
|
| 84 |
+
RUN dotnet build "SampleApi.csproj" -c Release -o /app/build
|
| 85 |
+
|
| 86 |
+
FROM build AS publish
|
| 87 |
+
RUN dotnet publish "SampleApi.csproj" -c Release -o /app/publish /p:UseAppHost=false
|
| 88 |
+
|
| 89 |
+
FROM base AS final
|
| 90 |
+
WORKDIR /app
|
| 91 |
+
COPY --from=publish /app/publish .
|
| 92 |
+
ENTRYPOINT ["dotnet", "SampleApi.dll"]
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+

|
| 96 |
+
|
| 97 |
+
### With Self contained .NET app (**experimental**)
|
| 98 |
+
|
| 99 |
+
Additionally, a feature is presented that enhances the "dotnet push" operation,
|
| 100 |
+
enabling it to create self-contained, singular executable files and reduced library applications.
|
| 101 |
+
|
| 102 |
+
This facilitates the construction of applications that are not reliant on the .NET runtime,
|
| 103 |
+
as well as the removal of all unused methods present within the library,
|
| 104 |
+
consequently yielding a more compact application.
|
| 105 |
+
|
| 106 |
+
Let's evaluate the Dockerfile delineated below, _The comments have been added on top of all changed lines_.
|
| 107 |
+
|
| 108 |
+
Please note that,
|
| 109 |
+
the `PublishTrimmed` and `PublishSingleFile` are experimental feature and may not compatible with all applications.
|
| 110 |
+
So verify the applications carefully before moving to the Production environment.
|
| 111 |
+
|
| 112 |
+
```ps
|
| 113 |
+
# 1. Changes this image from 'aspnet:7.0-alpine' to 'runtime-deps:7.0-alpine'
|
| 114 |
+
FROM mcr.microsoft.com/dotnet/runtime-deps:7.0-alpine AS base
|
| 115 |
+
WORKDIR /app
|
| 116 |
+
EXPOSE 80
|
| 117 |
+
EXPOSE 443
|
| 118 |
+
|
| 119 |
+
FROM mcr.microsoft.com/dotnet/sdk:7.0-alpine AS build
|
| 120 |
+
WORKDIR /src
|
| 121 |
+
COPY ["SampleApi/SampleApi.csproj", "SampleApi/"]
|
| 122 |
+
RUN dotnet restore "SampleApi/SampleApi.csproj"
|
| 123 |
+
COPY . .
|
| 124 |
+
WORKDIR "/src/SampleApi"
|
| 125 |
+
RUN dotnet build "SampleApi.csproj" -c Release -o /app/build
|
| 126 |
+
|
| 127 |
+
FROM build AS publish
|
| 128 |
+
|
| 129 |
+
# 2. updated 'dotnet publish' options
|
| 130 |
+
RUN dotnet publish "SampleApi.csproj" -c Release -o /app/publish \
|
| 131 |
+
--runtime alpine-x64 \
|
| 132 |
+
--self-contained true \
|
| 133 |
+
/p:PublishTrimmed=true \
|
| 134 |
+
/p:PublishSingleFile=true
|
| 135 |
+
|
| 136 |
+
FROM base AS final
|
| 137 |
+
WORKDIR /app
|
| 138 |
+
COPY --from=publish /app/publish .
|
| 139 |
+
|
| 140 |
+
# 3. updated the endpoint, the application path no need to mentiond the '.dll' anymore.
|
| 141 |
+
ENTRYPOINT ["./SampleApi"]
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
Good news! Our application is impressively lean and only uses about **47MB**.
|
| 145 |
+
That's pretty light, right? So, we can count on it to run smoothly even in low-specs environments.
|
| 146 |
+
|
| 147 |
+
Nonetheless, it is prudently advisable to subject your application to a comprehensive compatibility test with the Alpine image,
|
| 148 |
+
ensuring seamless real-world performance without compromising on any usage scenarios.
|
| 149 |
+
|
| 150 |
+
### Docker Image without root user.
|
| 151 |
+
|
| 152 |
+
In a production environment, it is recommended to restrict the utilization of root user privileges for the majority of applications.
|
| 153 |
+
In the event that your application doesn't necessitate elevated permissions, you are advised to instantiate a non-root user during the Docker build process.
|
| 154 |
+
|
| 155 |
+
I'd like to share a quick best practice tip with you to boost the security level of your images. Keep in mind, this might not necessarily decrease the image size, but it's an essential step nonetheless.
|
| 156 |
+
|
| 157 |
+
Implementing this practice could potentially prevent any flags by our InfoSec's security scanning system during the vetting process for Production deployment. It's always better to be safe and secure as we progress!
|
| 158 |
+
|
| 159 |
+
```ps
|
| 160 |
+
FROM mcr.microsoft.com/dotnet/runtime-deps:7.0-alpine AS base
|
| 161 |
+
WORKDIR /app
|
| 162 |
+
EXPOSE 80
|
| 163 |
+
EXPOSE 443
|
| 164 |
+
|
| 165 |
+
FROM mcr.microsoft.com/dotnet/sdk:7.0-alpine AS build
|
| 166 |
+
WORKDIR /src
|
| 167 |
+
COPY ["SampleApi/SampleApi.csproj", "SampleApi/"]
|
| 168 |
+
RUN dotnet restore "SampleApi/SampleApi.csproj"
|
| 169 |
+
COPY . .
|
| 170 |
+
WORKDIR "/src/SampleApi"
|
| 171 |
+
RUN dotnet build "SampleApi.csproj" -c Release -o /app/build
|
| 172 |
+
|
| 173 |
+
FROM build AS publish
|
| 174 |
+
RUN dotnet publish "SampleApi.csproj" -c Release -o /app/publish \
|
| 175 |
+
--runtime alpine-x64 \
|
| 176 |
+
--self-contained true \
|
| 177 |
+
/p:PublishTrimmed=true \
|
| 178 |
+
/p:PublishSingleFile=true
|
| 179 |
+
|
| 180 |
+
FROM base AS final
|
| 181 |
+
|
| 182 |
+
# 1. Create a new user and change directory ownership
|
| 183 |
+
RUN adduser --disabled-password \
|
| 184 |
+
--home /app \
|
| 185 |
+
--gecos '' dotnetuser && chown -R dotnetuser /app
|
| 186 |
+
|
| 187 |
+
# 2. Impersonate into the new user
|
| 188 |
+
USER dotnetuser
|
| 189 |
+
WORKDIR /app
|
| 190 |
+
|
| 191 |
+
COPY --from=publish /app/publish .
|
| 192 |
+
ENTRYPOINT ["./SampleApi"]
|
| 193 |
+
```
|
| 194 |
+
|
| 195 |
+
## Multi-platform docker image.
|
| 196 |
+
|
| 197 |
+
Even after performing the aforementioned steps, the Docker image remains built for the x64 platform.
|
| 198 |
+
To add support for the Docker on an ARM processor, it is essential to revise your Docker image and leverage the "docker buildx" feature for cross-compatibility.
|
| 199 |
+
Consider the changes of the following Dockerfile for reference.
|
| 200 |
+
|
| 201 |
+
```ps
|
| 202 |
+
FROM mcr.microsoft.com/dotnet/runtime-deps:7.0-alpine AS base
|
| 203 |
+
WORKDIR /app
|
| 204 |
+
EXPOSE 80
|
| 205 |
+
EXPOSE 443
|
| 206 |
+
|
| 207 |
+
# 1. Add 2 (BUILDPLATFORM and TARGETARCH) arguments and add 'platform' parameter to the FROM statement.
|
| 208 |
+
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:7.0-alpine AS build
|
| 209 |
+
ARG TARGETARCH
|
| 210 |
+
ARG BUILDPLATFORM
|
| 211 |
+
|
| 212 |
+
WORKDIR /src
|
| 213 |
+
COPY ["SampleApi/SampleApi.csproj", "SampleApi/"]
|
| 214 |
+
RUN dotnet restore "SampleApi/SampleApi.csproj"
|
| 215 |
+
COPY . .
|
| 216 |
+
WORKDIR "/src/SampleApi"
|
| 217 |
+
|
| 218 |
+
# 2. add '-a $TARGETARCH' to the 'dotnet build' command.
|
| 219 |
+
RUN dotnet build "SampleApi.csproj" -c Release -o /app/build -a $TARGETARCH
|
| 220 |
+
|
| 221 |
+
FROM build AS publish
|
| 222 |
+
|
| 223 |
+
# 2. add '-a $TARGETARCH' to the 'dotnet publish' command.
|
| 224 |
+
RUN dotnet publish "SampleApi.csproj" -c Release -o /app/publish \
|
| 225 |
+
#--runtime alpine-x64 \
|
| 226 |
+
--self-contained true \
|
| 227 |
+
/p:PublishTrimmed=true \
|
| 228 |
+
/p:PublishSingleFile=true \
|
| 229 |
+
-a $TARGETARCH
|
| 230 |
+
|
| 231 |
+
# 3. Add 2 (BUILDPLATFORM and TARGETARCH) arguments and add 'platform' parameter to the FROM statement.
|
| 232 |
+
FROM --platform=$BUILDPLATFORM base AS final
|
| 233 |
+
ARG TARGETARCH
|
| 234 |
+
ARG BUILDPLATFORM
|
| 235 |
+
|
| 236 |
+
RUN adduser --disabled-password \
|
| 237 |
+
--home /app \
|
| 238 |
+
--gecos '' dotnetuser && chown -R dotnetuser /app
|
| 239 |
+
|
| 240 |
+
USER dotnetuser
|
| 241 |
+
WORKDIR /app
|
| 242 |
+
|
| 243 |
+
COPY --from=publish /app/publish .
|
| 244 |
+
ENTRYPOINT ["./SampleApi"]
|
| 245 |
+
```
|
| 246 |
+
|
| 247 |
+
This is the command to construct a multi-platform compatible image.
|
| 248 |
+
|
| 249 |
+
```bash
|
| 250 |
+
# Build Docker for x64 processor
|
| 251 |
+
docker build --platform="linux/amd64" -f Dockerfile -t sampleapi-x64:latest .
|
| 252 |
+
|
| 253 |
+
# Build image for arm64 processor
|
| 254 |
+
docker build --platform="linux/arm64" -f Dockerfile -t sampleapi-arm64:latest .
|
| 255 |
+
|
| 256 |
+
# All together, build image for multi-platform with docker buildx
|
| 257 |
+
docker buildx build --platform="linux/amd64,linux/arm64" -f Dockerfile -t sampleapi:latest .
|
| 258 |
+
```
|
| 259 |
+
|
| 260 |
+
Here are some sample results of Docker images on my Intel workstation.
|
| 261 |
+

|
| 262 |
+
|
| 263 |
+
Test to ensure both images work correctly without any issues on my workstation.
|
| 264 |
+

|
| 265 |
+
|
| 266 |
+
## Altogether with GitAction.
|
| 267 |
+
|
| 268 |
+
We have successfully established a Dockerfile that facilitates multi-platform support for .NET 7.
|
| 269 |
+
In coordination with GitHub Actions, this allows us to construct and propel the respective image to a container registry
|
| 270 |
+
Docker Hub being our prime focus in this situation.
|
| 271 |
+
|
| 272 |
+
Prior to engaging with the GitHub Action setup, I want to highlight a valuable feature known as **[Reusing workflows](https://docs.github.com/en/actions/using-workflows/reusing-workflows)**.
|
| 273 |
+
This sophisticated feature grants us the capability to outline a build workflow, which can be employed repetitively across multiple projects down the line.
|
| 274 |
+
|
| 275 |
+
To provide an illustrative example, please consider the undermentioned workflow located at **[.github/workflows/docker-publish.yaml](https://github.com/baoduy/ShareWorkflows/blob/main/.github/workflows/docker-publish.yaml)** within the **[ShareWorkflows](https://github.com/baoduy/ShareWorkflows)** repository.
|
| 276 |
+
This workflow effectively develops a Dockerfile for multi-platform usage and subsequently propels the images to Docker Hub.
|
| 277 |
+
|
| 278 |
+
```yaml
|
| 279 |
+
name: Docker-Publish
|
| 280 |
+
|
| 281 |
+
on:
|
| 282 |
+
workflow_call:
|
| 283 |
+
inputs:
|
| 284 |
+
# The location of the Dockerfile parameter.
|
| 285 |
+
dockerFile:
|
| 286 |
+
required: true
|
| 287 |
+
type: string
|
| 288 |
+
description: The location of the Dockerfile.
|
| 289 |
+
|
| 290 |
+
# The context path of the project parameter.
|
| 291 |
+
context:
|
| 292 |
+
default: .
|
| 293 |
+
type: string
|
| 294 |
+
description: The context path of the project.
|
| 295 |
+
|
| 296 |
+
# The docker platforms parameter with default value is "linux/arm64 and linux/amd64"
|
| 297 |
+
platforms:
|
| 298 |
+
default: linux/arm64,linux/amd64
|
| 299 |
+
type: string
|
| 300 |
+
description: The docker platforms parameter with default value is "linux/arm64 and linux/amd64".
|
| 301 |
+
|
| 302 |
+
# The name of the docker image parameter.
|
| 303 |
+
imageName:
|
| 304 |
+
required: true
|
| 305 |
+
type: string
|
| 306 |
+
description: The name of the docker image.
|
| 307 |
+
|
| 308 |
+
# The version parameter of the image with default value is current date-time.
|
| 309 |
+
version:
|
| 310 |
+
default: $(date +%s)
|
| 311 |
+
type: string
|
| 312 |
+
description: The version of the image with default value is current date-time.
|
| 313 |
+
secrets:
|
| 314 |
+
# The DOCKER_USERNAME secret parameter.
|
| 315 |
+
DOCKER_USERNAME:
|
| 316 |
+
required: true
|
| 317 |
+
description: The docker hub user name.
|
| 318 |
+
# The DOCKER_TOKEN secret parameter.
|
| 319 |
+
DOCKER_TOKEN:
|
| 320 |
+
required: true
|
| 321 |
+
description: The docker hub PAT token.
|
| 322 |
+
|
| 323 |
+
jobs:
|
| 324 |
+
build:
|
| 325 |
+
runs-on: ubuntu-latest
|
| 326 |
+
|
| 327 |
+
steps:
|
| 328 |
+
- uses: actions/checkout@v3
|
| 329 |
+
|
| 330 |
+
# Setup Buildx
|
| 331 |
+
- name: Docker Setup Buildx
|
| 332 |
+
uses: docker/setup-buildx-action@v2.9.1
|
| 333 |
+
with:
|
| 334 |
+
platforms: ${{ inputs.platforms }}
|
| 335 |
+
|
| 336 |
+
# Login to docker hub
|
| 337 |
+
- name: Docker Login
|
| 338 |
+
uses: docker/login-action@v2.0.0
|
| 339 |
+
with:
|
| 340 |
+
username: ${{ secrets.DOCKER_USERNAME }}
|
| 341 |
+
password: ${{ secrets.DOCKER_TOKEN }}
|
| 342 |
+
ecr: auto
|
| 343 |
+
logout: true
|
| 344 |
+
|
| 345 |
+
# Pull the previous image from docker hub to use it as cache to improve the image build time.
|
| 346 |
+
- name: docker pull cache image
|
| 347 |
+
continue-on-error: true
|
| 348 |
+
run: docker pull ${{ inputs.imageName }}:latest
|
| 349 |
+
|
| 350 |
+
# Setup QEMU
|
| 351 |
+
- name: Set up QEMU
|
| 352 |
+
uses: docker/setup-qemu-action@v2
|
| 353 |
+
|
| 354 |
+
# Build and Publish to Docker
|
| 355 |
+
- name: Build the Docker image
|
| 356 |
+
run: |
|
| 357 |
+
docker buildx build ${{ inputs.context }} --file ${{ inputs.dockerFile }} \
|
| 358 |
+
--tag ${{ inputs.imageName }}:${{ inputs.version }} \
|
| 359 |
+
--tag ${{ inputs.imageName }}:latest \
|
| 360 |
+
--cache-from=${{ inputs.imageName }}:latest \
|
| 361 |
+
--push --platform=${{ inputs.platforms }}
|
| 362 |
+
```
|
| 363 |
+
|
| 364 |
+
### How to reuse the Git workflows
|
| 365 |
+
|
| 366 |
+
I've pushed my SampleAPI to my GitHub. You can find it in the **[HBD.Samples](https://github.com/baoduy/HBD.Samples)** repository.
|
| 367 |
+
Following with the SampleAPI of GitAction that calls the shared workflow, making sure to give it the right parameters.
|
| 368 |
+
|
| 369 |
+
_Remember, before you get this action running, it's important to first update the workflow location according to your Git repository
|
| 370 |
+
and add your **DOCKER_USERNAME** and **DOCKER_TOKEN** into your repository's secrets._
|
| 371 |
+
|
| 372 |
+
```yaml
|
| 373 |
+
name: Docker-Buildx
|
| 374 |
+
|
| 375 |
+
on:
|
| 376 |
+
push:
|
| 377 |
+
branches:
|
| 378 |
+
- "main"
|
| 379 |
+
|
| 380 |
+
jobs:
|
| 381 |
+
dotnet_release_job:
|
| 382 |
+
# TODO: Update this path according to your git repository.
|
| 383 |
+
uses: baoduy/ShareWorkflows/.github/workflows/docker-publish.yaml@main
|
| 384 |
+
with:
|
| 385 |
+
# The location of the Dockerfile parameter.
|
| 386 |
+
dockerFile: "01_Multi_platform_docker_image_for_NET/SampleApi/Dockerfile"
|
| 387 |
+
# The context path of the project parameter.
|
| 388 |
+
context: '"./01_Multi_platform_docker_image_for_NET"'
|
| 389 |
+
# The name of the docker image parameter.
|
| 390 |
+
imageName: "baoduy2412/sample-01-api"
|
| 391 |
+
# The docker platforms parameter.
|
| 392 |
+
platforms: linux/arm64,linux/amd64
|
| 393 |
+
secrets:
|
| 394 |
+
# The DOCKER_USERNAME secret parameter.
|
| 395 |
+
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
| 396 |
+
# The DOCKER_TOKEN secret parameter.
|
| 397 |
+
DOCKER_TOKEN: ${{ secrets.DOCKER_TOKEN }}
|
| 398 |
+
```
|
| 399 |
+
|
| 400 |
+
Woohoo! Once the Git action has been executed successfully, we can hop over to Docker Hub to see the image neatly tagged across multiple platforms.
|
| 401 |
+
|
| 402 |
+

|
| 403 |
+
|
| 404 |
+
_To ensure that everything's working as it should,
|
| 405 |
+
both images were put to the test on my iMac (which has an Intel chip) and a K3s Raspberry Pi 4 cluster._
|
| 406 |
+
|
| 407 |
+
---
|
| 408 |
+
|
| 409 |
+
## Thank You
|
| 410 |
+
|
| 411 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 412 |
+
|
| 413 |
+
**Steven** | *[GitHub](https://github.com/baoduy)*
|
dotnet-04-aspire-local-env-tests.md
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-08-22T12:00:00Z
|
| 4 |
+
title: "[.NET] Aspire, Simplifying Local Development Environment and Testing."
|
| 5 |
+
postSlug: dotnet-04-aspire-local-env-and-testing
|
| 6 |
+
featured: true
|
| 7 |
+
draft: false
|
| 8 |
+
tags:
|
| 9 |
+
- dotnet
|
| 10 |
+
- aspire
|
| 11 |
+
- local-env
|
| 12 |
+
description: "Setting up a new project can be challenging, especially with the involvement of various technologies. This guide explores how .NET Aspire simplifies development by streamlining local environment setup, testing, and continuous integration, while also detailing the end-to-end process with an Azure DevOps CI/CD pipeline."
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
Starting a new project is both exciting and challenging, especially when it comes to configuring the development environment. Many projects require a mix of technologies, which can lead to time-consuming setup and potential errors. **.NET Aspire** simplifies this process by offering a framework that helps developers set up a consistent and efficient environment across various projects.
|
| 16 |
+
|
| 17 |
+
With .NET Aspire, We can create a ready-to-run local environment that integrates seamlessly with Docker, allowing the development team to focus on coding without worrying about complex setup requirements. It supports smooth integration with containers, making it easier to handle dependencies and ensuring that our local environment closely mirrors the development/staging environment setup.
|
| 18 |
+
|
| 19 |
+
In addition to simplifying environment setup, this guide walks us through writing robust integration tests. These tests ensure all components work well together and catch potential issues early in the development process. We'll also learn how to incorporate these tests into a continuous integration (CI) pipeline, ensuring the code is consistently validated and error-free before it reaches production.
|
| 20 |
+
|
| 21 |
+
## Why .NET Aspire?
|
| 22 |
+
|
| 23 |
+
**.NET Aspire** is designed to improve the experience of building .NET cloud-native applications. It provides a consistent, opinionated set of tools and patterns that help to build and run distributed apps. .NET Aspire assists with:
|
| 24 |
+
|
| 25 |
+
- **Orchestration**: Features for running and connecting multi-project applications and their dependencies in local development environments.
|
| 26 |
+
- **Integrations**: NuGet packages for commonly used services, such as Redis or PostgreSQL, with standardized interfaces ensuring they connect consistently and seamlessly with the app.
|
| 27 |
+
- **Tooling**: Project templates and tooling experiences for Visual Studio, Visual Studio Code, and the `dotnet` CLI to help to create and interact with .NET Aspire projects.
|
| 28 |
+
|
| 29 |
+
---
|
| 30 |
+
|
| 31 |
+
## Table of Contents
|
| 32 |
+
|
| 33 |
+
1. [Why .NET Aspire?](#why-net-aspire)
|
| 34 |
+
2. [Setting Up the Local Environment](#setting-up-the-local-environment)
|
| 35 |
+
3. [Hosting with Aspire](#hosting-with-aspire)
|
| 36 |
+
4. [.NET Aspire for Testing](#net-aspire-for-testing)
|
| 37 |
+
5. [Running Tests on Azure DevOps](#running-tests-on-azure-devops)
|
| 38 |
+
6. [Conclusion](#conclusion)
|
| 39 |
+
|
| 40 |
+
---
|
| 41 |
+
|
| 42 |
+
## Setting Up the Local Environment
|
| 43 |
+
|
| 44 |
+
Let's start by creating a simple API project and hosting it with .NET Aspire.
|
| 45 |
+
|
| 46 |
+
### Prerequisites
|
| 47 |
+
|
| 48 |
+
- **.NET 8 SDK** or later
|
| 49 |
+
- **Docker Desktop** installed and running
|
| 50 |
+
- **Aspire workload** installed: Install the Aspire workload using the following command:
|
| 51 |
+
|
| 52 |
+
```bash
|
| 53 |
+
dotnet workload install aspire
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
### Creating an API Project
|
| 57 |
+
|
| 58 |
+
Assuming we already have a simple API that utilizes the following technologies:
|
| 59 |
+
|
| 60 |
+
- **MediatR**: A library used to implement the command and response pattern at the API level. It helps decouple request handling logic from controllers, making the code more modular and easier to maintain.
|
| 61 |
+
- **Entity Framework Core (EF Core)**: An Object-Relational Mapper (ORM) used to manage database access.
|
| 62 |
+
- **PostgreSQL**: Used as the database to store and manage the application's data.
|
| 63 |
+
|
| 64 |
+
This API has the following endpoints, as displayed in the Swagger UI:
|
| 65 |
+
|
| 66 |
+

|
| 67 |
+
|
| 68 |
+
### Aspire Templates Explanation
|
| 69 |
+
|
| 70 |
+
Aspire provides several project templates to help to get started quickly with different aspects of application development and testing:
|
| 71 |
+
|
| 72 |
+
- **App Host**: The primary template for creating an Aspire hosting project. It sets up the necessary infrastructure to host the application and its dependencies.
|
| 73 |
+
- **Service Defaults**: Configures essential services for the application, such as `OpenTelemetry` for distributed tracing, `DefaultHealthChecks` for monitoring service health, and `RequestTimeouts` to manage request durations. While optional, it's highly recommended for applications hosted on Aspire to ensure robust monitoring and orchestration management.
|
| 74 |
+
- **Test Project (MSTest)**: Sets up a project for unit testing using the MSTest framework.
|
| 75 |
+
- **Test Project (NUnit)**: Sets up a project for unit testing using the NUnit framework.
|
| 76 |
+
- **Test Project (xUnit)**: Sets up a project for unit testing using the xUnit framework.
|
| 77 |
+
|
| 78 |
+

|
| 79 |
+
|
| 80 |
+
---
|
| 81 |
+
|
| 82 |
+
## Hosting with Aspire
|
| 83 |
+
|
| 84 |
+
To host the API above with its dependencies with Aspire, follow these steps:
|
| 85 |
+
|
| 86 |
+
### Create `Aspire.Host`
|
| 87 |
+
|
| 88 |
+
First, create a new project named `Aspire.Host` using the App Host template provided by .NET Aspire.
|
| 89 |
+
|
| 90 |
+
### Add PostgreSQL Support
|
| 91 |
+
|
| 92 |
+
Next, install the Aspire PostgreSQL hosting package to add PostgreSQL support to this project.
|
| 93 |
+
|
| 94 |
+
```bash
|
| 95 |
+
dotnet add package Aspire.Hosting.PostgreSQL
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
> **Note**: Refer to the [.NET Aspire GitHub repository](https://github.com/dotnet/aspire) for a full list of hosting components supported by Aspire.
|
| 99 |
+
|
| 100 |
+
### Aspire Host with `Config as Code`
|
| 101 |
+
|
| 102 |
+
Open `Program.cs` in the `Aspire.Host` project and configure the `DistributedApplication` as shown:
|
| 103 |
+
|
| 104 |
+
```csharp
|
| 105 |
+
var builder = DistributedApplication.CreateBuilder(args);
|
| 106 |
+
|
| 107 |
+
// Database
|
| 108 |
+
var postgres = builder.AddPostgres("postgres").PublishAsConnectionString();
|
| 109 |
+
var db = postgres.AddDatabase("Db");
|
| 110 |
+
|
| 111 |
+
// Internal API
|
| 112 |
+
builder.AddProject<Projects.Api>("api")
|
| 113 |
+
.WithReference(db);
|
| 114 |
+
|
| 115 |
+
builder.Build().Run();
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
**Explanation**:
|
| 119 |
+
|
| 120 |
+
- **AddPostgres("postgres")**: Adds a PostgreSQL service.
|
| 121 |
+
- **PublishAsConnectionString()**: Makes the connection string available to other services.
|
| 122 |
+
- **AddDatabase("Db")**: Sets up a database named "Db".
|
| 123 |
+
- **AddProject**: Includes the API project in the Aspire host configuration.
|
| 124 |
+
- **WithReference(db)**: Links the API project to the database.
|
| 125 |
+
|
| 126 |
+
### EF Core Database Migration
|
| 127 |
+
|
| 128 |
+
Automating database migrations is important when using EF Core to ensure consistency across environments. While we won't discuss the details here, you can refer to the [EF Core Migrations guide](https://learn.microsoft.com/en-us/dotnet/aspire/database/ef-core-migrations) compatible with .NET Aspire.
|
| 129 |
+
|
| 130 |
+
### Aspire Host Dashboard
|
| 131 |
+
|
| 132 |
+
Run the `Aspire.Host` project. The dashboard will display all running components.
|
| 133 |
+
|
| 134 |
+

|
| 135 |
+
|
| 136 |
+
---
|
| 137 |
+
|
| 138 |
+
## .NET Aspire for Testing
|
| 139 |
+
|
| 140 |
+
Integration tests ensure that different parts of the application work together correctly. However, writing and running them on CI/CD pipelines can be challenging and time-consuming. .NET Aspire simplifies this process by handling much of the setup for us.
|
| 141 |
+
|
| 142 |
+
### Create `Aspire.Tests`
|
| 143 |
+
|
| 144 |
+
Create a new test project named `Aspire.Tests` using the Test Project (xUnit) template provided by .NET Aspire. This template sets up the necessary scaffolding for integration tests using xUnit.
|
| 145 |
+
|
| 146 |
+
### Add Reference to `Aspire.Host`
|
| 147 |
+
|
| 148 |
+
Instead of installing the same NuGet package dependencies in `Aspire.Tests`, add a project reference to `Aspire.Host`. This allows the test project to leverage the configurations and services defined in the host project.
|
| 149 |
+
|
| 150 |
+
Here is a reference graph:
|
| 151 |
+
|
| 152 |
+

|
| 153 |
+
|
| 154 |
+
### ApiFixture Class
|
| 155 |
+
|
| 156 |
+
The `ApiFixture` class sets up the necessary environment for integration tests. It extends `WebApplicationFactory<Api.Program>` and implements `IAsyncLifetime` to manage the lifecycle of the test environment.
|
| 157 |
+
|
| 158 |
+
```csharp
|
| 159 |
+
public sealed class ApiFixture : WebApplicationFactory<Api.Program>, IAsyncLifetime
|
| 160 |
+
{
|
| 161 |
+
private readonly IHost _app;
|
| 162 |
+
private readonly IResceBuilder<PostgresServerResce> _postgres;
|
| 163 |
+
private string? _postgresConnectionString;
|
| 164 |
+
|
| 165 |
+
/**
|
| 166 |
+
* Constructor for ApiFixture.
|
| 167 |
+
* Initializes the DistributedApplicationOptions and sets up the PostgreSQL server resce.
|
| 168 |
+
*/
|
| 169 |
+
public ApiFixture()
|
| 170 |
+
{
|
| 171 |
+
var options = new DistributedApplicationOptions
|
| 172 |
+
{
|
| 173 |
+
AssemblyName = typeof(ApiFixture).Assembly.FullName,
|
| 174 |
+
DisableDashboard = true
|
| 175 |
+
};
|
| 176 |
+
var builder = DistributedApplication.CreateBuilder(options);
|
| 177 |
+
|
| 178 |
+
_postgres = builder.AddPostgres("postgres").PublishAsConnectionString();
|
| 179 |
+
_app = builder.Build();
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
/**
|
| 183 |
+
* Creates and configures the host for the application.
|
| 184 |
+
* Adds the PostgreSQL connection string to the host configuration.
|
| 185 |
+
* Ensures the database is created before returning the host.
|
| 186 |
+
*
|
| 187 |
+
* @param builder The IHostBuilder instance.
|
| 188 |
+
* @return The configured IHost instance.
|
| 189 |
+
*/
|
| 190 |
+
protected override IHost CreateHost(IHostBuilder builder)
|
| 191 |
+
{
|
| 192 |
+
builder.ConfigureHostConfiguration(config =>
|
| 193 |
+
{
|
| 194 |
+
config.AddInMemoryCollection(new Dictionary<string, string?>
|
| 195 |
+
{
|
| 196 |
+
{ "ConnectionStrings:Db", _postgresConnectionString },
|
| 197 |
+
}!);
|
| 198 |
+
});
|
| 199 |
+
|
| 200 |
+
//TODO: add logic for db migration and seeding data here.
|
| 201 |
+
var host = base.CreateHost(builder);
|
| 202 |
+
host.EnsureDbCreated().GetAwaiter().GetResult();
|
| 203 |
+
return host;
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
/**
|
| 207 |
+
* Disposes the resces used by the fixture asynchronously.
|
| 208 |
+
* Stops the application host and disposes of it.
|
| 209 |
+
*/
|
| 210 |
+
public new async Task DisposeAsync()
|
| 211 |
+
{
|
| 212 |
+
await base.DisposeAsync();
|
| 213 |
+
await _app.StopAsync();
|
| 214 |
+
if (_app is IAsyncDisposable asyncDisposable)
|
| 215 |
+
{
|
| 216 |
+
await asyncDisposable.DisposeAsync().ConfigureAwait(false);
|
| 217 |
+
}
|
| 218 |
+
else
|
| 219 |
+
{
|
| 220 |
+
_app.Dispose();
|
| 221 |
+
}
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
/**
|
| 225 |
+
* Initializes the fixture asynchronously.
|
| 226 |
+
* Starts the application host and waits for the PostgreSQL resce to be in the running state.
|
| 227 |
+
* Retrieves the PostgreSQL connection string.
|
| 228 |
+
*/
|
| 229 |
+
public async Task InitializeAsync()
|
| 230 |
+
{
|
| 231 |
+
var resceNotificationService = _app.Services.GetRequiredService<ResceNotificationService>();
|
| 232 |
+
await _app.StartAsync();
|
| 233 |
+
|
| 234 |
+
await resceNotificationService.WaitForResceAsync(_postgres.Resce.Name, KnownResceStates.Running);
|
| 235 |
+
_postgresConnectionString = await _postgres.Resce.GetConnectionStringAsync();
|
| 236 |
+
}
|
| 237 |
+
}
|
| 238 |
+
```
|
| 239 |
+
|
| 240 |
+
**Explanation**:
|
| 241 |
+
|
| 242 |
+
The `ApiFixture` class is responsible for:
|
| 243 |
+
|
| 244 |
+
- Setting up a PostgreSQL server resource.
|
| 245 |
+
- Configuring the host with the necessary connection strings.
|
| 246 |
+
- Ensuring the database is created and testing data prepared before tests run.
|
| 247 |
+
- Starting and stopping the application host.
|
| 248 |
+
- Cleaning up resources after tests are completed.
|
| 249 |
+
|
| 250 |
+
### Test Cases Class
|
| 251 |
+
|
| 252 |
+
The `ProductEndpointsTests` class contains integration tests for the product endpoints of the API. It uses the `ApiFixture` to set up the test environment and `HttpClient` to make requests to the API.
|
| 253 |
+
|
| 254 |
+
```csharp
|
| 255 |
+
public class ProductEndpointsTests(ApiFixture fixture, ITestOutputHelper output) : IClassFixture<ApiFixture>
|
| 256 |
+
{
|
| 257 |
+
private readonly HttpClient _client = fixture.CreateClient();
|
| 258 |
+
|
| 259 |
+
/**
|
| 260 |
+
* Tests the creation of a product.
|
| 261 |
+
* Ensures that the product is created successfully and returns a valid product ID.
|
| 262 |
+
*/
|
| 263 |
+
[Fact]
|
| 264 |
+
public async Task CreateProduct_ReturnsCreatedProduct()
|
| 265 |
+
{
|
| 266 |
+
// Arrange
|
| 267 |
+
var command = new CreateProduct.Command { Name = "Test Product", Price = 10.99m };
|
| 268 |
+
// Act
|
| 269 |
+
var response = await _client.PostAsJsonAsync("/products", command);
|
| 270 |
+
|
| 271 |
+
// Assert
|
| 272 |
+
response.EnsureSuccessStatusCode();
|
| 273 |
+
var productId = await response.Content.ReadFromJsonAsync<int>();
|
| 274 |
+
Assert.True(productId > 0);
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
/**
|
| 278 |
+
* Tests the retrieval of a product.
|
| 279 |
+
* Ensures that the product is retrieved successfully and matches the expected values.
|
| 280 |
+
*/
|
| 281 |
+
[Fact]
|
| 282 |
+
public async Task GetProduct_ReturnsProduct()
|
| 283 |
+
{
|
| 284 |
+
// Arrange
|
| 285 |
+
var command = new CreateProduct.Command { Name = "Test Product", Price = 10.99m };
|
| 286 |
+
var createResponse = await _client.PostAsJsonAsync("/products", command);
|
| 287 |
+
var productId = await createResponse.Content.ReadFromJsonAsync<int>();
|
| 288 |
+
|
| 289 |
+
// Act
|
| 290 |
+
var response = await _client.GetAsync($"/products/{productId}");
|
| 291 |
+
|
| 292 |
+
// Assert
|
| 293 |
+
response.EnsureSuccessStatusCode();
|
| 294 |
+
var product = await response.Content.ReadFromJsonAsync<Product>();
|
| 295 |
+
Assert.NotNull(product);
|
| 296 |
+
Assert.Equal("Test Product", product.Name);
|
| 297 |
+
Assert.Equal(10.99m, product.Price);
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
/**
|
| 301 |
+
* Tests the update of a product.
|
| 302 |
+
* Ensures that the product is updated successfully and returns a NoContent status.
|
| 303 |
+
*/
|
| 304 |
+
[Fact]
|
| 305 |
+
public async Task UpdateProduct_ReturnsNoContent()
|
| 306 |
+
{
|
| 307 |
+
// Arrange
|
| 308 |
+
var command = new CreateProduct.Command { Name = "Test Product", Price = 10.99m };
|
| 309 |
+
var createResponse = await _client.PostAsJsonAsync("/products", command);
|
| 310 |
+
var productId = await createResponse.Content.ReadFromJsonAsync<int>();
|
| 311 |
+
|
| 312 |
+
var updateCommand = new UpdateProduct.Command { Id = productId, Name = "Updated Product", Price = 20.99m };
|
| 313 |
+
|
| 314 |
+
// Act
|
| 315 |
+
var response = await _client.PutAsJsonAsync($"/products/{productId}", updateCommand);
|
| 316 |
+
|
| 317 |
+
// Assert
|
| 318 |
+
response.EnsureSuccessStatusCode();
|
| 319 |
+
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
/**
|
| 323 |
+
* Tests the deletion of a product.
|
| 324 |
+
* Ensures that the product is deleted successfully and returns a NoContent status.
|
| 325 |
+
*/
|
| 326 |
+
[Fact]
|
| 327 |
+
public async Task DeleteProduct_ReturnsNoContent()
|
| 328 |
+
{
|
| 329 |
+
// Arrange
|
| 330 |
+
var command = new CreateProduct.Command { Name = "Test Product", Price = 10.99m };
|
| 331 |
+
var createResponse = await _client.PostAsJsonAsync("/products", command);
|
| 332 |
+
var productId = await createResponse.Content.ReadFromJsonAsync<int>();
|
| 333 |
+
|
| 334 |
+
// Act
|
| 335 |
+
var response = await _client.DeleteAsync($"/products/{productId}");
|
| 336 |
+
|
| 337 |
+
// Assert
|
| 338 |
+
response.EnsureSuccessStatusCode();
|
| 339 |
+
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
|
| 340 |
+
}
|
| 341 |
+
}
|
| 342 |
+
```
|
| 343 |
+
|
| 344 |
+
**Explanation**:
|
| 345 |
+
|
| 346 |
+
The `ProductEndpointsTests` class is responsible for testing the CRUD of the product endpoints. It ensures that:
|
| 347 |
+
|
| 348 |
+
- **Creating a product** works correctly and returns a valid product ID.
|
| 349 |
+
- **Retrieving a product** returns the expected product details.
|
| 350 |
+
- **Updating a product** successfully applies the changes and returns the appropriate status.
|
| 351 |
+
- **Deleting a product** removes it from the database and returns the correct status code.
|
| 352 |
+
|
| 353 |
+
> **Note:** Postgres connection issues may arise when running multiple sets of test cases in parallel. In such cases, instead of using `IClassFixture<>`, consider using [`IAssemblyFixture`](https://github.com/JDCain/Xunit.Extensions.AssemblyFixture). This approach ensures that only a single instance of `DistributedApplication` is created for the entire test suite.
|
| 354 |
+
|
| 355 |
+
### Testing Results
|
| 356 |
+
|
| 357 |
+
Here are the reports on Azure DevOps after the pipeline ran successfully.
|
| 358 |
+
|
| 359 |
+
- **Test Case Results**:
|
| 360 |
+
|
| 361 |
+
The test case results show the outcome of each executed test.
|
| 362 |
+
|
| 363 |
+

|
| 364 |
+
|
| 365 |
+
- **Coverage Results**:
|
| 366 |
+
|
| 367 |
+
Code coverage results provide insights into how much of the codebase is being tested.
|
| 368 |
+
|
| 369 |
+

|
| 370 |
+
|
| 371 |
+
---
|
| 372 |
+
|
| 373 |
+
## Running Tests on Azure DevOps
|
| 374 |
+
|
| 375 |
+
### Configuring the Pipeline
|
| 376 |
+
|
| 377 |
+
To automate testing and code coverage collection, let's set up a continuous integration (CI) pipeline using Azure DevOps.
|
| 378 |
+
|
| 379 |
+
In the Azure DevOps project, create a new pipeline that builds the code, runs tests, and collects code coverage data.
|
| 380 |
+
|
| 381 |
+
Here is an example of what our `azure-pipelines.yml` file might look like.
|
| 382 |
+
|
| 383 |
+
```yaml
|
| 384 |
+
trigger:
|
| 385 |
+
- main
|
| 386 |
+
|
| 387 |
+
resources:
|
| 388 |
+
- repo: self
|
| 389 |
+
|
| 390 |
+
variables:
|
| 391 |
+
BuildConfiguration: Release
|
| 392 |
+
RestoreBuildProjects: "**/*.csproj"
|
| 393 |
+
TestProjects: "**/*[Tt]ests/*.csproj"
|
| 394 |
+
|
| 395 |
+
# Agent VM image name
|
| 396 |
+
vmImageName: "ubuntu-latest"
|
| 397 |
+
|
| 398 |
+
stages:
|
| 399 |
+
- stage: Build
|
| 400 |
+
displayName: Build and Test Stage
|
| 401 |
+
jobs:
|
| 402 |
+
- job: Build
|
| 403 |
+
displayName: Build
|
| 404 |
+
pool:
|
| 405 |
+
vmImage: $(vmImageName)
|
| 406 |
+
steps:
|
| 407 |
+
# Use the correct .NET SDK version
|
| 408 |
+
- task: UseDotNet@2
|
| 409 |
+
displayName: "Use .NET SDK 8.x"
|
| 410 |
+
inputs:
|
| 411 |
+
packageType: "sdk"
|
| 412 |
+
version: "8.x"
|
| 413 |
+
|
| 414 |
+
# Install the necessary .NET workload
|
| 415 |
+
- task: Bash@3
|
| 416 |
+
displayName: "Install Aspire Workload"
|
| 417 |
+
inputs:
|
| 418 |
+
targetType: "inline"
|
| 419 |
+
script: "dotnet workload install aspire"
|
| 420 |
+
|
| 421 |
+
# Build the project
|
| 422 |
+
- task: DotNetCoreCLI@2
|
| 423 |
+
displayName: "Build Project"
|
| 424 |
+
inputs:
|
| 425 |
+
command: "build"
|
| 426 |
+
projects: $(RestoreBuildProjects)
|
| 427 |
+
arguments: -c $(BuildConfiguration)
|
| 428 |
+
|
| 429 |
+
# Run tests and collect code coverage
|
| 430 |
+
- task: DotNetCoreCLI@2
|
| 431 |
+
displayName: "Run Tests and Collect Coverage"
|
| 432 |
+
inputs:
|
| 433 |
+
command: "test"
|
| 434 |
+
projects: "$(TestProjects)"
|
| 435 |
+
arguments: '--configuration $(BuildConfiguration) --collect "Code Coverage"'
|
| 436 |
+
```
|
| 437 |
+
|
| 438 |
+
**Explanation**:
|
| 439 |
+
|
| 440 |
+
- **UseDotNet@2**: Ensures that the correct .NET SDK is installed on the build agent.
|
| 441 |
+
- **Install Aspire Workload**: Installs the Aspire workload needed for the project.
|
| 442 |
+
- **Build Projects**: Builds all the projects specified by the `RestoreBuildProjects` variable.
|
| 443 |
+
- **Run Tests and Collect Code Coverage**: Executes the tests in the projects specified by the `TestProjects` variable and collects code coverage data.
|
| 444 |
+
|
| 445 |
+
_Note_: Ensure that the YAML file includes the `UseDotNet@2` task to specify the required .NET SDK version.
|
| 446 |
+
|
| 447 |
+
### Running the Pipeline
|
| 448 |
+
|
| 449 |
+
Save the pipeline configuration and run it. Monitor the build process to ensure all steps complete successfully.
|
| 450 |
+
|
| 451 |
+
After the pipeline completes, the test results and code coverage reports should be appeared in Azure DevOps.
|
| 452 |
+
|
| 453 |
+
1. **Test Results**:
|
| 454 |
+
|
| 455 |
+
Displays which tests passed or failed.
|
| 456 |
+
|
| 457 |
+

|
| 458 |
+
|
| 459 |
+
2. **Code Coverage**:
|
| 460 |
+
|
| 461 |
+
Provides detailed information about which parts of the code were tested.
|
| 462 |
+
|
| 463 |
+

|
| 464 |
+
|
| 465 |
+
> **Note**: The initial code coverage might be lower than expected. For example, you might see an overall coverage of 23.89%, even though the API component itself has 88.14% coverage. This discrepancy occurs because the coverage report includes all libraries, those not part of the API project.
|
| 466 |
+
|
| 467 |
+
### Improving Code Coverage Reports
|
| 468 |
+
|
| 469 |
+
To generate a more meaningful code coverage report, We can configure it to include only the relevant components of the project.
|
| 470 |
+
|
| 471 |
+
1. **Creating the Coverage Filtering File**:
|
| 472 |
+
|
| 473 |
+
Create a file named `coverage.runsettings` in the project root with the appropriate configuration.
|
| 474 |
+
|
| 475 |
+
```xml
|
| 476 |
+
<?xml version="1.0" encoding="utf-8"?>
|
| 477 |
+
<RunSettings>
|
| 478 |
+
<DataCollectionRunSettings>
|
| 479 |
+
<DataCollectors>
|
| 480 |
+
<DataCollector friendlyName="XPlat Code Coverage">
|
| 481 |
+
<Configuration>
|
| 482 |
+
<Include>
|
| 483 |
+
[Api*]*
|
| 484 |
+
</Include>
|
| 485 |
+
<Exclude>
|
| 486 |
+
</Exclude>
|
| 487 |
+
</Configuration>
|
| 488 |
+
</DataCollector>
|
| 489 |
+
</DataCollectors>
|
| 490 |
+
</DataCollectionRunSettings>
|
| 491 |
+
</RunSettings>
|
| 492 |
+
```
|
| 493 |
+
|
| 494 |
+
**Explanation**:
|
| 495 |
+
|
| 496 |
+
- The `<Include>` section specifies which assemblies to include in the code coverage report. In this case, `[Api*]*` includes all assemblies starting with "Api".
|
| 497 |
+
- The `<Exclude>` section can be used to exclude specific assemblies or classes.
|
| 498 |
+
|
| 499 |
+
2. **Updating the Pipeline Configuration**:
|
| 500 |
+
|
| 501 |
+
Modify the `azure-pipelines.yml` file to use the `coverage.runsettings` file and publish the code coverage results.
|
| 502 |
+
|
| 503 |
+
```yaml
|
| 504 |
+
# ... previous configuration ...
|
| 505 |
+
|
| 506 |
+
# Run tests with coverage filtering
|
| 507 |
+
- task: DotNetCoreCLI@2
|
| 508 |
+
displayName: "Test with Coverage Filtering"
|
| 509 |
+
inputs:
|
| 510 |
+
command: "test"
|
| 511 |
+
projects: "$(TestProjects)"
|
| 512 |
+
arguments: '--configuration $(BuildConfiguration) --settings coverage.runsettings --collect "XPlat Code Coverage"'
|
| 513 |
+
|
| 514 |
+
# Publish the code coverage results to Azure DevOps
|
| 515 |
+
- task: PublishCodeCoverageResults@2
|
| 516 |
+
inputs:
|
| 517 |
+
summaryFileLocation: "$(Agent.TempDirectory)/**/coverage.cobertura.xml"
|
| 518 |
+
```
|
| 519 |
+
|
| 520 |
+
**Explanation**:
|
| 521 |
+
|
| 522 |
+
- **Run Tests with Coverage Filtering**: Executes tests using the `coverage.runsettings` file to filter the code coverage data.
|
| 523 |
+
- **Publish Code Coverage Results**: Publishes the code coverage results to Azure DevOps for easy visualization.
|
| 524 |
+
|
| 525 |
+
3. **Enhanced Coverage Report**:
|
| 526 |
+
|
| 527 |
+
After running the updated pipeline, We should see an improved code coverage report that focuses on the relevant parts of the project. The coverage results will now provide detailed insights at the class level using the XPlat format.
|
| 528 |
+
|
| 529 |
+

|
| 530 |
+
|
| 531 |
+
---
|
| 532 |
+
|
| 533 |
+
## Conclusion
|
| 534 |
+
|
| 535 |
+
By utilizing .NET Aspire and Docker, we can create a consistent, isolated environment that streamlines not just Entity Framework integration testing but the entire development lifecycle. .NET Aspire offers a flexible to `config as code` and sharing `ready-to-run` environment to all the development teams.
|
| 536 |
+
|
| 537 |
+
---
|
| 538 |
+
|
| 539 |
+
## References
|
| 540 |
+
|
| 541 |
+
- [Sample Code From DrunkCode](https://github.com/baoduy/sample-aspire-dotnet-unittests)
|
| 542 |
+
- [.NET Aspire Documentation](https://learn.microsoft.com/en-us/dotnet/aspire/get-started/aspire-overview)
|
| 543 |
+
- [EfCore Migration in .NET Aspire](https://learn.microsoft.com/en-us/dotnet/aspire/database/ef-core-migrations)
|
| 544 |
+
|
| 545 |
+
---
|
| 546 |
+
|
| 547 |
+
## Thank You
|
| 548 |
+
|
| 549 |
+
Thank for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 550 |
+
|
| 551 |
+
**Steven**
|
| 552 |
+
[GitHub](https://github.com/baoduy)
|
ks-00-series-k8s-setup-local-env-pi-cluster.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-09-25T12:00:00Z
|
| 4 |
+
title: "[K8s] A Complete Series of Articles on Kubernetes Environment Locally"
|
| 5 |
+
featured: true
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- k3s
|
| 9 |
+
- kubernetes
|
| 10 |
+
- picluster
|
| 11 |
+
description: "A concise series guiding you through setting up a local Kubernetes environment using K3s on Raspberry Pi 4 clusters. Learn how to install K3s, configure Nginx Ingress, implement SSL certificates with Cert-Manager and Cloudflare, and host applications like Outline VPN and Longhorn."
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
## Introduction
|
| 15 |
+
|
| 16 |
+
Welcome to our complete series of articles on building a local Kubernetes environment using K3s on Raspberry Pi 4 clusters. This series is designed to provide us with step-by-step guidance through practical examples.
|
| 17 |
+
|
| 18 |
+
We'll start by installing K3s, a lightweight version of Kubernetes that's perfect for devices like the Raspberry Pi. Then, we'll set up Nginx Ingress to manage network traffic and explore two ways to implement SSL certificates: using Cert-Manager and leveraging Cloudflare for a simpler approach.
|
| 19 |
+
|
| 20 |
+
Additionally, we'll learn how to expose our services to the internet without a static IP by using Cloudflare Tunnel. We'll also host applications like Outline VPN for secure connections and Longhorn for reliable, cloud-native storage solutions.
|
| 21 |
+
|
| 22 |
+
By the end of this series, we'll have a fully functional Kubernetes environment capable of running and managing complex applications, all from our local setup. Let's dive in and start this exciting journey together!
|
| 23 |
+
|
| 24 |
+
---
|
| 25 |
+
|
| 26 |
+
## Series of Articles
|
| 27 |
+
|
| 28 |
+
### [Day 01: Step-By-Step Guide: Installing K3s on a Raspberry Pi 4 Cluster](/posts/ks-01-install-k3s-on-pi-cluster/)
|
| 29 |
+
|
| 30 |
+
In this guide, sharing some useful tips to help you seamlessly install K3s on a Raspberry Pi 4 cluster.
|
| 31 |
+
Let's dive in and start the installation process.
|
| 32 |
+
|
| 33 |
+
### [Day 02: Step-By-Step Guide: Installing Nginx Ingress on K3s Pi 4 Cluster](/posts/ks-02-install-nginx-on-pi-cluster/)
|
| 34 |
+
|
| 35 |
+
This guide provides helpful tips for installing the Nginx Ingress on a K3s Raspberry Pi 4 cluster.
|
| 36 |
+
Detailed and step-by-step instructions will ensure a seamless installation process. Let's get started!
|
| 37 |
+
|
| 38 |
+
### [Day 03: Step-By-Step Guide: Installation of Cert-Manager, Implementing Free SSL Certificates for Kubernetes Clusters](/posts/ks-03-install-cert-manager-free-ssl-kubernetes-cluster)
|
| 39 |
+
|
| 40 |
+
This comprehensive guide will help you to smoothly install Cert-Manager and implement free SSL certificates for Kubernetes clusters.
|
| 41 |
+
It is designed with step-by-step instructions to facilitate a seamless installation process. Dive in and let's begin this journey for enhanced security!
|
| 42 |
+
|
| 43 |
+
### [Day 04: Step-By-Step Guide: Cert-Manager Alternative with Cloudflare, Implementing Free SSL Certificates for Kubernetes Clusters](/posts/ks-04-cert-manager-alternative-with-cloudflare)
|
| 44 |
+
|
| 45 |
+
We explore the concept of using a Cert-Manager Alternative with Cloudflare to implement free SSL Certificates for Kubernetes clusters.
|
| 46 |
+
This strategy leverages Cloudflare SSL certificates conjunction with the Kubernetes setup to provide a secure environment, replacing the need of Cert-Manager.
|
| 47 |
+
Discover how this approach simplifies the process, and enhances the security of our Kubernetes clusters.
|
| 48 |
+
|
| 49 |
+
### [Day 05: Step-By-Step Guide: Nginx Alternative with Cloudflare Tunnel, Enables services to internet a public static IP address](/posts/ks-05-public-services-with-cloudflare-tunnel)
|
| 50 |
+
|
| 51 |
+
This robust solution provides a feasible alternative to Nginx when there's no public static IP address or port forwarding required.
|
| 52 |
+
This guide walks us through the process step by step, enabling the services online more efficiently.
|
| 53 |
+
|
| 54 |
+
### [Day 06: Step-By-Step Guide: Hosting Outline VPN on Kubernetes](/posts/ks-06-hosting-outline-vpn-kubernetes)
|
| 55 |
+
|
| 56 |
+
Outline VPN, a comprehensive server and client software tool, is a free and open-source system developed by Google.
|
| 57 |
+
In this article, we will delve into the process of hosting Outline VPN on Kubernetes and outlining the steps to expose connection ports via NGINX.
|
| 58 |
+
|
| 59 |
+
### [Day 07: Step-By-Step Guide: Hosting Longhorn on K3s (ARM)](/posts/ks-07-hosting-longhorn-on-kubernetes)
|
| 60 |
+
|
| 61 |
+
In this article, we will explore how to deploy Longhorn, a cloud-native distributed block storage system designed for Kubernetes on our K3s (ARM).
|
| 62 |
+
Longhorn is known for its lightweight, reliable, and open-source nature, which simplifies the process of adding persistent storage to Kubernetes clusters, making it easier to run stateful applications.
|
| 63 |
+
|
| 64 |
+
### [Day 08: To be continue...](/posts/ks-00-series-k8s-setup-local-env-pi-cluster)
|
| 65 |
+
|
| 66 |
+
---
|
| 67 |
+
|
| 68 |
+
## Thank You
|
| 69 |
+
|
| 70 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 71 |
+
|
| 72 |
+
**Steven** | *[GitHub](https://github.com/baoduy)*
|
ks-01-Install-k3s-on-pi-cluster.md
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- k3s
|
| 9 |
+
- kubernetes
|
| 10 |
+
- picluster
|
| 11 |
+
ogImage: ""
|
| 12 |
+
description:
|
| 13 |
+
In this guide, sharing some useful tips to help you seamlessly install K3s on a Raspberry Pi 4 cluster.
|
| 14 |
+
Let's dive in and start the installation process.
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
In this guide, share some useful tips to help you seamlessly install K3s on a Raspberry Pi 4 cluster.
|
| 18 |
+
Let's dive in and start the installation process.
|
| 19 |
+
|
| 20 |
+
## Raspberry Pi4 CLuster Illustration.
|
| 21 |
+
|
| 22 |
+
Before beginning the installation process, let's take a moment to review the cluster setup and the corresponding IP addresses assigned to each node in our Raspberry Pi 4 cluster.
|
| 23 |
+
|
| 24 |
+
<img src="/assets/ks-Install-k3s-on-pi-cluster/pi-cluster-diagram.png" width="600px">
|
| 25 |
+
|
| 26 |
+
In our configuration, we have three Raspberry Pi 4 units connected to a switch. This switch, in turn, is connected to the router supplied by my internet service provider.
|
| 27 |
+
Additionally, I have been provided with a static public IP address for internet access.
|
| 28 |
+
|
| 29 |
+
The table below outlines the specific IP configuration for each of the nodes in our Raspberry Pi cluster:
|
| 30 |
+
|
| 31 |
+

|
| 32 |
+
|
| 33 |
+
I will pick the Pi running at 192.168.1.85 as my master mode and start the installation as below instructions.
|
| 34 |
+
|
| 35 |
+
---
|
| 36 |
+
|
| 37 |
+
## K3s Installation
|
| 38 |
+
|
| 39 |
+
### Pi Os installation
|
| 40 |
+
|
| 41 |
+
Given our project's need for a k3s cluster, I selected the Raspberry Pi OS Lite 64Bit which can be downloaded from the [Raspberry PI Imager](https://www.raspberrypi.com/software/).
|
| 42 |
+
This particular OS variant doesn't include a desktop environment. Thus, SSH will be our primary method for node installation.
|
| 43 |
+
|
| 44 |
+

|
| 45 |
+
|
| 46 |
+
Before you flash the OS onto the SD Card, it's crucial to configure the node name and login details for each node.
|
| 47 |
+
|
| 48 |
+

|
| 49 |
+
|
| 50 |
+
Once the OS preparation for each node is complete, I set up the following cluster:
|
| 51 |
+
|
| 52 |
+
- **pi-master**: 192.168.1.85 (Running Pi OS Lite 64Bit)
|
| 53 |
+
- **pi-node-1**: 192.168.1.86 (Running Pi OS Lite 64Bit)
|
| 54 |
+
- **pi-node-2**: 192.168.1.87 (Running Pi OS Lite 64Bit)
|
| 55 |
+
|
| 56 |
+
I use `Termius` as my tool of choice for establishing a connection to the cluster for installation purposes. You can download it for free from [here](https://termius.com).
|
| 57 |
+
|
| 58 |
+
### I. Config static IP for Pi
|
| 59 |
+
|
| 60 |
+
By default, Pi OS will use DHCP to receive random Ip from the router, so to ensure the stable connectivity between the node
|
| 61 |
+
We will config the status IP for each node by using the following steps.
|
| 62 |
+
|
| 63 |
+
```shell
|
| 64 |
+
# 1. Open the file dhcpcd.conf
|
| 65 |
+
sudo nano /etc/dhcpcd.conf
|
| 66 |
+
|
| 67 |
+
# 2. update the below parameters according to your router ip-address.
|
| 68 |
+
interface eth0
|
| 69 |
+
static ip_address=192.168.1.85/24
|
| 70 |
+
static routers=192.168.1.254
|
| 71 |
+
|
| 72 |
+
# 3. select control + X and save the changes.
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
### II. Disable swap
|
| 76 |
+
|
| 77 |
+
When installing Kubernetes on Linux, it's recommended to disable swap because of how Kubernetes manages resources.
|
| 78 |
+
|
| 79 |
+
- **Memory Management**: Kubernetes efficiently manages and allocates resources, including memory. Allowing an operating system to swap can interrupt Kubernetes' memory management process.
|
| 80 |
+
|
| 81 |
+
- **Performance Issues**: Swapping can lead to performance degradation. When Kubernetes needs to access something that has been swapped to disk, it must wait for it to be loaded back into memory, causing delays.
|
| 82 |
+
|
| 83 |
+
- **Predictability**: Disabling swap helps ensure predictable performance, as it removes the chance of the system swapping out Kubernetes' processes.
|
| 84 |
+
|
| 85 |
+
- **Kubernetes Design**: Kubernetes is designed to work with no swapping activity. It assumes that applications are memory-resident, which means it expects them to stay in memory all the time.
|
| 86 |
+
|
| 87 |
+
To disable swap on Linux, you can use the following command:
|
| 88 |
+
|
| 89 |
+
```shell
|
| 90 |
+
# 1. Turn off swap temporary.
|
| 91 |
+
sudo swapoff -a
|
| 92 |
+
|
| 93 |
+
# 2. To turn of swap permanently we need to update the `CONF_SWAPSIZE` in `dphys-swapfile` file to `0`
|
| 94 |
+
sudo nano /etc/dphys-swapfile
|
| 95 |
+
|
| 96 |
+
# 3. set
|
| 97 |
+
CONF_SWAPSIZE=0
|
| 98 |
+
|
| 99 |
+
# 4. select control + X and save the changes.
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
### III. Cgroup configuration
|
| 103 |
+
|
| 104 |
+
If a `FATA[0000] failed to find memory cgroup (v2)` error surfaces during the installation of k3s, it is likely because the Pi OS lacks the required `cgroup` configuration. Below are the steps needed to resolve this issue:
|
| 105 |
+
|
| 106 |
+
```shell
|
| 107 |
+
# 1. Open the cmdline.txt file
|
| 108 |
+
sudo nano /boot/cmdline.txt
|
| 109 |
+
|
| 110 |
+
#2. Add below into THE END of the current line
|
| 111 |
+
cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory
|
| 112 |
+
|
| 113 |
+
# 3. Save the file and reboot
|
| 114 |
+
sudo reboot
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
### IV. Master node installation
|
| 118 |
+
|
| 119 |
+
Execute the following command to install the K3s master node. Make sure to replace the IP address according to your cluster configuration:
|
| 120 |
+
|
| 121 |
+
```shell
|
| 122 |
+
curl -sfL https://get.k3s.io | INSTALL_K3S_EXEC="server --disable=traefik --flannel-backend=host-gw --tls-san=192.168.1.85 --bind-address=192.168.1.85 --advertise-address=192.168.1.85 --node-ip=192.168.1.85 --cluster-init" sh -s -
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
**K3s parameters examination:**
|
| 126 |
+
|
| 127 |
+
- **server**: This is telling k3s to run in server mode (as opposed to agent mode). In server mode, k3s will start up and manage Kubernetes master components.
|
| 128 |
+
- **--disable=traefik**: This is instructing k3s to disable the Traefik ingress controller. By default, k3s includes and enables Traefik; this flag will prevent that from happening.
|
| 129 |
+
- **--flannel-backend=host-gw**: This flag is setting the backend for Flannel (k3s's default network provider) to use. The host-gw option provides high-performance networking by creating a route for each node in the cluster.
|
| 130 |
+
- **--tls-san=192.168.1.85**: The --tls-san flag allows you to specify additional IP or DNS names that should be included in the TLS certificate that is automatically generated for the Kubernetes API server. You can repeat this flag to add more than one SAN. The value 192.168.1.85 is an additional Subjective Alternative Name (SAN) for the Kubernetes API server's certificate.
|
| 131 |
+
- **--bind-address=192.168.1.85**: This is the IP address that the k3s API server will listen to.
|
| 132 |
+
- **--advertise-address=192.168.1.85**: This is the IP address that the k3s API server will advertise to other nodes in the cluster. They will use this IP to connect to the API server.
|
| 133 |
+
- **--node-ip=192.168.1.85**: This defines the IP that should be used for Kubernetes services on the node.
|
| 134 |
+
- **--cluster-init**: This flag instructs k3s to initialize a new Kubernetes cluster. If this flag is not provided, k3s will join an existing cluster if one is available.
|
| 135 |
+
|
| 136 |
+
Once installed, the k3s configuration should be located in `/etc/rancher/k3s/k3s.yaml`. Using this configuration with **[K8s Lend](https://k8slens.dev)** allows access to the K3s cluster.
|
| 137 |
+
|
| 138 |
+
Here's a snapshot of how it should look:
|
| 139 |
+
|
| 140 |
+

|
| 141 |
+
|
| 142 |
+
### V. Worker nodes installation
|
| 143 |
+
|
| 144 |
+
To install the worker nodes, we first need to obtain the `K3S_TOKEN` from the master node. Execute the command shown below to retrieve it:
|
| 145 |
+
|
| 146 |
+
```shell
|
| 147 |
+
# get node-token from master node
|
| 148 |
+
sudo cat /var/lib/rancher/k3s/server/node-token
|
| 149 |
+
|
| 150 |
+
# The result is something likes this
|
| 151 |
+
`THIS19937008cbde678aeaf200517f07c0ccd67dc80bdf4df6f746IS4780e15ebcd::server:40fc2cc2fnode81cdacc0b9bb1231token`
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
Upon retrieval of the node token, it is necessary to inject it into the script shown below. This script should be executed on all the Pi nodes specified previously. Please ensure to update the IP address associated with K3S_URL, as required.
|
| 155 |
+
|
| 156 |
+
```shell
|
| 157 |
+
# Execute this to install the nodes
|
| 158 |
+
curl -sfL https://get.k3s.io | K3S_URL=https://192.168.1.85:6443 \
|
| 159 |
+
K3S_TOKEN="THIS19937008cbde678aeaf200517f07c0ccd67dc80bdf4df6f746IS4780e15ebcd::server:40fc2cc2fnode81cdacc0b9bb1231token" sh -
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
Congratulations, your K3s cluster is now ready to be utilized.
|
| 163 |
+
|
| 164 |
+

|
| 165 |
+
|
| 166 |
+
---
|
| 167 |
+
|
| 168 |
+
## Thank You
|
| 169 |
+
|
| 170 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 171 |
+
|
| 172 |
+
**Steven** | *[GitHub](https://github.com/baoduy)*
|
ks-02-Install-nginx-on-pi-cluster.md
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2023-09-16T00:00:00Z
|
| 4 |
+
title: "[k8s] Step-By-Step Guide: Installing Nginx Ingress on K3s Pi 4 Cluster"
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- k3s
|
| 9 |
+
- kubernetes
|
| 10 |
+
- picluster
|
| 11 |
+
- nginx
|
| 12 |
+
ogImage: ""
|
| 13 |
+
description:
|
| 14 |
+
This guide provides helpful tips for installing the Nginx Ingress on a K3s Raspberry Pi 4 cluster.
|
| 15 |
+
Detailed and step-by-step instructions will ensure a seamless installation process. Let's get started!
|
| 16 |
+
---
|
| 17 |
+
|
| 18 |
+
In our [previous article](/posts/ks-install-k3s-on-raspberry-pi-cluster), we successfully set up a k3s Pi cluster. We will now build upon that foundation. Let's dive in!
|
| 19 |
+
|
| 20 |
+
<img src="/assets/ks-Install-k3s-on-pi-cluster/pi-cluster-diagram.png" width="600px">
|
| 21 |
+
|
| 22 |
+
- **pi-master**: 192.168.1.85 (Running Pi OS Lite 64Bit)
|
| 23 |
+
- **pi-node-1**: 192.168.1.86 (Running Pi OS Lite 64Bit)
|
| 24 |
+
- **pi-node-2**: 192.168.1.87 (Running Pi OS Lite 64Bit)
|
| 25 |
+
|
| 26 |
+
### Router Port Forwarding Setup.
|
| 27 |
+
|
| 28 |
+
In order to make the internal applications accessible via the internet, we need to set up port forwarding on our router.
|
| 29 |
+
This routing process will redirect internet requests coming to ports 80 and 443 to our master private IP node (192.168.1.85).
|
| 30 |
+
|
| 31 |
+
Please note, the configuration interface may vary among different routers. Nonetheless, most broadband routers should offer the same functionality pertaining to port forwarding.
|
| 32 |
+
|
| 33 |
+
<img src="/assets/ks-Install-nginx-on-pi-cluster/pi-cluster-port-forwarding-diagram.png" width="600px">
|
| 34 |
+
|
| 35 |
+
Here are my current router settings.
|
| 36 |
+
|
| 37 |
+
<img src="/assets/ks-Install-nginx-on-pi-cluster/router-port-forwarding-config.png" width="550px"/>
|
| 38 |
+
|
| 39 |
+
---
|
| 40 |
+
|
| 41 |
+
### Nginx installation
|
| 42 |
+
|
| 43 |
+
We're going to start by installing Nginx on our cluster. In the following guide, we will illustrate how to set up and run Nginx on K3s.
|
| 44 |
+
At its core, Nginx will listen to inbound requests on the master node's IP address and subsequently forward these requests to the services operating within our cluster.
|
| 45 |
+
|
| 46 |
+
<img alt="pi-cluster-nginx-diagram" src="/assets/ks-Install-nginx-on-pi-cluster/pi-cluster-nginx-diagram.png" width="600px">
|
| 47 |
+
|
| 48 |
+
**1. Config Ip address**
|
| 49 |
+
|
| 50 |
+
Helm charts come with a file called `values.yaml` which contains the default configuration values.
|
| 51 |
+
We can override these values by creating your own values.yaml file. Here is an example:
|
| 52 |
+
|
| 53 |
+
```yaml
|
| 54 |
+
# Refer to line 434 here for details
|
| 55 |
+
# https://github.com/kubernetes/ingress-nginx/blob/main/charts/ingress-nginx/values.yaml
|
| 56 |
+
|
| 57 |
+
controller:
|
| 58 |
+
service:
|
| 59 |
+
# Our primary node ip address here.
|
| 60 |
+
# Do remember replacing this ip address with your once accordingly.
|
| 61 |
+
loadBalancerIP: "192.168.1.85"
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
**2. Download the Helm chart:**
|
| 65 |
+
|
| 66 |
+
Download the Nginix helm chart. You can do this by adding the Nginx repo to the Helm. Run the following commands:
|
| 67 |
+
|
| 68 |
+
```shell
|
| 69 |
+
helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
|
| 70 |
+
helm repo update
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
**3. Create namespace**
|
| 74 |
+
|
| 75 |
+
```shell
|
| 76 |
+
kubectl create namespace nginx-ingress
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
**4. Install the Helm chart:**
|
| 80 |
+
|
| 81 |
+
Now you can install the Helm chart using your custom values.yaml file to override the default configuration values. Run the following command:
|
| 82 |
+
|
| 83 |
+
```shell
|
| 84 |
+
helm install nginx ingress-nginx/ingress-nginx --values values.yaml -n nginx-ingress
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
**5. Verify nginx pod:**
|
| 88 |
+
|
| 89 |
+
After installed successfully, we should be able to find a pod running there:
|
| 90 |
+

|
| 91 |
+
|
| 92 |
+
### Nginx Verification
|
| 93 |
+
|
| 94 |
+
**1. Deploy the echo application:**
|
| 95 |
+
|
| 96 |
+
You can deploy an echo server application using a simple Kubernetes deployment and service.
|
| 97 |
+
The echo server will respond with the same request it receives.
|
| 98 |
+
|
| 99 |
+
Here is a sample YAML file you can use:
|
| 100 |
+
|
| 101 |
+
```yaml
|
| 102 |
+
apiVersion: apps/v1
|
| 103 |
+
kind: Deployment
|
| 104 |
+
metadata:
|
| 105 |
+
name: echo-deployment
|
| 106 |
+
namespace: default
|
| 107 |
+
spec:
|
| 108 |
+
replicas: 1
|
| 109 |
+
selector:
|
| 110 |
+
matchLabels:
|
| 111 |
+
app: echo
|
| 112 |
+
template:
|
| 113 |
+
metadata:
|
| 114 |
+
labels:
|
| 115 |
+
app: echo
|
| 116 |
+
spec:
|
| 117 |
+
containers:
|
| 118 |
+
- name: echo
|
| 119 |
+
image: ealen/echo-server
|
| 120 |
+
ports:
|
| 121 |
+
- containerPort: 80
|
| 122 |
+
---
|
| 123 |
+
apiVersion: v1
|
| 124 |
+
kind: Service
|
| 125 |
+
metadata:
|
| 126 |
+
name: echo-service
|
| 127 |
+
namespace: default
|
| 128 |
+
spec:
|
| 129 |
+
ports:
|
| 130 |
+
- port: 80
|
| 131 |
+
selector:
|
| 132 |
+
app: echo
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
Save this YAML into a file, let's say `echo-app.yaml`, and apply it to `default` namespace (_using `default` namespace in Production is not recommended_):
|
| 136 |
+
|
| 137 |
+
```shell
|
| 138 |
+
kubectl apply -f echo-app.yaml -n default
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
2. Create an ingress rule:
|
| 142 |
+
|
| 143 |
+
Now that your echo server is running, you can create an ingress rule to route traffic to it.
|
| 144 |
+
|
| 145 |
+
Here is a sample ingress YAML:
|
| 146 |
+
|
| 147 |
+
```yaml
|
| 148 |
+
apiVersion: networking.k8s.io/v1
|
| 149 |
+
kind: Ingress
|
| 150 |
+
metadata:
|
| 151 |
+
name: echo-ingress
|
| 152 |
+
namespace: default
|
| 153 |
+
spec:
|
| 154 |
+
ingressClassName: nginx
|
| 155 |
+
rules:
|
| 156 |
+
# Replace the domain below with your domain accordingly.
|
| 157 |
+
- host: echo.drunkcoding.net
|
| 158 |
+
http:
|
| 159 |
+
paths:
|
| 160 |
+
- pathType: Prefix
|
| 161 |
+
path: "/"
|
| 162 |
+
backend:
|
| 163 |
+
service:
|
| 164 |
+
name: echo-service
|
| 165 |
+
port:
|
| 166 |
+
number: 80
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
**3. Update your domain DNS**
|
| 170 |
+
|
| 171 |
+
To ensure you can access from the internet, you need to point a domain to your public address.
|
| 172 |
+
|
| 173 |
+
Here is my `drunkcoding.net` DNS configuration on Cloudflare for reference purposes.
|
| 174 |
+

|
| 175 |
+
|
| 176 |
+
After all these configurations now we should be able to access your application hosting on our k3s cluster from the internet.
|
| 177 |
+
When accessing to `http://echo.drunkcoding.net` you able to see the JSON response from the echo pod as below.
|
| 178 |
+
|
| 179 |
+

|
| 180 |
+
|
| 181 |
+
---
|
| 182 |
+
|
| 183 |
+
## Thank You
|
| 184 |
+
|
| 185 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 186 |
+
|
| 187 |
+
**Steven** | *[GitHub](https://github.com/baoduy)*
|
ks-03-install-cert-manager-free-ssl-kubernetes-cluster.md
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2023-09-17T00:00:00Z
|
| 4 |
+
title: "[k8s] Step-By-Step Guide: Installation of Cert-Manager, Implementing Free SSL Certificates for Kubernetes Clusters"
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- k3s
|
| 9 |
+
- kubernetes
|
| 10 |
+
- cert-manager
|
| 11 |
+
- ssl
|
| 12 |
+
- tls
|
| 13 |
+
ogImage: ""
|
| 14 |
+
description:
|
| 15 |
+
This comprehensive guide will help you to smoothly install Cert-Manager and implement free SSL certificates for Kubernetes clusters.
|
| 16 |
+
It is designed with step-by-step instructions to facilitate a seamless installation process. Dive in and let's begin this journey for enhanced security!
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
Welcome back to our ongoing dialogue about Kubernetes. In the [previous article](/posts/ks-install-nginx-on-k3s-raspberry-pi-cluster/), we successfully executed the Nginx installation and made our applications internet-accessible.
|
| 20 |
+
However, you might've observed that the applications are operating under the HTTP protocol, which is not secure at present.
|
| 21 |
+
|
| 22 |
+
> As of July 2018, with the release of Chrome 68, Google started marking all non-HTTPS websites as 'Not secure' in the Chrome browser.
|
| 23 |
+
> This means that if a website doesn't use HTTPS, Chrome displays a warning to users in the address bar, indicating that the connection is not secure.
|
| 24 |
+
> The goal of this move was to push more webmasters to secure their websites with SSL/TLS certificates, providing a safer browsing experience for users.
|
| 25 |
+
|
| 26 |
+
Securing our applications through SSL encryption is crucial, particularly in production environments. For enhanced security, it's recommended to procure and implement valid SSL certificates for all production applications.
|
| 27 |
+
|
| 28 |
+
However, for the development or testing environments, which may not require paid SSL certificates, you can make use of Cert-Manager.
|
| 29 |
+
This tool utilizes Let's Encrypt to generate SSL certificates free of cost, providing a secure and cost-effective solution for **non-production** environments.
|
| 30 |
+
|
| 31 |
+
## Cert-Manager installation
|
| 32 |
+
|
| 33 |
+
1. **Prerequisite** - Kubernetes cluster with admin access is required. Make sure you have kubectl installed and configured to interact with your cluster.
|
| 34 |
+
|
| 35 |
+
2. **Add the Jetstack Helm repository** - Jetstack is the organization that maintains cert-manager, and they provide a Helm repository that we can use to install it:
|
| 36 |
+
|
| 37 |
+
```shell
|
| 38 |
+
helm repo add jetstack https://charts.jetstack.io
|
| 39 |
+
helm repo update
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
3. **Install cert-manager CustomResourceDefinitions** (CRDs) - These are the resources that cert-manager uses to store its configuration. Run the following command to install the CRDs:
|
| 43 |
+
|
| 44 |
+
Please make certain that you are utilizing the most up-to-date version. You can achieve this by substituting `v1.13.0` with the newest release from the cert-manager official GitHub repository.
|
| 45 |
+
Visit the following link to obtain the latest version: [Cert-Manager Releases](https://github.com/cert-manager/cert-manager/releases).
|
| 46 |
+
|
| 47 |
+
```shell
|
| 48 |
+
kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.0/cert-manager.crds.yaml
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
4. **Create cert-manager Namespace** - It's a good practice to install cert-manager in its own namespace. Use this command:
|
| 52 |
+
|
| 53 |
+
```shell
|
| 54 |
+
kubectl create namespace cert-manager
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
5. Create `value.yaml` file with the content below
|
| 58 |
+
|
| 59 |
+
```yaml
|
| 60 |
+
ingressShim:
|
| 61 |
+
defaultIssuerName: "letsencrypt-prod"
|
| 62 |
+
defaultIssuerKind: "ClusterIssuer"
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
6. **Install cert-manager** Helm chart - This will install cert-manager along with its components:
|
| 66 |
+
|
| 67 |
+
```shell
|
| 68 |
+
helm install cert-manager jetstack/cert-manager --values values.yaml -n cert-manager
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
7. **Verify the Installation** - Check if the cert-manager pods are running:
|
| 72 |
+
|
| 73 |
+

|
| 74 |
+
|
| 75 |
+
8. **Cluster Issuer configuration**
|
| 76 |
+
|
| 77 |
+
```yaml
|
| 78 |
+
# File name is `cluster-issuer.yaml`
|
| 79 |
+
apiVersion: cert-manager.io/v1
|
| 80 |
+
kind: ClusterIssuer
|
| 81 |
+
metadata:
|
| 82 |
+
# The name should be the same with `defaultIssuerName` above
|
| 83 |
+
name: letsencrypt-prod
|
| 84 |
+
namespace: cert-manager
|
| 85 |
+
spec:
|
| 86 |
+
acme:
|
| 87 |
+
server: https://acme-v02.api.letsencrypt.org/directory
|
| 88 |
+
# Replace with your domain email.
|
| 89 |
+
email: support@drunkcoding.net
|
| 90 |
+
privateKeySecretRef:
|
| 91 |
+
name: letsencrypt-prod
|
| 92 |
+
solvers:
|
| 93 |
+
- http01:
|
| 94 |
+
ingress:
|
| 95 |
+
# The ingress class name of nginx.
|
| 96 |
+
class: nginx
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
Apply it on the cluster:
|
| 100 |
+
|
| 101 |
+
```shell
|
| 102 |
+
kubectl apply -f cluster-issuer.yaml
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
## Update echo-app ingress.
|
| 106 |
+
|
| 107 |
+
Leverage the existing `echo-app` to enhance your project. We'll revise the ingress configuration to enable HTTPS for secure communication in our application.
|
| 108 |
+
Additionally, we'll integrate with cert-manager for automated SSL certificate generation.
|
| 109 |
+
|
| 110 |
+
```yaml
|
| 111 |
+
apiVersion: networking.k8s.io/v1
|
| 112 |
+
kind: Ingress
|
| 113 |
+
metadata:
|
| 114 |
+
name: echo-ingress
|
| 115 |
+
namespace: default
|
| 116 |
+
annotations:
|
| 117 |
+
# 1. enable cert-manager for this ingress
|
| 118 |
+
kubernetes.io/tls-acme: "true"
|
| 119 |
+
spec:
|
| 120 |
+
ingressClassName: nginx
|
| 121 |
+
# 3. Config the tls secret name. Replace the domain and secretName below with your config accordingly.
|
| 122 |
+
tls:
|
| 123 |
+
- hosts:
|
| 124 |
+
- echo.drunkcoding.net
|
| 125 |
+
secretName: tls-drunkcoding-net
|
| 126 |
+
rules:
|
| 127 |
+
- host: echo.drunkcoding.net
|
| 128 |
+
http:
|
| 129 |
+
paths:
|
| 130 |
+
- pathType: Prefix
|
| 131 |
+
path: "/"
|
| 132 |
+
backend:
|
| 133 |
+
service:
|
| 134 |
+
name: echo-service
|
| 135 |
+
port:
|
| 136 |
+
number: 80
|
| 137 |
+
```
|
| 138 |
+
|
| 139 |
+
> The certificate generated from `Let's Encrypt` has validity of 90 days. However, the `cert-manager` will automatically renew the certificate as it nears its expiration date.
|
| 140 |
+
|
| 141 |
+
## Verify application
|
| 142 |
+
|
| 143 |
+
Once the configuration is properly set up and the certificate has been successfully issued, you should be able to locate a certificate named `tls-drunkcoding-net` housed under the `default` namespace secrets.
|
| 144 |
+

|
| 145 |
+
|
| 146 |
+
The application is also fully functional with SSL for secure communication.
|
| 147 |
+

|
| 148 |
+
|
| 149 |
+
Below is the detailed certificate information as seen from the browser.
|
| 150 |
+

|
| 151 |
+
|
| 152 |
+
---
|
| 153 |
+
|
| 154 |
+
## Thank You
|
| 155 |
+
|
| 156 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel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Hoang
|
| 3 |
+
pubDatetime: 2023-09-17T02:00:00Z
|
| 4 |
+
title: "[k8s] Step-By-Step Guide: Cert-Manager Alternative with Cloudflare, Implementing Free SSL Certificates for Kubernetes Clusters"
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- k3s
|
| 9 |
+
- kubernetes
|
| 10 |
+
- cert-manager
|
| 11 |
+
- cloudflare
|
| 12 |
+
- ssl
|
| 13 |
+
- tls
|
| 14 |
+
ogImage: ""
|
| 15 |
+
description:
|
| 16 |
+
We explore the concept of using a Cert-Manager Alternative with Cloudflare to implement free SSL Certificates for Kubernetes clusters.
|
| 17 |
+
This strategy leverages Cloudflare SSL certificates conjunction with the Kubernetes setup to provide a secure environment, replacing the need of Cert-Manager.
|
| 18 |
+
Discover how this approach simplifies the process, and enhances the security of our Kubernetes clusters.
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
In our [previous post](/posts/ks-install-cert-manager-free-ssl-kubernetes-cluster), we walked through the process of successfully installing Cert-Manager to handle SSL certificate assignments for all ingresses.
|
| 22 |
+
While advantageous, this approach comes with a few noteworthy challenges:
|
| 23 |
+
|
| 24 |
+
- **Limited validity period**: Certificates provided by Cert-Manager are valid for a short period (90 days), meaning any third-party systems utilizing the services may need to update their certificate whitelist every 90 days.
|
| 25 |
+
- **Inappropriate for production environments**: Certificates provided by Let's Encrypt, while useful, may not be suitable for production environments.
|
| 26 |
+
- **Opening Port 80**: To validate and issue the certificate, Cert-Manager requires the use of insecure HTTP on port 80 during the process. However, if for any reason, the infrastructure team is reluctant to expose port 80 to the internet, then the operation of Cert-Manager may be compromised.
|
| 27 |
+
- **Potential Cert-Manager failures**: There can be instances where Cert-Manager encounters issues and fails to renew the certificate. In such cases, third-party systems may be unable to access our service due to failed certificate verification.
|
| 28 |
+
|
| 29 |
+
By understanding these issues, We'll explore a better solution to replace the Cert-Manager with Cloudflare. More detailed information will follow in subsequent posts.
|
| 30 |
+
|
| 31 |
+
## Cert-Manager Alternative
|
| 32 |
+
|
| 33 |
+
Cloudflare provides several valuable services:
|
| 34 |
+
|
| 35 |
+
1. **Domain Management**: Makes it simple to purchase, move, and control domain names. It centralised DNS record setup, subdomain management in once place.
|
| 36 |
+
|
| 37 |
+
2. **Universal SSL (Free)**: Provides automatic secure HTTPS access to our website. This saves time from the need to buy and manage SSL certificates.
|
| 38 |
+
|
| 39 |
+
3. **Advanced Certificate Manager**: Perfect for businesses wanting more control over their SSL certificates. We can customize the certificates, including those for multiple subdomain levels.
|
| 40 |
+
|
| 41 |
+
4. **Proxy**: Sits between the website's server and its visitors, with [WAF enabled](https://www.cloudflare.com/application-services/products/waf/) through proxy giving protection from threats like DDoS attacks and bots, while also enhancing performance.
|
| 42 |
+
All requests appear to be coming from Cloudflare IP addresses, enabling us to enhance site security by just whitelisting [Cloudflare IP Addresses](https://www.cloudflare.com/en-in/ips/).
|
| 43 |
+
|
| 44 |
+
## Kickstart with Cloudflare
|
| 45 |
+
|
| 46 |
+
1. Before we get started, ensure that we have a Cloudflare account that can register for one, free of charge, [here](https://www.cloudflare.com).
|
| 47 |
+
2. The next essential step is to onboard a Domain into Cloudflare's management system. Rest assured, this process is straightforward and involves zero downtime.
|
| 48 |
+
3. For demonstration, I have onboarded my `drunkcoding.net` to Cloudflare. Once a Domain is onboarded, it should resemble the following demonstration.
|
| 49 |
+

|
| 50 |
+
|
| 51 |
+
4. Moving forward to the **DNS** Records management, I have added an A record with the proxy option enabled, as shown below.
|
| 52 |
+

|
| 53 |
+
Once set up, all requests to subdomains such as `echo.drunkcoding.net`, `wiki.drunkcoding.net`, etc., will be redirected to my public IP address.
|
| 54 |
+
|
| 55 |
+
5. Next, under **SSL/TLS**, I created an Origin Server for the domains `drunkcoding.net and *.drunkcoding.net` and chose the certificate validity from 7 days to 15 years.
|
| 56 |
+

|
| 57 |
+
After setting this up, please ensure to download the certificate and private key immediately and save it to local files as we won't be able to access the private key in the future.
|
| 58 |
+
|
| 59 |
+
6. Following this, download the Cloudflare Root CA certificate from [here](https://developers.cloudflare.com/ssl/static/origin_ca_rsa_root.pem).
|
| 60 |
+
7. Once all the above steps are complete, we should have the following three files:
|
| 61 |
+
|
| 62 |
+
- `cert.crt`: This public key certification is in PEM format.
|
| 63 |
+
- `private.key`: This private key of the certificate is also in PEM format.
|
| 64 |
+
- `Root CA`: This root CA certificate is also in PEM format.
|
| 65 |
+
|
| 66 |
+
8. Switch the SSL/TLS encryption mode of the domain to `Full (strict)`
|
| 67 |
+

|
| 68 |
+
|
| 69 |
+
## Cloudflare Certificate Installation
|
| 70 |
+
|
| 71 |
+
1. **Certificate preparation:**
|
| 72 |
+
|
| 73 |
+
Before to proceeding, it is necessary to append the contents of the `Root CA` file to the `cert.crt` file, as illustrated in the following example:
|
| 74 |
+
|
| 75 |
+
```textmate
|
| 76 |
+
-----BEGIN CERTIFICATE-----
|
| 77 |
+
Content of cert.crt file here
|
| 78 |
+
-----END CERTIFICATE-----
|
| 79 |
+
-----BEGIN CERTIFICATE-----
|
| 80 |
+
Content of ca file here
|
| 81 |
+
-----END CERTIFICATE-----
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
2. **Create a secret certificate on kubernetes:**
|
| 85 |
+
|
| 86 |
+
Update the name based on your naming convention. In this context, we're using `tls` as the prefix and `import` as the suffix.
|
| 87 |
+
This denotes that it's a TLS certificate secret imported from a third party, as opposed to being auto-generated by Cert-Manager.
|
| 88 |
+
|
| 89 |
+
```shell
|
| 90 |
+
kubectl create secret tls tls-drunkcoding-net-import --cert=cert.crt --key=private.key --namespace=our-namespace
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
Remember to do this for each namespace in the cluster if there are services utilizing this domain.
|
| 94 |
+
|
| 95 |
+
After the successful creation, a secret, similar to the one illustrated below, should be identifiable.
|
| 96 |
+

|
| 97 |
+
|
| 98 |
+
3. **Update Application Ingress:**
|
| 99 |
+
|
| 100 |
+
Leverage the existing `echo-app` ingress. We'll revise the ingress configuration use the imported certificate by change the secretName of the ingress as below.
|
| 101 |
+
|
| 102 |
+
```yaml
|
| 103 |
+
apiVersion: networking.k8s.io/v1
|
| 104 |
+
kind: Ingress
|
| 105 |
+
metadata:
|
| 106 |
+
name: echo-ingress
|
| 107 |
+
namespace: default
|
| 108 |
+
annotations:
|
| 109 |
+
kubernetes.io/tls-acme: "true"
|
| 110 |
+
spec:
|
| 111 |
+
ingressClassName: nginx
|
| 112 |
+
tls:
|
| 113 |
+
- hosts:
|
| 114 |
+
- echo.drunkcoding.net
|
| 115 |
+
# only need to change this secret name.
|
| 116 |
+
secretName: tls-drunkcoding-net-imported
|
| 117 |
+
rules:
|
| 118 |
+
- host: echo.drunkcoding.net
|
| 119 |
+
http:
|
| 120 |
+
paths:
|
| 121 |
+
- pathType: Prefix
|
| 122 |
+
path: "/"
|
| 123 |
+
backend:
|
| 124 |
+
service:
|
| 125 |
+
name: echo-service
|
| 126 |
+
port:
|
| 127 |
+
number: 80
|
| 128 |
+
```
|
| 129 |
+
|
| 130 |
+
The application will be protected with cloudflare cert, and below is the detailed certificate information as seen from the browser.
|
| 131 |
+
|
| 132 |
+

|
| 133 |
+
|
| 134 |
+
You may observe that the certificates provided by Cloudflare and Cert-Manager bear a resemblance, owing to their shared use of Let's Encrypt for free SSL certificate generation.
|
| 135 |
+
However, it's important to note that for production applications, an upgrade to [**Cloudflare Advanced Certificate Manager**](https://www.cloudflare.com/lp/pg-advanced-certificate-manager/)
|
| 136 |
+
is recommended for Production environment which provides a certificate from a standard, trusted third-party authority and boasts an extended validity period.
|
| 137 |
+
|
| 138 |
+
> After completing these steps, we can proceed with uninstalling the Cert-Manager, as it is no longer needed.
|
| 139 |
+
|
| 140 |
+
---
|
| 141 |
+
|
| 142 |
+
## Thank You
|
| 143 |
+
|
| 144 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 145 |
+
|
| 146 |
+
**Steven** | *[GitHub](https://github.com/baoduy)*
|
ks-05-public-services-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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2023-09-18T00:00:00Z
|
| 4 |
+
title: "[k8s] Step-By-Step Guide: Nginx Alternative with Cloudflare Tunnel, Enables services to internet a public static IP address"
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- k3s
|
| 9 |
+
- kubernetes
|
| 10 |
+
- cloudflare
|
| 11 |
+
- tunnel
|
| 12 |
+
ogImage: ""
|
| 13 |
+
description:
|
| 14 |
+
This robust solution provides a feasible alternative to Nginx when there's no public static IP address or port forwarding required.
|
| 15 |
+
This guide walks us through the process step by step, enabling the services online more efficiently.
|
| 16 |
+
---
|
| 17 |
+
|
| 18 |
+
In the previous articles we successfully:
|
| 19 |
+
|
| 20 |
+
1. [Install kubernetes cluster](/posts/ks-install-k3s-on-raspberry-pi-cluster).
|
| 21 |
+
2. [Install Ngix on cluster](/posts/ks-install-nginx-on-k3s-raspberry-pi-cluster).
|
| 22 |
+
3. [Install SSL for Ingress with Cert-Manager](/posts/ks-install-cert-manager-free-ssl-kubernetes-cluster) or with [Cloudflare SSL](/posts/ks-cert-manager-alternative-with-cloudflare).
|
| 23 |
+
|
| 24 |
+
However, to expose our services to the internet, it's essential to obtain a **Static Public IP Address** and configure the **router/firewall to open ports 80 and 443**.
|
| 25 |
+
If for any reason we're unable to meet these requirements, we won't be able to expose our services online.
|
| 26 |
+
|
| 27 |
+
In addition, if our organization relies on private Kubernetes on cloud platforms such as AKS, EKS, or GKS, and we wish to expose a select set of services to the internet
|
| 28 |
+
without jeopardizing security, we might consider using [Cloudflare Tunnel](https://www.cloudflare.com/products/tunnel/).
|
| 29 |
+
|
| 30 |
+
Let's delve into this topic further.
|
| 31 |
+
|
| 32 |
+
<img src="/assets/ks-public-services-with-cloudflare-tunnel/argo-tunnel-network-diagram-1024x491.png" width="600px">
|
| 33 |
+
|
| 34 |
+
## Cloudflare Tunnel Configuration
|
| 35 |
+
|
| 36 |
+
1. This guide assumes that we have followed the instructions from our [previous post](/posts/ks-install-cert-manager-free-ssl-kubernetes-cluster), and configured Cloudflare account with at least one onboarded domain.
|
| 37 |
+
|
| 38 |
+
2. The next step is to create a [Cloudflare Zero Trust Account](https://one.dash.cloudflare.com). While creating this account might require adding a payment method, please note that there are no charges for the first 50 users. You can proceed to register without any hesitation.
|
| 39 |
+
|
| 40 |
+
<img src="/assets/ks-public-services-with-cloudflare-tunnel/cloudflare-zero-trust-dashboard.png" width="600px">
|
| 41 |
+
|
| 42 |
+
2. Once logged in, navigate to **Access => Tunnel** and create a new tunnel. For the purposes of this guide, we'll name it `pi-k3s`. After creating the tunnel, make sure to copy the tunnel token that appears (similar to the one below):
|
| 43 |
+
|
| 44 |
+
```textmate
|
| 45 |
+
eyJhIjoiYWVlMGFjYzZiYejTkz....yzCfgm7oqfnhz2DrJDKyL8PBDr9hR5FvYgDR45TxPiAxbmVW=
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
3. Finally, ensure we click the Save button to confirm the creation of the tunnel.
|
| 49 |
+
|
| 50 |
+
## Kubernetes Tunnel Installation
|
| 51 |
+
|
| 52 |
+
1. Create cloudflare Namespace. It's a good practice to install the tunnel in its own namespace. Use this command:
|
| 53 |
+
|
| 54 |
+
```shell
|
| 55 |
+
kubectl create namespace cloudflare
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
2. Create the `cloudflare-tunnel.yaml` deployment file as below:
|
| 59 |
+
|
| 60 |
+
```shell
|
| 61 |
+
apiVersion: v1
|
| 62 |
+
kind: Secret
|
| 63 |
+
metadata:
|
| 64 |
+
name: cloudflare-tunnel
|
| 65 |
+
namespace: cloudflare
|
| 66 |
+
labels:
|
| 67 |
+
app: cloudflare-tunnel
|
| 68 |
+
type: Opaque
|
| 69 |
+
stringData:
|
| 70 |
+
# the cloudflare tunnel token here
|
| 71 |
+
token: 'eyJhIjoiYWVlMGFjYzZiYejTkz....yzCfgm7oqfnhz2DrJDKyL8PBDr9hR5FvYgDR45TxPiAxbmVW='
|
| 72 |
+
---
|
| 73 |
+
apiVersion: apps/v1
|
| 74 |
+
kind: Deployment
|
| 75 |
+
metadata:
|
| 76 |
+
name: cloudflare-tunnel
|
| 77 |
+
namespace: cloudflare
|
| 78 |
+
labels:
|
| 79 |
+
app: tunnel
|
| 80 |
+
spec:
|
| 81 |
+
replicas: 2
|
| 82 |
+
selector:
|
| 83 |
+
matchLabels:
|
| 84 |
+
app: cloudflare-tunnel
|
| 85 |
+
template:
|
| 86 |
+
metadata:
|
| 87 |
+
labels:
|
| 88 |
+
app: cloudflare-tunnel
|
| 89 |
+
spec:
|
| 90 |
+
containers:
|
| 91 |
+
- name: cloudflare-tunnel
|
| 92 |
+
image: cloudflare/cloudflared:latest
|
| 93 |
+
args:
|
| 94 |
+
- tunnel
|
| 95 |
+
- '--no-autoupdate'
|
| 96 |
+
- run
|
| 97 |
+
- '--token'
|
| 98 |
+
- $(token)
|
| 99 |
+
envFrom:
|
| 100 |
+
- secretRef:
|
| 101 |
+
name: cloudflare-tunnel
|
| 102 |
+
resources:
|
| 103 |
+
limits:
|
| 104 |
+
cpu: 500m
|
| 105 |
+
memory: 512Mi
|
| 106 |
+
requests:
|
| 107 |
+
cpu: 1m
|
| 108 |
+
memory: 10Mi
|
| 109 |
+
imagePullPolicy: Always
|
| 110 |
+
securityContext:
|
| 111 |
+
readOnlyRootFilesystem: true
|
| 112 |
+
restartPolicy: Always
|
| 113 |
+
terminationGracePeriodSeconds: 30
|
| 114 |
+
dnsPolicy: ClusterFirst
|
| 115 |
+
automountServiceAccountToken: false
|
| 116 |
+
strategy:
|
| 117 |
+
type: RollingUpdate
|
| 118 |
+
rollingUpdate:
|
| 119 |
+
maxUnavailable: 25%
|
| 120 |
+
maxSurge: 25%
|
| 121 |
+
revisionHistoryLimit: 1
|
| 122 |
+
progressDeadlineSeconds: 600
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
3. Install Cloudflare tunnel:
|
| 126 |
+
|
| 127 |
+
```shell
|
| 128 |
+
kubectl apply -f cloudflare-tunnel.yaml
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
4. Verify running pods after deployed.
|
| 132 |
+
|
| 133 |
+

|
| 134 |
+
|
| 135 |
+
5. Back to the Cloudflare Zero Trust the tunnel status should be in `Health` also.
|
| 136 |
+
|
| 137 |
+

|
| 138 |
+
|
| 139 |
+
## Exposing the Application to the Internet
|
| 140 |
+
|
| 141 |
+
1. Navigate to the tunnel configuration page. Under the 'Public Host' section, add a public host name to expose our `echo service` to the internet. See the example below.
|
| 142 |
+
|
| 143 |
+
Note: Kubernetes internal service URLs follow the convention: `http://{service-name}.{namespace}.svc.cluster.local`.
|
| 144 |
+
|
| 145 |
+

|
| 146 |
+
|
| 147 |
+
2. Verify the performance of the application by visiting `https://echo.drunkcoding.net`. The service should be accessible without any constraints.
|
| 148 |
+
|
| 149 |
+
3. I have established two endpoints as follows and conducted a load test using Postman.
|
| 150 |
+
The results were astonishing as the Cloudflare tunnel delivered speeds even greater than direct access via Nginx.
|
| 151 |
+
|
| 152 |
+
- **echo-nginx.drunkcoding.net**: This endpoint provides access to the echo application through Nginx ingress and with a public IP address.
|
| 153 |
+
- **echo.drunkcoding.net**: This endpoint offers access to the echo application through the Cloudflare tunnel.
|
| 154 |
+
|
| 155 |
+
Please see the results in the attached image.
|
| 156 |
+

|
| 157 |
+
|
| 158 |
+
> Note: The cluster hosting this application is based in Singapore, while the test was conducted from a terminal in Vietnam.
|
| 159 |
+
|
| 160 |
+
## Concluding Remarks
|
| 161 |
+
|
| 162 |
+
Leveraging Cloudflare tunnels simplifies application exposure to the internet without the necessity of below:
|
| 163 |
+
|
| 164 |
+
- A public IP Address.
|
| 165 |
+
- Port forwarding.
|
| 166 |
+
- Firewall whitelisting.
|
| 167 |
+
- Nginx proxy/ingress.
|
| 168 |
+
- A Cert-manager or Cloudflare origin server certificate.
|
| 169 |
+
|
| 170 |
+
This results in a significantly simplified infrastructure setup.
|
| 171 |
+
|
| 172 |
+
---
|
| 173 |
+
|
| 174 |
+
## Thank You
|
| 175 |
+
|
| 176 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 177 |
+
|
| 178 |
+
**Steven** | *[GitHub](https://github.com/baoduy)*
|
ks-06-hosting-outline-vpn-kubernetes.md
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2023-10-05T00:00:00Z
|
| 4 |
+
title: "[k8s] Step-By-Step Guide: Hosting Outline VPN on Kubernetes"
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- k3s
|
| 9 |
+
- kubernetes
|
| 10 |
+
- nginx
|
| 11 |
+
- outline
|
| 12 |
+
ogImage: ""
|
| 13 |
+
description: "Outline VPN, a comprehensive server and client software tool, is a free and open-source system developed by Google.
|
| 14 |
+
In this article, we will delve into the process of hosting Outline VPN on Kubernetes and outlining the steps to expose connection ports via NGINX."
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
In our [previous article]("posts/ks-install-nginx-on-k3s-raspberry-pi-cluster"),
|
| 18 |
+
we were successfully installed NGINX on Kubernetes.Now, we're going to take NGINX for a spin and use it to host the Outline VPN on Kubernetes and open up our connection ports.
|
| 19 |
+
|
| 20 |
+
You're probably aware that by default, Outline VPN changes the client port each time a new connection is made.
|
| 21 |
+
It can be a bit of a challenge when we need to expose the ports through NGINX and get the outbound port on the whitelist at the firewall level.
|
| 22 |
+
|
| 23 |
+
However, there is a feature that allows us to modify the Outline VPN's default configuration during deployment.
|
| 24 |
+
With this little tweak, we can get all connections to pass through a single port and manage to expose both the management and client ports through NGINX.
|
| 25 |
+
Stick with us as we walk you through this process.
|
| 26 |
+
|
| 27 |
+
## Install Outline VPN
|
| 28 |
+
|
| 29 |
+
Before proceeding with the installation of the Outline, it's essential to define some variables as follows:
|
| 30 |
+
|
| 31 |
+
- **Management Port (60000)**: This port facilitates the connection between the Outline Manager and the VPN server.
|
| 32 |
+
- **Client Port (40000)**: This port is assigned for client devices to establish a connection with the VPN server.
|
| 33 |
+
- **Hostname (vpn.drunkcoding.net)**: This DNS (Domain Name Server) allows client devices to communicate with the VPN server from the public internet.
|
| 34 |
+
|
| 35 |
+
1. Let's start with a new _Outline-system_ namespace creation.
|
| 36 |
+
|
| 37 |
+
```shell
|
| 38 |
+
kubectl create namespace outline-system
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
2. Create a Self-sign certificate
|
| 42 |
+
|
| 43 |
+
To install Outline VPN, a required certificate plays multiple crucial roles:
|
| 44 |
+
|
| 45 |
+
- **Server Authentication**: This certificate is key in verifying the VPN server you're connecting to is the genuine one.
|
| 46 |
+
|
| 47 |
+
- **Data Encryption**: This certificate establishes the encryption for all data transmissions between your device and the VPN server.
|
| 48 |
+
If someone happens to intercept the data, they won't be able to decipher it due to this encryption.
|
| 49 |
+
|
| 50 |
+
- **Secured Connection Assurance**: This essential certificate ensures the connection between the client devices and the VPN server is both private and secure.
|
| 51 |
+
This is particularly crucial when connecting from insecure networks like public Wi-Fi.
|
| 52 |
+
|
| 53 |
+
Let's generate a self-signed certificate.
|
| 54 |
+
It can be accomplished through various methods, each tailored to specific environments.
|
| 55 |
+
|
| 56 |
+
Here, we'll be using OpenSSL as an example. The commands illustrating this process are detailed below:
|
| 57 |
+
|
| 58 |
+
```shell
|
| 59 |
+
# 1. Create private key
|
| 60 |
+
openssl genrsa -out private.key 2048
|
| 61 |
+
|
| 62 |
+
# 2. Create a Certificate Signing Request (CSR) using the private key with some parameters as below:
|
| 63 |
+
#-----
|
| 64 |
+
# - Country Name (2 letter code) [AU]:VN
|
| 65 |
+
# - State or Province Name (full name) [Some-State]:VN
|
| 66 |
+
# - Locality Name (eg, city) []:HCM
|
| 67 |
+
# - Organization Name (eg, company) [Internet Widgits Pty Ltd]:drunkcoding
|
| 68 |
+
# - Organizational Unit Name (eg, section) []:DCN
|
| 69 |
+
# - Common Name (e.g. server FQDN or YOUR name) []:vpn.drunkcoding.net
|
| 70 |
+
# - Email Address []:system@drunkcoding.net
|
| 71 |
+
|
| 72 |
+
# - Please enter the following 'extra' attributes
|
| 73 |
+
# - to be sent with your certificate request
|
| 74 |
+
# - A challenge password []:123456
|
| 75 |
+
# - An optional company name []:DCN
|
| 76 |
+
openssl req -new -key private.key -out csr_request.csr
|
| 77 |
+
|
| 78 |
+
# 3. Create a self-signed certificate
|
| 79 |
+
openssl x509 -req -days 365 -in csr_request.csr -signkey private.key -out cert.crt
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
Once the certificate is generated, following command to import into kubernetes cluster.
|
| 83 |
+
|
| 84 |
+
```shell
|
| 85 |
+
kubectl create secret tls tls-outline-vpn-imported --cert=cert.crt --key=private.key --namespace=outline-system
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
3. Deploy Outline Service with following `outline-deployment.yaml` file.
|
| 89 |
+
|
| 90 |
+
- **PersistentVolumeClaim**:
|
| 91 |
+
A PersistentVolumeClaim named _outline-vpn-claim_ is created
|
| 92 |
+
which requests storage is being created in the namespace _outline-system_ to store the configuration of Outline VPN.
|
| 93 |
+
- **Deployment**: A Deployment named _outline-vpn_ is being created in the namespace _outline-system_.
|
| 94 |
+
With this Deployment, a Pod is created with a container that uses the image quay.io/outline/shadowbox:stable. The container defines two TCP ports (40000, 60000) to expose.
|
| 95 |
+
- **Service**: A Service named _outline-vpn_ is configured to expose the Pods and expose the ports (40000 and 60000) for both TCP and UDP protocols.
|
| 96 |
+
|
| 97 |
+
```yaml
|
| 98 |
+
# 1. PersistentVolume
|
| 99 |
+
apiVersion: v1
|
| 100 |
+
kind: PersistentVolumeClaim
|
| 101 |
+
metadata:
|
| 102 |
+
name: outline-vpn-claim
|
| 103 |
+
namespace: outline-system
|
| 104 |
+
status:
|
| 105 |
+
phase: Bound
|
| 106 |
+
accessModes:
|
| 107 |
+
- ReadWriteOnce
|
| 108 |
+
capacity:
|
| 109 |
+
storage: 5Gi
|
| 110 |
+
spec:
|
| 111 |
+
accessModes:
|
| 112 |
+
- ReadWriteOnce
|
| 113 |
+
resources:
|
| 114 |
+
requests:
|
| 115 |
+
storage: 5Gi
|
| 116 |
+
#TODO: Remember to change `storageClassName` according to your environment.
|
| 117 |
+
storageClassName: local-path
|
| 118 |
+
volumeMode: Filesystem
|
| 119 |
+
---
|
| 120 |
+
#2. Pod Deployment
|
| 121 |
+
apiVersion: apps/v1
|
| 122 |
+
kind: Deployment
|
| 123 |
+
metadata:
|
| 124 |
+
name: outline-vpn
|
| 125 |
+
namespace: outline-system
|
| 126 |
+
spec:
|
| 127 |
+
replicas: 1
|
| 128 |
+
selector:
|
| 129 |
+
matchLabels:
|
| 130 |
+
app: outline-vpn
|
| 131 |
+
name: outline-vpn
|
| 132 |
+
template:
|
| 133 |
+
metadata:
|
| 134 |
+
labels:
|
| 135 |
+
app: outline-vpn
|
| 136 |
+
name: outline-vpn
|
| 137 |
+
spec:
|
| 138 |
+
volumes:
|
| 139 |
+
- name: server-config-volume
|
| 140 |
+
emptyDir: {}
|
| 141 |
+
- name: shadowbox-config
|
| 142 |
+
persistentVolumeClaim:
|
| 143 |
+
claimName: outline-vpn-claim
|
| 144 |
+
- name: tls
|
| 145 |
+
secret:
|
| 146 |
+
secretName: tls-outline-vpn-imported
|
| 147 |
+
items:
|
| 148 |
+
- key: tls.crt
|
| 149 |
+
path: shadowbox.crt
|
| 150 |
+
- key: tls.key
|
| 151 |
+
path: shadowbox.key
|
| 152 |
+
defaultMode: 420
|
| 153 |
+
containers:
|
| 154 |
+
- name: outline-vpn
|
| 155 |
+
image: quay.io/outline/shadowbox:stable
|
| 156 |
+
ports:
|
| 157 |
+
- containerPort: 40000
|
| 158 |
+
protocol: TCP
|
| 159 |
+
- containerPort: 60000
|
| 160 |
+
protocol: TCP
|
| 161 |
+
env:
|
| 162 |
+
- name: SB_API_PORT
|
| 163 |
+
value: "60000"
|
| 164 |
+
- name: SB_API_PREFIX
|
| 165 |
+
value: b782eecb-bb9e-58be-614a-d5de1431d6b3
|
| 166 |
+
- name: SB_CERTIFICATE_FILE
|
| 167 |
+
value: /tmp/shadowbox.crt
|
| 168 |
+
- name: SB_PRIVATE_KEY_FILE
|
| 169 |
+
value: /tmp/shadowbox.key
|
| 170 |
+
volumeMounts:
|
| 171 |
+
- name: server-config-volume
|
| 172 |
+
mountPath: /cache
|
| 173 |
+
- name: shadowbox-config
|
| 174 |
+
mountPath: /opt/outline
|
| 175 |
+
- name: shadowbox-config
|
| 176 |
+
mountPath: /root/shadowbox
|
| 177 |
+
- name: tls
|
| 178 |
+
readOnly: true
|
| 179 |
+
mountPath: /tmp/shadowbox.crt
|
| 180 |
+
subPath: shadowbox.crt
|
| 181 |
+
- name: tls
|
| 182 |
+
readOnly: true
|
| 183 |
+
mountPath: /tmp/shadowbox.key
|
| 184 |
+
subPath: shadowbox.key
|
| 185 |
+
lifecycle:
|
| 186 |
+
postStart:
|
| 187 |
+
exec:
|
| 188 |
+
command:
|
| 189 |
+
- /bin/sh
|
| 190 |
+
- "-c"
|
| 191 |
+
- >-
|
| 192 |
+
echo
|
| 193 |
+
'{"rollouts":[{"id":"single-port","enabled":true}],"portForNewAccessKeys":40000,"hostname":"vpn.drunkcoding.net"}'
|
| 194 |
+
>
|
| 195 |
+
/root/shadowbox/persisted-state/shadowbox_server_config.json;
|
| 196 |
+
imagePullPolicy: Always
|
| 197 |
+
restartPolicy: Always
|
| 198 |
+
terminationGracePeriodSeconds: 30
|
| 199 |
+
strategy:
|
| 200 |
+
type: RollingUpdate
|
| 201 |
+
rollingUpdate:
|
| 202 |
+
maxUnavailable: 25%
|
| 203 |
+
maxSurge: 25%
|
| 204 |
+
revisionHistoryLimit: 10
|
| 205 |
+
progressDeadlineSeconds: 600
|
| 206 |
+
---
|
| 207 |
+
# 3. Service
|
| 208 |
+
apiVersion: v1
|
| 209 |
+
kind: Service
|
| 210 |
+
metadata:
|
| 211 |
+
name: outline-vpn
|
| 212 |
+
namespace: outline-system
|
| 213 |
+
labels:
|
| 214 |
+
app: outline-vpn
|
| 215 |
+
spec:
|
| 216 |
+
ports:
|
| 217 |
+
- name: apiport-tcp
|
| 218 |
+
protocol: TCP
|
| 219 |
+
port: 60000
|
| 220 |
+
targetPort: 60000
|
| 221 |
+
- name: apiport-udp
|
| 222 |
+
protocol: UDP
|
| 223 |
+
port: 60000
|
| 224 |
+
targetPort: 60000
|
| 225 |
+
- name: accessport-tcp
|
| 226 |
+
protocol: TCP
|
| 227 |
+
port: 40000
|
| 228 |
+
targetPort: 40000
|
| 229 |
+
- name: accessport-udp
|
| 230 |
+
protocol: UDP
|
| 231 |
+
port: 40000
|
| 232 |
+
targetPort: 40000
|
| 233 |
+
selector:
|
| 234 |
+
app: outline-vpn
|
| 235 |
+
type: ClusterIP
|
| 236 |
+
internalTrafficPolicy: Cluster
|
| 237 |
+
```
|
| 238 |
+
|
| 239 |
+
Apply it on the cluster:
|
| 240 |
+
|
| 241 |
+
```shell
|
| 242 |
+
kubectl apply -f outline-deployment.yaml
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
Upon successful deployment, you should be able to see a pod along with its corresponding logs as in the screenshot below.
|
| 246 |
+

|
| 247 |
+
|
| 248 |
+
## PostStart command & Environment variables explanation
|
| 249 |
+
|
| 250 |
+
In the deployment lifecycle configuration above, there is a postStart command
|
| 251 |
+
that creates a JSON file located at **/root/shadowbox/persisted-state/shadowbox_server_config.json**.
|
| 252 |
+
|
| 253 |
+
The structure of the JSON object should look like this:
|
| 254 |
+
|
| 255 |
+
```json
|
| 256 |
+
{
|
| 257 |
+
"rollouts": [
|
| 258 |
+
{
|
| 259 |
+
"id": "single-port",
|
| 260 |
+
"enabled": true
|
| 261 |
+
}
|
| 262 |
+
],
|
| 263 |
+
"portForNewAccessKeys": 40000,
|
| 264 |
+
"hostname": "vpn.drunkcoding.net"
|
| 265 |
+
}
|
| 266 |
+
```
|
| 267 |
+
|
| 268 |
+
Let's break down the components of the JSON configuration for the Outline VPN:
|
| 269 |
+
|
| 270 |
+
- **rollouts**: This has an ID 'single-port', indicating to the Outline VPN that client connections are to be allowed on this single port.
|
| 271 |
+
- **portForNewAccessKeys**: This represents the port number (40000), where new access keys will be created.
|
| 272 |
+
- **hostname**: This refers to the domain name or IP address of the VPN server the clients will connect to, in this case being "vpn.drunkcoding.net".
|
| 273 |
+
|
| 274 |
+
There are also a few environment variables to acknowledge:
|
| 275 |
+
|
| 276 |
+
- **SB_API_PORT**: It denotes the port exposed by the Outline Management API.
|
| 277 |
+
- **SB_API_PREFIX**: It's a random GUID to be used as a prefix on the Outline Management API.
|
| 278 |
+
- **SB_CERTIFICATE_FILE**: It points to a file, /tmp/shadowbox.crt, which corresponds to the certificate we created earlier.
|
| 279 |
+
- **SB_PRIVATE_KEY_FILE**: This points to the path of the private key file. In this case, it's /tmp/shadowbox.key. This file matches the aforementioned certificate.
|
| 280 |
+
|
| 281 |
+
## Exposing connection ports through nginx
|
| 282 |
+
|
| 283 |
+
Once we've completed the installation as mentioned above, our Outline Container will be active and providing services on ports 60000 and 40000.
|
| 284 |
+
Currently, this service is confined to the Kubernetes network, meaning they can't be accessed directly from external sources, such as the internet.
|
| 285 |
+
|
| 286 |
+
In order to make these services receptive to outside connections, we'll need to expose the ports through NGINX.
|
| 287 |
+
The following illustration provides a visual representation on how to do this.
|
| 288 |
+

|
| 289 |
+
|
| 290 |
+
To begin with, we need to update the `values.yaml` file from our previous NGINX deployment. This configuration will open up the needed ports.
|
| 291 |
+
|
| 292 |
+
Here's the template:
|
| 293 |
+
|
| 294 |
+
```yaml
|
| 295 |
+
# Refer to line 155 and 160 here for details
|
| 296 |
+
# https://github.com/kubernetes/ingress-nginx/blob/main/charts/ingress-nginx/values.yaml
|
| 297 |
+
|
| 298 |
+
# 1. Expose the TCP with convention tcp: 'port':'namespace/service:port'
|
| 299 |
+
tcp:
|
| 300 |
+
60000: "outline-system/outline-vpn:60000"
|
| 301 |
+
40000: "outline-system/outline-vpn:40000"
|
| 302 |
+
|
| 303 |
+
# 2. Expose the UDP with convention udp: 'port':'namespace/service:port'
|
| 304 |
+
udp:
|
| 305 |
+
40000: "outline-system/outline-vpn:40000"
|
| 306 |
+
|
| 307 |
+
controller:
|
| 308 |
+
service:
|
| 309 |
+
loadBalancerIP: "192.168.1.85"
|
| 310 |
+
```
|
| 311 |
+
|
| 312 |
+
After updating the values.yaml with the correct information, re-upgrade the helm chart using the command:
|
| 313 |
+
|
| 314 |
+
```shell
|
| 315 |
+
# 1. To install brand new nginx
|
| 316 |
+
helm install nginx ingress-nginx/ingress-nginx --values values.yaml -n nginx-ingress
|
| 317 |
+
|
| 318 |
+
# 2. To update the existing nginx
|
| 319 |
+
helm upgrade nginx ingress-nginx/ingress-nginx --values values.yaml -n nginx-ingress
|
| 320 |
+
|
| 321 |
+
# 3. TO delete existing nginx and re-install with step 1 above.
|
| 322 |
+
helm delete nginx -n nginx-ingress
|
| 323 |
+
```
|
| 324 |
+
|
| 325 |
+
## Managing the Outline VPN
|
| 326 |
+
|
| 327 |
+
Follow these steps to manage your Outline VPN:
|
| 328 |
+
|
| 329 |
+
**Step 1: Download the Outline Manager**
|
| 330 |
+
|
| 331 |
+
Download the Outline Manager from [Outline's official website](https://getoutline.org/get-started/#step-1).
|
| 332 |
+
|
| 333 |
+
**Step 2: Prepare the Connection Configuration**
|
| 334 |
+
|
| 335 |
+
Prepare the connection configuration with the following parameters:
|
| 336 |
+
|
| 337 |
+
- **apiUrl**: Use the following format `https://{hostname}:{management-port}/{SB_API_PREFIX}`.
|
| 338 |
+
- **certSha256**: This is the thumbprint of the certificate created. Use the following command to access the thumbprint:
|
| 339 |
+
|
| 340 |
+
```shell
|
| 341 |
+
echo SHA=$(openssl x509 -noout -fingerprint -sha256 -inform pem -in cert.crt | sed "s/://g" | sed 's/.*=//')
|
| 342 |
+
```
|
| 343 |
+
|
| 344 |
+
**Step 3: Generate the Configuration**
|
| 345 |
+
|
| 346 |
+
Our configuration should look like this:
|
| 347 |
+
|
| 348 |
+
```json
|
| 349 |
+
{
|
| 350 |
+
"apiUrl": "https://vpn.drunkcoding.net:60000/b782eecb-bb9e-58be-614a-d5de1431d6b3",
|
| 351 |
+
"certSha256": "34B3C8EB1C6EC9B5335556D7E8DC73A30152D27C66B054BAB8ACF5D11AE0C810"
|
| 352 |
+
}
|
| 353 |
+
```
|
| 354 |
+
|
| 355 |
+
**Step 4: Setup Outline Anywhere**
|
| 356 |
+
|
| 357 |
+
Open the Outline Manager App and click **Setup Outline Anywhere**. Paste the configuration into the second input box and click Done. .
|
| 358 |
+

|
| 359 |
+
|
| 360 |
+
**Step 5: Connect to the Outline VPN Server**
|
| 361 |
+
|
| 362 |
+
On successful configuration, you should be able to connect to the Outline VPN server as shown below:
|
| 363 |
+

|
| 364 |
+
|
| 365 |
+
**Step 6: Create a Connection**
|
| 366 |
+
|
| 367 |
+
To allow the clients to connect to the server, click Add new key to create a connection and note down the access key:
|
| 368 |
+
|
| 369 |
+
```textmate
|
| 370 |
+
ss://Y2hhY2hhMjAtaWV0Zi1wb2x5MTMwNTpQc1YxY0V0ZkhzSVFueEJFVEVsMFRF@vpn.drunkcoding.net:40000/?outline=1
|
| 371 |
+
```
|
| 372 |
+
|
| 373 |
+
## Getting Started with the Outline Client
|
| 374 |
+
|
| 375 |
+
To get started with the VPN, follow the steps below:
|
| 376 |
+
|
| 377 |
+
1. Begin by navigating to the [Outline official website](https://getoutline.org/get-started/#step-3) to download the client application. Be sure to select the version compatible with your platform architecture.
|
| 378 |
+
|
| 379 |
+
2. Launch the client application. Select **Add Access Key**, then input the access key mentioned above. Afterward, click on **Add Server**.
|
| 380 |
+
<img src="/assets/ks-hosting-outline-vpn-kubernetes/outline-client-config.png" width="400px">
|
| 381 |
+
|
| 382 |
+
3. Proceed by clicking on the 'Connect' button to establish a connection.
|
| 383 |
+
|
| 384 |
+
4. To verify the VPN server's capability, access [myip.info](https://www.myip.info). Upon successful connection, your public IP address should reflect the Kubernetes outbound public IP. This means the VPN server is functioning as expected.
|
| 385 |
+
|
| 386 |
+
---
|
| 387 |
+
|
| 388 |
+
## Thank You
|
| 389 |
+
|
| 390 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 391 |
+
|
| 392 |
+
**Steven** | *[GitHub](https://github.com/baoduy)*
|
ks-07-hosting-longhorn-on-kubernetes.md
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-02-29T00:00:00Z
|
| 4 |
+
title: "[k8s] Step-By-Step Guide: Hosting Longhorn on K3s (ARM)"
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- k3s
|
| 9 |
+
- kubernetes
|
| 10 |
+
- longhorn
|
| 11 |
+
- storage
|
| 12 |
+
ogImage: ""
|
| 13 |
+
description: "In this article, we will explore how to deploy Longhorn, a cloud-native distributed block storage system designed for Kubernetes on our K3s (ARM).
|
| 14 |
+
Longhorn is known for its lightweight, reliable, and open-source nature, which simplifies the process of adding persistent storage to Kubernetes clusters, making it easier to run stateful applications."
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
As you know by default the kubernetes provide a **"local-path"** storage. However, this local storage has many limitation:
|
| 18 |
+
|
| 19 |
+
1. **Node Affinity**: When using local-path storage, the volume created is tied to the specific node where the pod runs.
|
| 20 |
+
If that node goes down for maintenance or any other reason, the pods won’t be able to start on other nodes because they won’t find their volumes.
|
| 21 |
+
|
| 22 |
+
2. **Not Network Storage**: Local-path storage is not network-based. The volume remains local to the K3s node where the pod executes.
|
| 23 |
+
It doesn't allow data sharing across nodes.
|
| 24 |
+
|
| 25 |
+
3. **Not Suitability for Production**: While local-path storage is suitable for small, single-node development clusters,
|
| 26 |
+
it’s not recommended for production-grade multi-node clusters.
|
| 27 |
+
|
| 28 |
+
## What is Longhorn?
|
| 29 |
+
|
| 30 |
+
Longhorn, an innovative open-source project by **Rancher Labs**, offers a reliable, lightweight, and user-friendly distributed block storage system for Kubernetes.
|
| 31 |
+
|
| 32 |
+
1. **High Availability**: Longhorn replicates storage volumes across multiple nodes in the Kubernetes cluster,
|
| 33 |
+
ensuring that data remains available even if a node fails.
|
| 34 |
+
2. **Cost-Effective**: Traditional external storage arrays can be expensive and non-portable. Longhorn offers a cost-effective,
|
| 35 |
+
cloud-native solution that can run anywhere.
|
| 36 |
+
3. **Disaster Recovery**: Longhorn allows you to easily create a disaster recovery volume in another Kubernetes cluster and fail over to it in the event of an emergency.
|
| 37 |
+
This ensures that your applications can quickly recover with a defined Recovery Point Objective (RPO) and Recovery Time Objective (RTO).
|
| 38 |
+
|
| 39 |
+
## Longhorn installation
|
| 40 |
+
|
| 41 |
+
Longhorn provides a straightforward method for installing the iSCSI driver and NFSv4 directly on all nodes. Follow the steps below to set up the necessary components.
|
| 42 |
+
|
| 43 |
+
1. **Installing open-iscsi**
|
| 44 |
+
|
| 45 |
+
The open-iscsi package is a prerequisite for Longhorn to create distributed volumes that can be shared across nodes.
|
| 46 |
+
Ensure that this driver is installed on all worker nodes within your cluster.
|
| 47 |
+
|
| 48 |
+
Execute the following command on your cluster to install the driver
|
| 49 |
+
|
| 50 |
+
```shell
|
| 51 |
+
# please check the latest release of the longhorn here https://github.com/longhorn/longhorn and update the version accordingly. Current version is v1.6.0
|
| 52 |
+
kubectl apply -f https://raw.githubusercontent.com/longhorn/longhorn/v1.6.0/deploy/prerequisite/longhorn-iscsi-installation.yaml
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
After deploying the iSCSI driver, confirm the status of the installer pods using the following command:
|
| 56 |
+
|
| 57 |
+
```shell
|
| 58 |
+
kubectl get pod | grep longhorn-iscsi-installation
|
| 59 |
+
|
| 60 |
+
# The result
|
| 61 |
+
longhorn-iscsi-installation-pdbgq 1/1 Running 0 21m
|
| 62 |
+
longhorn-iscsi-installation-qplbb 1/1 Running 0 39m
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
Additionally, review the installation logs to ensure successful deployment:
|
| 66 |
+
|
| 67 |
+
```shell
|
| 68 |
+
kubectl logs longhorn-iscsi-installation-pdbgq -c iscsi-installation
|
| 69 |
+
|
| 70 |
+
# The result
|
| 71 |
+
...
|
| 72 |
+
IProcessing triggers for libc-bin (2.35-0ubuntu3.6) ...
|
| 73 |
+
Processing triggers for man-db (2.10.2-1) ...
|
| 74 |
+
Processing triggers for initramfs-tools (0.140ubuntu13.1) ...
|
| 75 |
+
update-initramfs: Generating /boot/initrd.img-6.5.0-18-generic
|
| 76 |
+
iscsi install successfully
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
Once the iscsi installed successfully, Then you can safely uninstall the above with following command.
|
| 80 |
+
|
| 81 |
+
```shell
|
| 82 |
+
kubectl delete -f https://raw.githubusercontent.com/longhorn/longhorn/v1.6.0/deploy/prerequisite/longhorn-iscsi-installation.yaml
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
2. **Installing NFSv4 client**
|
| 86 |
+
|
| 87 |
+
To enable Longhorn’s backup functionality and ensure proper operation, the NFSv4 client must be installed on the worker nodes within your cluster.
|
| 88 |
+
|
| 89 |
+
Follow these steps to set up the necessary components:
|
| 90 |
+
|
| 91 |
+
```shell
|
| 92 |
+
# please check the latest release of the longhorn here https://github.com/longhorn/longhorn and update the version accordingly. Current version is v1.6.0
|
| 93 |
+
kubectl apply -f https://raw.githubusercontent.com/longhorn/longhorn/v1.6.0/deploy/prerequisite/longhorn-nfs-installation.yaml
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
After deploying the NFSv4 client, confirm the status of the installer pods using the following command:
|
| 97 |
+
|
| 98 |
+
```shell
|
| 99 |
+
kubectl get pod | grep longhorn-nfs-installation
|
| 100 |
+
|
| 101 |
+
# The results
|
| 102 |
+
NAME READY STATUS RESTARTS AGE
|
| 103 |
+
longhorn-nfs-installation-mt5p7 1/1 Running 0 143m
|
| 104 |
+
longhorn-nfs-installation-n6nnq 1/1 Running 0 143m
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
And also can check the log with the following command to see the installation result:
|
| 108 |
+
|
| 109 |
+
```shell
|
| 110 |
+
kubectl logs longhorn-nfs-installation-mt5p7 -c nfs-installation
|
| 111 |
+
|
| 112 |
+
# The results
|
| 113 |
+
...
|
| 114 |
+
rpc-svcgssd.service is a disabled or a static unit, not starting it.
|
| 115 |
+
rpc_pipefs.target is a disabled or a static unit, not starting it.
|
| 116 |
+
var-lib-nfs-rpc_pipefs.mount is a disabled or a static unit, not starting it.
|
| 117 |
+
Processing triggers for man-db (2.10.2-1) ...
|
| 118 |
+
Processing triggers for libc-bin (2.35-0ubuntu3.6) ...
|
| 119 |
+
nfs install successfully
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
Once the NFSv4 installed successfully, Then you can safely uninstall the above with following command.
|
| 123 |
+
|
| 124 |
+
```shell
|
| 125 |
+
kubectl delete -f https://raw.githubusercontent.com/longhorn/longhorn/v1.6.0/deploy/prerequisite/longhorn-nfs-installation.yaml
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
3. **Installing Longhorn**
|
| 129 |
+
|
| 130 |
+
- Preparing the configuration `value.yaml` file
|
| 131 |
+
|
| 132 |
+
```yaml
|
| 133 |
+
csi:
|
| 134 |
+
kubeletRootDir: "/var/lib/kubelet"
|
| 135 |
+
defaultSettings:
|
| 136 |
+
diskType: "flesystem"
|
| 137 |
+
```
|
| 138 |
+
|
| 139 |
+
- Install Longhorn in the `longhorn-system` namespace with configuration above.
|
| 140 |
+
|
| 141 |
+
```shell
|
| 142 |
+
# 1. added longhorn chart
|
| 143 |
+
helm repo add longhorn https://charts.longhorn.io
|
| 144 |
+
helm repo update
|
| 145 |
+
|
| 146 |
+
# 2. Installing
|
| 147 |
+
helm install longhorn longhorn/longhorn -f value.yaml --namespace longhorn-system --create-namespace
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
+
Once installed successfully and all the pods are up and running.
|
| 151 |
+
You should be able to access Longhorn UI through the `longhorn-frontend` service (needs port-forward or expose through nginx or cloudflare tunnel).
|
| 152 |
+
<img src="/assets/ks-hosting-longhorn-on-kubernetes/longhorn-ui.png" width="600px">
|
| 153 |
+
|
| 154 |
+
4. **Uninstalling Longhorn**
|
| 155 |
+
|
| 156 |
+
If any reason we would like to uninstall Longhorn helm then the below commands will help.
|
| 157 |
+
|
| 158 |
+
```shell
|
| 159 |
+
# Update `deleting-confirmation-flag` to allows uninstall longhorn
|
| 160 |
+
kubectl -n longhorn-system patch -p '{"value": "true"}' --type=merge lhs deleting-confirmation-flag
|
| 161 |
+
# Uninstall longhorn
|
| 162 |
+
helm uninstall longhorn -n longhorn-system
|
| 163 |
+
# Delete namespace
|
| 164 |
+
kubectl delete namespace longhorn-system
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
### Using the Longhorn storage with Mariadb
|
| 168 |
+
|
| 169 |
+
To explore Longhorn storage capabilities, we’ll set up a MariaDB Galera multi-primary database cluster for synchronous replication and high availability. Follow these steps:
|
| 170 |
+
|
| 171 |
+
```shell
|
| 172 |
+
# Setup chart repo
|
| 173 |
+
helm repo add bitnami https://charts.bitnami.com/bitnami
|
| 174 |
+
helm repo update
|
| 175 |
+
|
| 176 |
+
# Install mariadb-ha
|
| 177 |
+
helm install mariadb-ha bitnami/mariadb-galera \
|
| 178 |
+
--set global.storageClass=longhorn \
|
| 179 |
+
--set rootUser.password=Pass@word1 \
|
| 180 |
+
--set galera.mariabackup.password=Password1 \
|
| 181 |
+
--set db.name=drunk_db \
|
| 182 |
+
--namespace db --create-namespace
|
| 183 |
+
|
| 184 |
+
# Uninstall mariadb-ha
|
| 185 |
+
helm uninstall mariadb-ha -n db
|
| 186 |
+
```
|
| 187 |
+
|
| 188 |
+
After deployed successful, you should find three MariaDB pods running in the `db` namespace:
|
| 189 |
+
|
| 190 |
+
```shell
|
| 191 |
+
kubectl get pod -n db
|
| 192 |
+
|
| 193 |
+
# The results
|
| 194 |
+
NAME READY STATUS RESTARTS AGE
|
| 195 |
+
mariadb-ha-mariadb-galera-0 1/1 Running 0 5m6s
|
| 196 |
+
mariadb-ha-mariadb-galera-1 1/1 Running 0 3m44s
|
| 197 |
+
mariadb-ha-mariadb-galera-2 1/1 Running 0 2m41s
|
| 198 |
+
```
|
| 199 |
+
|
| 200 |
+
You’ll also find three persistent volumes in the Longhorn UI portal. !Longhorn Volumes
|
| 201 |
+
<img src="/assets/ks-hosting-longhorn-on-kubernetes/longhorn-volumes.png" width="600px">
|
| 202 |
+
|
| 203 |
+
### Longhorn System Backup
|
| 204 |
+
|
| 205 |
+
Longhorn supports a variety of backup targets, including Azure Storage, AWS S3, Google Storage, NFS, and SMB/CIFS.
|
| 206 |
+
This post will initially cover the configuration for Azure Storage, with subsequent posts addressing the other backup targets.
|
| 207 |
+
|
| 208 |
+
1. **System Backup with Azure Storage**
|
| 209 |
+
|
| 210 |
+
This section assumes that you already have Azure Storage and a Kubernetes cluster that can connect to Azure.
|
| 211 |
+
|
| 212 |
+
- Create a `longhorn-azure-blob-backup.yaml` secret with your Azure Storage Account credentials:
|
| 213 |
+
|
| 214 |
+
```yaml
|
| 215 |
+
# Update the secret below with your Azure Storage Account credentials
|
| 216 |
+
apiVersion: v1
|
| 217 |
+
kind: Secret
|
| 218 |
+
metadata:
|
| 219 |
+
name: longhorn-azure-blob-backup
|
| 220 |
+
namespace: longhorn-system
|
| 221 |
+
stringData:
|
| 222 |
+
AZBLOB_ACCOUNT_KEY: "YOUR_STORAGE_KEY"
|
| 223 |
+
AZBLOB_ACCOUNT_NAME: "YOUR_STORAGE_NAME"
|
| 224 |
+
```
|
| 225 |
+
|
| 226 |
+
- Apply the secret to the cluster using the following command.
|
| 227 |
+
|
| 228 |
+
```shell
|
| 229 |
+
kubectl apply -f longhorn-azure-blob-backup.yaml
|
| 230 |
+
```
|
| 231 |
+
|
| 232 |
+
- Next, update the backup information in the defaultSettings section of the `value.yaml` file:
|
| 233 |
+
|
| 234 |
+
```yaml
|
| 235 |
+
csi:
|
| 236 |
+
kubeletRootDir: "/var/lib/kubelet"
|
| 237 |
+
defaultSettings:
|
| 238 |
+
diskType: "flesystem"
|
| 239 |
+
backupTargetCredentialSecret: "longhorn-azure-blob-backup" #The name of the secret created above.
|
| 240 |
+
backupTarget: "azblob://YOUR_CONTAINER_NAME@core.windows.net/" # Trailer slash is important
|
| 241 |
+
```
|
| 242 |
+
|
| 243 |
+
- Upgrade the Longhorn Helm chart with the updated values using the following command:
|
| 244 |
+
|
| 245 |
+
```shell
|
| 246 |
+
helm upgrade longhorn longhorn/longhorn -f value.yaml --namespace longhorn-system
|
| 247 |
+
|
| 248 |
+
# You should see a message indicating that the upgrade was successful
|
| 249 |
+
Release "longhorn" has been upgraded. Happy Helming!
|
| 250 |
+
NAME: longhorn
|
| 251 |
+
LAST DEPLOYED: Wed Feb 28 08:57:56 2024
|
| 252 |
+
NAMESPACE: longhorn-system
|
| 253 |
+
STATUS: deployed
|
| 254 |
+
REVISION: 2
|
| 255 |
+
TEST SUITE: None
|
| 256 |
+
NOTES:
|
| 257 |
+
Longhorn is now installed on the cluster!
|
| 258 |
+
|
| 259 |
+
Please wait a few minutes for other Longhorn components such as CSI deployments, Engine Images, and Instance Managers to be initialized.
|
| 260 |
+
|
| 261 |
+
Visit our documentation at https://longhorn.io/docs/
|
| 262 |
+
```
|
| 263 |
+
|
| 264 |
+
- Once the upgrade is complete, the backup information under `Setting` → `General` should reflect the changes made.
|
| 265 |
+
<img src="/assets/ks-hosting-longhorn-on-kubernetes/long-horn-azure-backup.png" width="600px">
|
| 266 |
+
|
| 267 |
+
- After creating a sys-backup under `Setting` → `System Backup`, you should see the following
|
| 268 |
+
<img src="/assets/ks-hosting-longhorn-on-kubernetes/azure-sys-bakup.png" width="600px">
|
| 269 |
+
|
| 270 |
+
- You should be able to see the data being backed up into the Azure Storage Container.
|
| 271 |
+
<img src="/assets/ks-hosting-longhorn-on-kubernetes/azure-storage-account.png" width="600px">
|
| 272 |
+
|
| 273 |
+
---
|
| 274 |
+
|
| 275 |
+
## Thank You
|
| 276 |
+
|
| 277 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 278 |
+
|
| 279 |
+
**Steven** | *[GitHub](https://github.com/baoduy)*
|
ks-08-cert-manager-with-private-aks.md
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-08-15T00:00:00Z
|
| 4 |
+
title: "[AKS] Implementing Cert Manager with Private Azure Kubernetes Service (AKS)."
|
| 5 |
+
featured: false
|
| 6 |
+
draft: false
|
| 7 |
+
tags:
|
| 8 |
+
- aks
|
| 9 |
+
- cert-manager
|
| 10 |
+
ogImage: ""
|
| 11 |
+
description: "Exploring the deployment and management of SSL certificates using cert-manager in a private Azure Kubernetes Service (AKS) environment.
|
| 12 |
+
This article covers the architecture involving CloudPC and AKS VNETs, the use of NGINX ingress for private connections, and the implementation of Cloudflare DNS management to secure internal communications."
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
In a previous [post](https://drunkcoding.net/posts/ks-03-install-cert-manager-free-ssl-kubernetes-cluster/), It detailed how to set up Cert Manager on a Raspberry Pi K3s Cluster. That was a great starting point, and in this article, I decided to explore a more complex scenario by deploying Cert Manager within a private Kubernetes cluster on Azure. I’m excited to share the insights and techniques I discovered along the way, hoping they can make your journey a bit smoother."
|
| 16 |
+
|
| 17 |
+
### **Azure Architecture Overview**
|
| 18 |
+
|
| 19 |
+
The following diagram illustrates the architecture we'll be working with:
|
| 20 |
+
<img src="/assets/aks-cert-manager-with-private-aks/private-AKS-with-cert-manager.png">
|
| 21 |
+
|
| 22 |
+
The setup involves two Virtual Networks (VNETs) that are peered:
|
| 23 |
+
|
| 24 |
+
1. **CloudPC VNET:** This is where we host all our Windows 365 Enterprise environments, allowing remote users to securely access the company’s resources.
|
| 25 |
+
|
| 26 |
+
2. **AKS VNET:** This VNET hosts our private AKS cluster. To keep things secure, I’ve set up a firewall that controls all outbound traffic, with no direct inbound access from the internet. The public IP is purely for outbound traffic—no inbound ports are left open.
|
| 27 |
+
|
| 28 |
+
3. **NGINX Ingress:** This piece allows CloudPC to access applications running on AKS through VNET peering, making sure everything stays within a private network.
|
| 29 |
+
|
| 30 |
+
### **The Challenge I Encountered: Securing Internal Traffic**
|
| 31 |
+
|
| 32 |
+
One of the challenges I came across was figuring out how to secure the communication between the applications hosted on AKS and the CloudPC environment, even though it’s all internal within the virtual networks. I wanted to make sure that all data in transit was encrypted using SSL certificates.
|
| 33 |
+
|
| 34 |
+
### **How I Solved It: Leveraging Cloudflare DNS and Cert Manager**
|
| 35 |
+
|
| 36 |
+
To address the challenge, I implemented the following approach:
|
| 37 |
+
|
| 38 |
+
1. **Domain Setup with Cloudflare:** Let’s assume I have a domain, `drunk.dev`, registered with Cloudflare. While this domain isn’t directly used for external-facing services. But, I utilize this domain with Let’s Encrypt to verify and issue SSL certificates for the ingress controllers of my applications within the AKS cluster.
|
| 39 |
+
|
| 40 |
+
2. **Internal DNS Configuration on Azure:** Internally, I created a private DNS Zone in Azure with the same name (`drunk.dev`) and linked this zone to both the CloudPC and AKS VNETs. This setup is critical as it ensures that internal DNS queries for the `drunk.dev` domain are resolved correctly within the private network, facilitating secure communication between services.
|
| 41 |
+
|
| 42 |
+
---
|
| 43 |
+
|
| 44 |
+
### **Installation**
|
| 45 |
+
|
| 46 |
+
1. **Create a Cloudflare DNS API Token:**
|
| 47 |
+
First, navigate to the Cloudflare profile and create an API token by following [this link](https://dash.cloudflare.com/profile/api-tokens). The API token should have permissions to manage DNS records for the domains.
|
| 48 |
+
|
| 49 |
+
Additionally, for enhanced security, specify the AKS public IP address under `Client IP Address Filtering` in Cloudflare. This ensures that the API token is only accessible from the AKS platform, preventing unauthorized access from other locations.
|
| 50 |
+
<img src="/assets/aks-cert-manager-with-private-aks/cf-dns-token.png">
|
| 51 |
+
|
| 52 |
+
2. **Create a Kubernetes Secret for the Cloudflare API Token:**
|
| 53 |
+
|
| 54 |
+
Next, create a Kubernetes secret to securely store the Cloudflare API token within the AKS cluster. This secret will be referenced by Cert Manager during DNS validation.
|
| 55 |
+
|
| 56 |
+
```yaml
|
| 57 |
+
apiVersion: "v1"
|
| 58 |
+
kind: Secret
|
| 59 |
+
metadata:
|
| 60 |
+
name: cf-dns-secret
|
| 61 |
+
stringData:
|
| 62 |
+
token: "YOUR-CF-DNS-TOKEN"
|
| 63 |
+
# Replace 'YOUR-CF-DNS-TOKEN' with the actual API token generated in the previous step.
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
3. **Cert Manager Installation:**
|
| 67 |
+
|
| 68 |
+
- **Create a values.yaml file for Helm Installation:**
|
| 69 |
+
Before installing Cert Manager, create a values.yaml file with the following content. The extraArgs section is important as it directs Cert Manager to use Cloudflare’s DNS resolver for DNS-01 challenge validation.
|
| 70 |
+
|
| 71 |
+
```yaml
|
| 72 |
+
# auto create CRD resources
|
| 73 |
+
installCRDs: true
|
| 74 |
+
|
| 75 |
+
# Default ingress value
|
| 76 |
+
ingressShim:
|
| 77 |
+
defaultIssuerName: "letsencrypt-prod"
|
| 78 |
+
defaultIssuerKind: "ClusterIssuer"
|
| 79 |
+
defaultIssuerGroup: "cert-manager.io"
|
| 80 |
+
|
| 81 |
+
#extra args is important for Cloudflare DNS validation
|
| 82 |
+
extraArgs:
|
| 83 |
+
- --dns01-recursive-nameservers-only
|
| 84 |
+
- --dns01-recursive-nameservers=1.1.1.1:53
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
This configuration ensures that Cert Manager will only use Cloudflare’s DNS servers (specifically 1.1.1.1:53) to perform DNS-01 challenge validation, which is necessary for issuing SSL certificates.
|
| 88 |
+
|
| 89 |
+
- **Install Cert Manager with Helm:**
|
| 90 |
+
Now, proceed with installing Cert Manager using Helm. The following commands will add the Jetstack Helm repository, update it, and then install Cert Manager with the custom values.yaml configuration file above.
|
| 91 |
+
|
| 92 |
+
```shell
|
| 93 |
+
helm repo add jetstack https://charts.jetstack.io
|
| 94 |
+
helm repo update
|
| 95 |
+
|
| 96 |
+
helm install cert-manager jetstack/cert-manager \
|
| 97 |
+
--values values.yaml \
|
| 98 |
+
-n cert-manager \
|
| 99 |
+
--create-namespace --cleanup-on-fail
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
- **Set Up a ClusterIssuer for Cert Manager:**
|
| 103 |
+
The next step is create a ClusterIssuer resource to define how Cert Manager should obtain SSL certificates. The following template uses the Cloudflare DNS API token stored in the Kubernetes secret created earlier.
|
| 104 |
+
|
| 105 |
+
```yaml
|
| 106 |
+
apiVersion: cert-manager.io/v1
|
| 107 |
+
kind: ClusterIssuer
|
| 108 |
+
metadata:
|
| 109 |
+
name: letsencrypt-prod
|
| 110 |
+
spec:
|
| 111 |
+
acme:
|
| 112 |
+
server: https://acme-v02.api.letsencrypt.org/directory
|
| 113 |
+
# Replace with the administrator email associated with your domain.
|
| 114 |
+
email: "admin@drunk.dev"
|
| 115 |
+
privateKeySecretRef:
|
| 116 |
+
name: letsencrypt-prod
|
| 117 |
+
solvers:
|
| 118 |
+
- dns01:
|
| 119 |
+
cloudflare:
|
| 120 |
+
#Update this accoring to your domain
|
| 121 |
+
email: "admin@drunk.dev"
|
| 122 |
+
# Ensure that the name matches the secret you created (cf-dns-secret),
|
| 123 |
+
# and the key references the correct data key within the secret (token).
|
| 124 |
+
apiTokenSecretRef:
|
| 125 |
+
name: cf-dns-secret
|
| 126 |
+
key: token
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
- **Firewall Whitelisting**
|
| 130 |
+
|
| 131 |
+
Since the AKS cluster’s outbound traffic is managed by a firewall, it’s neededs to whitelist specific external services to ensure that Cert Manager can successfully issue certificates. Without these exceptions, the certificate issuance process will fail.
|
| 132 |
+
|
| 133 |
+
Here’s what needs to allow in the Firewall rules:
|
| 134 |
+
|
| 135 |
+
- Allow outbound access to `api.cloudflare.com` on port `443`.
|
| 136 |
+
- Allow outbound access to `*.api.letsencrypt.org` on port `443`.
|
| 137 |
+
|
| 138 |
+
---
|
| 139 |
+
|
| 140 |
+
## Nginx Ingress Installation
|
| 141 |
+
|
| 142 |
+
Setting up NGINX Ingress in a private AKS environment involves configuring it to use a private IP address and an internal ingress class.
|
| 143 |
+
|
| 144 |
+
1. **Install NGINX Ingress Controller**: To deploy NGINX as an internal Ingress controller with a private IP address, create a values.yaml file with the following configuration.
|
| 145 |
+
|
| 146 |
+
```yaml
|
| 147 |
+
controller:
|
| 148 |
+
hostNetwork: "false"
|
| 149 |
+
useIngressClassOnly: "true"
|
| 150 |
+
watchIngressWithoutClass: "true"
|
| 151 |
+
# the ingress class name is internal
|
| 152 |
+
ingressClass: "internal"
|
| 153 |
+
# The custom ingress class
|
| 154 |
+
ingressClassResource:
|
| 155 |
+
name: "internal"
|
| 156 |
+
enabled: true
|
| 157 |
+
default: true
|
| 158 |
+
controllerValue: k8s.io/ingress-nginx
|
| 159 |
+
service:
|
| 160 |
+
annotations:
|
| 161 |
+
# This annotation to tell Azure to create an internal load balancer.
|
| 162 |
+
service.beta.kubernetes.io/azure-load-balancer-internal: "true"
|
| 163 |
+
externalTrafficPolicy: "Local"
|
| 164 |
+
# update this private IP address accroding to your address spaces.
|
| 165 |
+
loadBalancerIP: "192.168.250.250"
|
| 166 |
+
```
|
| 167 |
+
|
| 168 |
+
**Explanation:**
|
| 169 |
+
|
| 170 |
+
- `hostNetwork`: false ensures that the NGINX pods do not bind directly to the node’s network interfaces, maintaining isolation.
|
| 171 |
+
- `useIngressClassOnly`: Ensures that only Ingress resources with the specified ingressClass will be processed by this controller.
|
| 172 |
+
- `ingressClass`: Named internal to distinguish it from other Ingress classes, ensuring it’s used specifically for internal traffic.
|
| 173 |
+
- `service.annotations`: The key annotation service.beta.kubernetes.io/azure-load-balancer-internal: 'true' tells Azure to create an internal load balancer instead of a public one.
|
| 174 |
+
- `loadBalancerIP`: Assigns a static private IP address (192.168.250.250) to the NGINX load balancer, ensuring it’s accessible only within the internal network.
|
| 175 |
+
Once NGINX is deployed with this configuration, it will only be accessible from within the internal network via the private IP address `192.168.250.250`.
|
| 176 |
+
|
| 177 |
+
**Install Nginx with Helm**
|
| 178 |
+
|
| 179 |
+
```shell
|
| 180 |
+
helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
|
| 181 |
+
helm repo update
|
| 182 |
+
|
| 183 |
+
helm nginx ingress-nginx/ingress-nginx \
|
| 184 |
+
--values values.yaml \
|
| 185 |
+
-n nginx-ingress \
|
| 186 |
+
--create-namespace --cleanup-on-fail
|
| 187 |
+
```
|
| 188 |
+
|
| 189 |
+
2. **Configure DNS for Internal Access**
|
| 190 |
+
|
| 191 |
+
After deploying the NGINX Ingress controller, the next step is to ensure that internal DNS queries resolve to the NGINX private IP. To do this, add an A record in the Azure private DNS zone that created earlier:
|
| 192 |
+
|
| 193 |
+
- **DNS Record**: Add an A record pointing to 192.168.250.250 for the internal domain. This ensures that any internal traffic destined for blogs.drunk.dev is routed to the NGINX Ingress controller.
|
| 194 |
+
<img src="/assets/aks-cert-manager-with-private-aks/az-private-dns.png">
|
| 195 |
+
|
| 196 |
+
3. **Create a Secure Ingress with Dynamic TLS Certificate Generation**
|
| 197 |
+
|
| 198 |
+
Now, it’s time to create a secure Ingress resource that uses dynamic TLS certificate generation.
|
| 199 |
+
|
| 200 |
+
Here’s an example configuration:
|
| 201 |
+
|
| 202 |
+
```yaml
|
| 203 |
+
apiVersion: networking.k8s.io/v1
|
| 204 |
+
kind: Ingress
|
| 205 |
+
metadata:
|
| 206 |
+
name: drunk-blog-apps
|
| 207 |
+
namespace: drunk-apps
|
| 208 |
+
annotations:
|
| 209 |
+
kubernetes.io/tls-acme: "true"
|
| 210 |
+
nginx.ingress.kubernetes.io/backend-protocol: HTTP
|
| 211 |
+
ingress.kubernetes.io/force-ssl-redirect: "true"
|
| 212 |
+
spec:
|
| 213 |
+
# the name of ingress class percificly here.
|
| 214 |
+
ingressClassName: internal
|
| 215 |
+
# The tls config
|
| 216 |
+
tls:
|
| 217 |
+
- hosts:
|
| 218 |
+
- blogs.drunk.dev
|
| 219 |
+
secretName: tls-blogs-lets
|
| 220 |
+
rules:
|
| 221 |
+
# the host config
|
| 222 |
+
- host: blogs.drunk.dev
|
| 223 |
+
http:
|
| 224 |
+
paths:
|
| 225 |
+
- path: /
|
| 226 |
+
pathType: Prefix
|
| 227 |
+
backend:
|
| 228 |
+
service:
|
| 229 |
+
name: blog-apps
|
| 230 |
+
port:
|
| 231 |
+
number: 8080
|
| 232 |
+
```
|
| 233 |
+
|
| 234 |
+
**Key Points:**
|
| 235 |
+
|
| 236 |
+
- `ingressClassName`: Specifies that this Ingress resource should be handled by the internal Ingress class, ensuring it’s routed through the private NGINX controller.
|
| 237 |
+
- `tls`: Configures automatic TLS certificate generation for `blogs.drunk.dev` using Cert Manager. The certificate will be stored in a Kubernetes secret named `tls-blogs-lets`.
|
| 238 |
+
- `annotations`: The force-ssl-redirect: 'true' annotation ensures that all HTTP traffic is redirected to HTTPS, securing the communication.
|
| 239 |
+
|
| 240 |
+
Once the Ingress resource is created, Cert Manager will automatically issue a TLS certificate for `blogs.drunk.dev` and bind it to the Ingress. The certificate will be monitored and automatically renewed by Cert Manager before expiration, ensuring continuous security without manual intervention.
|
| 241 |
+
|
| 242 |
+
---
|
| 243 |
+
|
| 244 |
+
### Conclusion
|
| 245 |
+
|
| 246 |
+
So, that’s how I secured internal communications within my private AKS environment using Cert Manager and Cloudflare DNS management. This approach simplified the management of SSL certificates and provided an extra layer of security for internal data transmissions.
|
| 247 |
+
|
| 248 |
+
I hope you found this walkthrough helpful or at least interesting. If you have any thoughts, questions, or would like to share your own experiences, feel free to reach out. I’m always keen to hear how others are tackling similar challenges!
|
| 249 |
+
|
| 250 |
+
---
|
| 251 |
+
|
| 252 |
+
## Thank You
|
| 253 |
+
|
| 254 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 255 |
+
|
| 256 |
+
**Steven** | *[GitHub](https://github.com/baoduy)*
|
tools-automate-letsencrypt-certification-with-azure-keyvault.md
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-08-26T12:00:00Z
|
| 4 |
+
title: "[Tools] Automating Let's Encrypt Certificate Management with Azure Key Vault and Cloudflare"
|
| 5 |
+
postSlug: tools-automate-letsencrypt-certification-with-azure-keyvault
|
| 6 |
+
featured: false
|
| 7 |
+
draft: false
|
| 8 |
+
tags:
|
| 9 |
+
- azure-key-vault
|
| 10 |
+
- lets-encrypt
|
| 11 |
+
- cloudflare
|
| 12 |
+
- tools
|
| 13 |
+
description: "This post introduces a tool that automates the generation and renewal of Let's Encrypt certificates, importing them into Azure Key Vault.
|
| 14 |
+
It detects certificates nearing expiration and only regenerates those, supporting multiple domains managed via Cloudflare.
|
| 15 |
+
The tool runs as a monthly cron job on AKS, ensuring SSL certificates are always up to date without manual intervention."
|
| 16 |
+
---
|
| 17 |
+
|
| 18 |
+
## Introduction
|
| 19 |
+
|
| 20 |
+
Custom domain names enhance the professionalism and credibility of applications hosted on Azure services.
|
| 21 |
+
However, associating a custom domain requires a trusted SSL/TLS certificate. For **development and sandbox environments**
|
| 22 |
+
used internally by development teams, leveraging **Let's Encrypt** certificates offers a convenient and automated solution.
|
| 23 |
+
Let's Encrypt provides free SSL certificates, but they have a short lifespan of only 90 days, necessitating frequent renewals.
|
| 24 |
+
|
| 25 |
+
To streamline this process, I've developed a tool that automates the generation and renewal of Let's Encrypt certificates specifically for development
|
| 26 |
+
and sandbox environments. The tool detects expiring certificates and renews only those that are nearing expiration, ensuring efficient management.
|
| 27 |
+
The new certificates are securely imported into **Azure Key Vault**, allowing seamless integration with Azure resources such as **Azure API Management**
|
| 28 |
+
and **Azure Front Door**. To eliminate manual intervention entirely, the tool runs as a monthly cron job on **Azure Kubernetes Service (AKS)**.
|
| 29 |
+
|
| 30 |
+
## Why Automate Certificate Management?
|
| 31 |
+
|
| 32 |
+
Manually managing short-lived Let's Encrypt SSL certificates can be time-consuming and error-prone, especially when dealing with multiple domains
|
| 33 |
+
and environments. Automating the certificate management process offers several significant advantages:
|
| 34 |
+
|
| 35 |
+
- **Cost Savings for Development and Sandbox Environments**: Let's Encrypt provides a free alternative to paid certificates,
|
| 36 |
+
making it ideal for non-production environments where cost optimization is important.
|
| 37 |
+
|
| 38 |
+
- **Elimination of Certificate Expiration Concerns**: The tool proactively identifies and renews certificates nearing expiration,
|
| 39 |
+
ensuring your services remain secure without requiring manual intervention.
|
| 40 |
+
|
| 41 |
+
- **Simplified Management of Multiple Domains**: With built-in support for handling multiple domains via **Cloudflare**,
|
| 42 |
+
the tool streamlines the process of managing DNS challenges required for certificate validation.
|
| 43 |
+
|
| 44 |
+
- **Secure Integration with Azure Key Vault**: Automatically importing generated certificates into Azure Key Vault provides a secure
|
| 45 |
+
and centralized storage solution, enhancing overall security and simplifying certificate management across your Azure resources.
|
| 46 |
+
|
| 47 |
+
## How It Works
|
| 48 |
+
|
| 49 |
+
The tool automates SSL certificate management by running as a **monthly cron job** on AKS. It handles the entire lifecycle of SSL certificates, from detection of impending expiration to deployment of new certificates. The workflow is as follows:
|
| 50 |
+
|
| 51 |
+
1. **Check Certificate Expiration**: The tool scans all certificates stored in Azure Key Vault to determine their expiration dates.
|
| 52 |
+
|
| 53 |
+
2. **Generate New Certificates**: For certificates nearing expiration, the tool requests new SSL certificates from **Let's Encrypt**.
|
| 54 |
+
|
| 55 |
+
3. **DNS Challenge via Cloudflare**: The tool integrates with **Cloudflare** to perform DNS challenges required by Let's Encrypt to validate domain ownership.
|
| 56 |
+
|
| 57 |
+
4. **Import Certificates to Azure Key Vault**: The newly obtained certificates are securely imported into **Azure Key Vault**, replacing the old certificates.
|
| 58 |
+
|
| 59 |
+
5. **Automated Monthly Execution**: The tool is scheduled to run monthly on AKS, ensuring that certificates are kept up-to-date with minimal manual effort.
|
| 60 |
+
|
| 61 |
+
## Setting Up Cloudflare DNS API Token
|
| 62 |
+
|
| 63 |
+
To enable the tool to perform DNS challenges for domain validation, you need to create a Cloudflare API token with permissions to manage DNS records.
|
| 64 |
+
|
| 65 |
+
1. **Create an API Token**:
|
| 66 |
+
|
| 67 |
+
- Log in to your Cloudflare account and navigate to your profile.
|
| 68 |
+
- Go to the **API Tokens** section or directly via [this link](https://dash.cloudflare.com/profile/api-tokens).
|
| 69 |
+
- Click on **"Create Token"**.
|
| 70 |
+
|
| 71 |
+
2. **Configure Token Permissions**:
|
| 72 |
+
|
| 73 |
+
- **Permissions**: Grant **Zone** > **DNS** > **Edit** permissions.
|
| 74 |
+
- **Zone Resources**: Select **Specific Zone** and choose the domain(s) you want to manage.
|
| 75 |
+
|
| 76 |
+
3. **Client IP Address Filtering (Optional but Recommended)**:
|
| 77 |
+
|
| 78 |
+
- For enhanced security, specify the AKS cluster's public IP address under **"Client IP Address Filtering"** in the token settings.
|
| 79 |
+
- This restricts API token usage to requests originating from your AKS cluster, preventing unauthorized access.
|
| 80 |
+
|
| 81 |
+
4. **Save the Token**:
|
| 82 |
+
|
| 83 |
+
- Generate the token and copy it. You'll need it for the tool's configuration.
|
| 84 |
+
|
| 85 |
+

|
| 86 |
+
|
| 87 |
+
## Configuration
|
| 88 |
+
|
| 89 |
+
The tool is configured using environment variables or a JSON configuration file. Here's an example `appsettings.json` file:
|
| 90 |
+
|
| 91 |
+
```json
|
| 92 |
+
{
|
| 93 |
+
"CertManager": {
|
| 94 |
+
"ProductionEnabled": true,
|
| 95 |
+
"CfEmail": "your-cloudflare-email@example.com",
|
| 96 |
+
"CfToken": "YOUR_CLOUDFLARE_API_TOKEN",
|
| 97 |
+
"ZoneId": "YOUR_CLOUDFLARE_ZONE_ID",
|
| 98 |
+
"LetsEncryptEmail": "your-email@example.com",
|
| 99 |
+
"Domains": ["api.example.com", "*.example.com"],
|
| 100 |
+
"CertInfo": {
|
| 101 |
+
"CountryName": "SG",
|
| 102 |
+
"State": "Singapore",
|
| 103 |
+
"Locality": "Singapore",
|
| 104 |
+
"Organization": "YourOrganization",
|
| 105 |
+
"OrganizationUnit": "YourUnit"
|
| 106 |
+
},
|
| 107 |
+
"KeyVaultUrl": "https://your-keyvault-name.vault.azure.net/",
|
| 108 |
+
"KeyVaultUID": "OPTIONAL_USER_ASSIGNED_IDENTITY_CLIENT_ID"
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
**Configuration Parameters Explained**:
|
| 114 |
+
|
| 115 |
+
- **ProductionEnabled**: Set to `true` to use Let's Encrypt production environment. Set to `false` for testing purposes.
|
| 116 |
+
|
| 117 |
+
- **CfEmail**: Your Cloudflare account email address.
|
| 118 |
+
|
| 119 |
+
- **CfToken**: The Cloudflare API token created earlier.
|
| 120 |
+
|
| 121 |
+
- **ZoneId**: The ID of your Cloudflare DNS zone. You can find this in your Cloudflare dashboard under the domain's **Overview** section.
|
| 122 |
+
|
| 123 |
+
- **LetsEncryptEmail**: An email address for Let's Encrypt notifications.
|
| 124 |
+
|
| 125 |
+
- **Domains**: An array of domains and subdomains for which you want to generate certificates.
|
| 126 |
+
|
| 127 |
+
- **CertInfo**: Certificate subject information.
|
| 128 |
+
|
| 129 |
+
- **KeyVaultUrl**: The URL of your Azure Key Vault where certificates will be stored.
|
| 130 |
+
|
| 131 |
+
- **KeyVaultUID**: The Client ID of the User Assigned Managed Identity (UAMI) used by your AKS cluster (optional if using the default identity).
|
| 132 |
+
|
| 133 |
+
## Deploying to AKS
|
| 134 |
+
|
| 135 |
+
### Prerequisites
|
| 136 |
+
|
| 137 |
+
- An AKS cluster where the tool will run.
|
| 138 |
+
|
| 139 |
+
- The AKS cluster's agent pool has a User Assigned Managed Identity (UAMI) for Azure resource authentication.
|
| 140 |
+
|
| 141 |
+
- Access to the Azure Key Vault where certificates will be stored.
|
| 142 |
+
|
| 143 |
+
### Granting Key Vault Access to AKS UAMI
|
| 144 |
+
|
| 145 |
+
Before deploying the tool, you need to grant your AKS cluster's UAMI the necessary permissions to access Azure Key Vault:
|
| 146 |
+
|
| 147 |
+
1. **Identify the AKS Agent Pool UAMI**:
|
| 148 |
+
|
| 149 |
+
- In the Azure portal, navigate to your AKS cluster.
|
| 150 |
+
- Under **Settings**, select **Identity**.
|
| 151 |
+
- Note the **Client ID** of the **User Assigned** identity associated with your node pools.
|
| 152 |
+
|
| 153 |
+

|
| 154 |
+
|
| 155 |
+
2. **Grant Key Vault Permissions**:
|
| 156 |
+
|
| 157 |
+
- Navigate to your Azure Key Vault.
|
| 158 |
+
- Select **Access control (IAM)**.
|
| 159 |
+
- Click on **"Add role assignment"**.
|
| 160 |
+
- In the **Role** dropdown, select **"Key Vault Certificates Officer"**.
|
| 161 |
+
- Click **Next** and select the AKS UAMI as the **Member**.
|
| 162 |
+
- Review and assign the role.
|
| 163 |
+
|
| 164 |
+
By granting the **Key Vault Certificates Officer** role to your AKS UAMI, you allow the tool running on AKS to manage certificates within the Key Vault.
|
| 165 |
+
|
| 166 |
+
### Deploying the Tool Using Helm
|
| 167 |
+
|
| 168 |
+
Assuming you are using Helm for deployment, you can update your Helm chart values file with the necessary configurations.
|
| 169 |
+
|
| 170 |
+
Here's an example `values.yaml` file:
|
| 171 |
+
|
| 172 |
+
```yaml
|
| 173 |
+
services:
|
| 174 |
+
cert-renewal:
|
| 175 |
+
image: baoduy2412/keyvault-letsencrypt:latest
|
| 176 |
+
environment:
|
| 177 |
+
CertManager__ProductionEnabled: "true"
|
| 178 |
+
CertManager__CfEmail: "your-cloudflare-email@example.com"
|
| 179 |
+
CertManager__CfToken: "YOUR_CLOUDFLARE_API_TOKEN"
|
| 180 |
+
CertManager__ZoneId: "YOUR_CLOUDFLARE_ZONE_ID"
|
| 181 |
+
CertManager__LetsEncryptEmail: "your-email@example.com"
|
| 182 |
+
CertManager__Domains__0: "api.example.com"
|
| 183 |
+
CertManager__Domains__1: "*.example.com"
|
| 184 |
+
CertManager__CertInfo__CountryName: "SG"
|
| 185 |
+
CertManager__CertInfo__State: "Singapore"
|
| 186 |
+
CertManager__CertInfo__Locality: "Singapore"
|
| 187 |
+
CertManager__CertInfo__Organization: "YourOrganization"
|
| 188 |
+
CertManager__CertInfo__OrganizationUnit: "YourUnit"
|
| 189 |
+
CertManager__KeyVaultUrl: "https://your-keyvault-name.vault.azure.net/"
|
| 190 |
+
CertManager__KeyVaultUID: "OPTIONAL_USER_ASSIGNED_IDENTITY_CLIENT_ID"
|
| 191 |
+
schedule: "0 0 1 * *" # Runs on the 1st of every month at midnight
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
**Notes**:
|
| 195 |
+
|
| 196 |
+
- **Image**: Ensure you're using the correct Docker image.
|
| 197 |
+
|
| 198 |
+
- **Environment Variables**: Update all placeholders with your actual configuration values.
|
| 199 |
+
|
| 200 |
+
- **Schedule**: The cron expression `"0 0 1 * *"` schedules the job to run at midnight on the first day of every month.
|
| 201 |
+
|
| 202 |
+
### Deploying the Helm Chart
|
| 203 |
+
|
| 204 |
+
1. **Update Helm Repositories**:
|
| 205 |
+
|
| 206 |
+
```bash
|
| 207 |
+
helm repo update
|
| 208 |
+
```
|
| 209 |
+
|
| 210 |
+
2. **Deploy or Upgrade the Chart**:
|
| 211 |
+
|
| 212 |
+
```bash
|
| 213 |
+
helm upgrade --install cert-renewal ./path-to-your-chart -f values.yaml
|
| 214 |
+
```
|
| 215 |
+
|
| 216 |
+
Replace `./path-to-your-chart` with the path to your Helm chart.
|
| 217 |
+
|
| 218 |
+
## Conclusion
|
| 219 |
+
|
| 220 |
+
Managing SSL certificates for Azure resources with custom domains can be challenging due to the frequent renewal requirements of Let's Encrypt certificates. This tool automates the entire process of certificate generation, validation, and deployment, significantly simplifying SSL certificate management for development and sandbox environments.
|
| 221 |
+
|
| 222 |
+
By running as a monthly cron job on AKS, it ensures that your certificates are always up-to-date without manual intervention. The integration with Azure Key Vault enhances security by providing centralized and secure storage of your certificates, which can be accessed by other Azure services as needed.
|
| 223 |
+
|
| 224 |
+
**Leveraging Infrastructure as Code for Deployment**
|
| 225 |
+
|
| 226 |
+
Once the certificates are stored in Azure Key Vault, you can further automate the deployment process by using infrastructure as code (IaC) tools like Pulumi or Terraform.
|
| 227 |
+
These tools can retrieve the certificates from Key Vault and deploy them to your Azure resources automatically.
|
| 228 |
+
By incorporating this into your IaC pipelines, you ensure that any updates to the certificates are seamlessly propagated to services like Azure API Management, Azure Front Door, or Azure Application Gateway, maintaining consistent and secure configurations across your infrastructure.
|
| 229 |
+
|
| 230 |
+
**Key Benefits**:
|
| 231 |
+
|
| 232 |
+
- **Automated Renewal**: Eliminates the manual effort required to renew Let's Encrypt certificates every 90 days.
|
| 233 |
+
|
| 234 |
+
- **Cost Efficiency**: Uses free Let's Encrypt certificates, reducing costs for non-production environments.
|
| 235 |
+
|
| 236 |
+
- **Scalability**: Easily manages multiple domains and environments.
|
| 237 |
+
|
| 238 |
+
- **Security**: Securely stores certificates in Azure Key Vault and restricts Cloudflare API access to your AKS cluster.
|
| 239 |
+
|
| 240 |
+
Give it a try and simplify your SSL certificate management process!
|
| 241 |
+
|
| 242 |
+
---
|
| 243 |
+
|
| 244 |
+
**Resources**:
|
| 245 |
+
|
| 246 |
+
- **GitHub Repository**: [az-keyvault-letsencrypt](https://github.com/baoduy/az-keyvault-letsencrypt)
|
| 247 |
+
- **Docker Image**: [baoduy2412/keyvault-letsencrypt](https://hub.docker.com/r/baoduy2412/keyvault-letsencrypt)
|
| 248 |
+
|
| 249 |
+
---
|
| 250 |
+
|
| 251 |
+
## Thank You
|
| 252 |
+
|
| 253 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 254 |
+
|
| 255 |
+
**Steven** | *[GitHub](https://github.com/baoduy)*
|
tools-az-scan-and-disable-entra-accounts.md
ADDED
|
@@ -0,0 +1,497 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ra-accounts
|
| 6 |
+
featured: false
|
| 7 |
+
draft: false
|
| 8 |
+
tags:
|
| 9 |
+
- Azure
|
| 10 |
+
- EntraID
|
| 11 |
+
- Disable Account
|
| 12 |
+
ogImage: ""
|
| 13 |
+
description:
|
| 14 |
+
Inactive accounts in Azure EntraID can pose significant security risks.
|
| 15 |
+
This post discusses the importance of implementing a housekeeping strategy and introduces a streamlined approach using Azure DevOps.
|
| 16 |
+
---
|
| 17 |
+
|
| 18 |
+
## Introduction
|
| 19 |
+
|
| 20 |
+
As organizations grow, so does the number of user accounts within their systems. Managing these accounts efficiently is crucial for maintaining security and compliance. In particular, inactive accounts in **Azure Entra ID** (formerly known as Azure Active Directory) can pose significant security risks. These dormant accounts are potential entry points for malicious actors seeking unauthorized access to sensitive data.
|
| 21 |
+
|
| 22 |
+
In this comprehensive guide, we'll walk through how to automate the management of inactive Azure Entra ID accounts using a TypeScript application. We'll cover everything from setting up an Azure Entra ID application, implementing the TypeScript program, to scheduling the script using Azure DevOps for regular execution.
|
| 23 |
+
|
| 24 |
+
## Table of Contents
|
| 25 |
+
|
| 26 |
+
1. [Understanding the Risks of Inactive Accounts](#1-understanding-the-risks-of-inactive-accounts)
|
| 27 |
+
2. [Creating an Azure Entra ID Application](#2-creating-an-azure-entra-id-application)
|
| 28 |
+
3. [Implementing the TypeScript Program](#3-implementing-the-typescript-program)
|
| 29 |
+
4. [Scheduling the Script with Azure DevOps](#4-scheduling-the-script-with-azure-devops)
|
| 30 |
+
5. [Conclusion](#5-conclusion)
|
| 31 |
+
|
| 32 |
+
---
|
| 33 |
+
|
| 34 |
+
## 1. Understanding the Risks of Inactive Accounts
|
| 35 |
+
|
| 36 |
+
Inactive accounts are user accounts that haven't been used for a significant period. They can accumulate due to employee turnover, role changes, or users simply forgetting about them. These accounts are risky because:
|
| 37 |
+
|
| 38 |
+
- **Security Vulnerabilities**: They might have weak or outdated passwords, making them easy targets.
|
| 39 |
+
- **Unauthorized Access**: If compromised, they can provide unauthorized access to internal systems and data.
|
| 40 |
+
- **Compliance Issues**: Regulations often require the timely removal or deactivation of unused accounts.
|
| 41 |
+
|
| 42 |
+
Regularly auditing and managing these accounts helps mitigate these risks and ensures compliance with security best practices.
|
| 43 |
+
|
| 44 |
+
---
|
| 45 |
+
|
| 46 |
+
## 2. Creating an Azure Entra ID Application
|
| 47 |
+
|
| 48 |
+
To interact with Azure Entra ID programmatically, we'll create an **App Registration**.
|
| 49 |
+
This application will authenticate and manage user accounts via the Microsoft Graph API.
|
| 50 |
+
|
| 51 |
+
### Steps to Create an App Registration
|
| 52 |
+
|
| 53 |
+
#### 1. Navigate to Azure Entra ID
|
| 54 |
+
|
| 55 |
+
- Log in to the [Azure portal](https://portal.azure.com).
|
| 56 |
+
- In the left-hand navigation pane, select **Azure Entra ID**.
|
| 57 |
+
|
| 58 |
+
#### 2. Create a New App Registration
|
| 59 |
+
|
| 60 |
+
- Click on **"App registrations"** in the sidebar.
|
| 61 |
+
- Click on **"New registration"** at the top.
|
| 62 |
+
|
| 63 |
+

|
| 64 |
+
|
| 65 |
+
#### 3. Configure the App Registration
|
| 66 |
+
|
| 67 |
+
- **Name**: Enter a meaningful name, e.g., `Azure-EntraID-Management` app.
|
| 68 |
+
- **Supported account types**: Choose **"Accounts in this organizational directory only (Single tenant)"**.
|
| 69 |
+
- **Redirect URI**: This is not required for our application, so you can leave it blank.
|
| 70 |
+
- Click **"Register"** to create the app.
|
| 71 |
+
|
| 72 |
+
### Adding API Permissions
|
| 73 |
+
|
| 74 |
+
After creating the app registration, we need to grant it permissions to access the Microsoft Graph API.
|
| 75 |
+
|
| 76 |
+
#### 1. Navigate to API Permissions
|
| 77 |
+
|
| 78 |
+
- In the app registration's overview page, click on **"API permissions"** in the sidebar.
|
| 79 |
+
|
| 80 |
+
#### 2. Add Permissions
|
| 81 |
+
|
| 82 |
+
- Click on **"Add a permission"**.
|
| 83 |
+
- Select **"Microsoft Graph"**.
|
| 84 |
+
- Choose **"Application permissions"** since this app will run as a background service or daemon.
|
| 85 |
+
|
| 86 |
+
#### 3. Select Required Permissions
|
| 87 |
+
|
| 88 |
+
Search for and select the following permissions:
|
| 89 |
+
|
| 90 |
+
- **`AuditLog.Read.All`**: Allows the app to read all audit log data.
|
| 91 |
+
- **`User.Read.All`**: Allows the app to read user profiles.
|
| 92 |
+
- **`User.ReadWrite.All`**: Allows the app to read and write user profiles.
|
| 93 |
+
|
| 94 |
+

|
| 95 |
+
|
| 96 |
+
> **Note**: The **`User.ReadWrite.All`** permission is required to enable or disable user accounts.
|
| 97 |
+
|
| 98 |
+
#### 4. Grant Admin Consent
|
| 99 |
+
|
| 100 |
+
- After adding the permissions, click on **"Grant admin consent for [Your Tenant Name]"**.
|
| 101 |
+
- Confirm by clicking **"Yes"** in the prompt.
|
| 102 |
+
|
| 103 |
+
#### 5. Create a Client Secret
|
| 104 |
+
|
| 105 |
+
- Navigate to **"Certificates & secrets"**.
|
| 106 |
+
- Click on **"New client secret"**.
|
| 107 |
+
- Provide a description and set an expiration period.
|
| 108 |
+
- Click **"Add"**.
|
| 109 |
+
- Copy the **Value** of the client secret and store it securely. You won't be able to view it again.
|
| 110 |
+
|
| 111 |
+
### Collect Necessary Information
|
| 112 |
+
|
| 113 |
+
You'll need the following information for your application:
|
| 114 |
+
|
| 115 |
+
- **Tenant ID**: Found in **Azure Entra ID** > **Properties**.
|
| 116 |
+
- **Client ID**: Found in your app registration's **Overview** page.
|
| 117 |
+
- **Client Secret**: The value you just created.
|
| 118 |
+
|
| 119 |
+
---
|
| 120 |
+
|
| 121 |
+
## 3. Implementing the TypeScript Program
|
| 122 |
+
|
| 123 |
+
We'll create a TypeScript program that:
|
| 124 |
+
|
| 125 |
+
- Authenticates with Azure Entra ID using the app registration.
|
| 126 |
+
- Retrieves inactive user accounts based on their last sign-in date.
|
| 127 |
+
- Disables these inactive accounts.
|
| 128 |
+
- Generates a report of all disabled accounts.
|
| 129 |
+
|
| 130 |
+
### Setting Up the Project
|
| 131 |
+
|
| 132 |
+
#### 1. Initialize the Project
|
| 133 |
+
|
| 134 |
+
Create a new directory for your project and initialize npm:
|
| 135 |
+
|
| 136 |
+
```bash
|
| 137 |
+
mkdir azure-entra-id-management
|
| 138 |
+
cd azure-entra-id-management
|
| 139 |
+
npm init -y
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
#### 2. Install Dependencies
|
| 143 |
+
|
| 144 |
+
Install the required packages:
|
| 145 |
+
|
| 146 |
+
```bash
|
| 147 |
+
npm install @azure/identity @microsoft/microsoft-graph-client dayjs
|
| 148 |
+
npm install --save-dev typescript ts-node
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
- **`@azure/identity`**: Provides Azure authentication methods.
|
| 152 |
+
- **`@microsoft/microsoft-graph-client`**: Allows interaction with Microsoft Graph API.
|
| 153 |
+
- **`dayjs`**: A lightweight library for date manipulation.
|
| 154 |
+
- **`typescript`** and **`ts-node`**: Required for compiling and running TypeScript code.
|
| 155 |
+
|
| 156 |
+
#### 3. Configure TypeScript
|
| 157 |
+
|
| 158 |
+
Create a `tsconfig.json` file:
|
| 159 |
+
|
| 160 |
+
```json
|
| 161 |
+
{
|
| 162 |
+
"compilerOptions": {
|
| 163 |
+
"module": "commonjs",
|
| 164 |
+
"esModuleInterop": true,
|
| 165 |
+
"target": "es6",
|
| 166 |
+
"moduleResolution": "node",
|
| 167 |
+
"sourceMap": true,
|
| 168 |
+
"outDir": "dist"
|
| 169 |
+
},
|
| 170 |
+
"lib": ["es2015"],
|
| 171 |
+
"files": ["index.ts"]
|
| 172 |
+
}
|
| 173 |
+
```
|
| 174 |
+
|
| 175 |
+
### Writing Code
|
| 176 |
+
|
| 177 |
+
#### 1. Create the Source File and Import Required Modules
|
| 178 |
+
|
| 179 |
+
At the top of `index.ts`, import the necessary modules:
|
| 180 |
+
|
| 181 |
+
```typescript
|
| 182 |
+
import { DefaultAzureCredential } from "@azure/identity";
|
| 183 |
+
import { Client } from "@microsoft/microsoft-graph-client";
|
| 184 |
+
import { TokenCredentialAuthenticationProvider } from "@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials";
|
| 185 |
+
import dayjs from "dayjs";
|
| 186 |
+
```
|
| 187 |
+
|
| 188 |
+
> **Note**: The `isomorphic-fetch` import is necessary for environments where `fetch` is not available globally.
|
| 189 |
+
|
| 190 |
+
#### 2. Set Configuration Variables
|
| 191 |
+
|
| 192 |
+
Define the configuration variables and excluded accounts:
|
| 193 |
+
|
| 194 |
+
```typescript
|
| 195 |
+
// Configuration
|
| 196 |
+
const INACTIVITY_THRESHOLD_MONTHS = 2; // Adjust as needed
|
| 197 |
+
const EXCLUDED_ACCOUNTS = ["admin@example.com", "serviceaccount@example.com"];
|
| 198 |
+
|
| 199 |
+
// Azure AD App Credentials - Replace with your actual credentials or use environment variables
|
| 200 |
+
const TENANT_ID = process.env.AZURE_TENANT_ID;
|
| 201 |
+
const CLIENT_ID = process.env.AZURE_CLIENT_ID;
|
| 202 |
+
const CLIENT_SECRET = process.env.AZURE_CLIENT_SECRET;
|
| 203 |
+
```
|
| 204 |
+
|
| 205 |
+
> **Security Tip**: Never hard-code credentials. Use environment variables or secure credential management.
|
| 206 |
+
|
| 207 |
+
#### 3. Set Up Authentication and Client
|
| 208 |
+
|
| 209 |
+
Create a `ClientSecretCredential` and initialize the Microsoft Graph client:
|
| 210 |
+
|
| 211 |
+
```typescript
|
| 212 |
+
if (!TENANT_ID || !CLIENT_ID || !CLIENT_SECRET) {
|
| 213 |
+
throw new Error(
|
| 214 |
+
"Please ensure AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET are set."
|
| 215 |
+
);
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
/** 1. Setup Credentials and Microsoft Graph client */
|
| 219 |
+
const client = Client.initWithMiddleware({
|
| 220 |
+
debugLogging: false,
|
| 221 |
+
authProvider: new TokenCredentialAuthenticationProvider(
|
| 222 |
+
// This DefaultAzureCredential will detect the credentials from environment variables above automatically.
|
| 223 |
+
new DefaultAzureCredential(),
|
| 224 |
+
{
|
| 225 |
+
scopes: ["https://graph.microsoft.com/.default"],
|
| 226 |
+
}
|
| 227 |
+
),
|
| 228 |
+
});
|
| 229 |
+
```
|
| 230 |
+
|
| 231 |
+
#### 4. Define Types
|
| 232 |
+
|
| 233 |
+
Define types for the Azure AD user and result:
|
| 234 |
+
|
| 235 |
+
```typescript
|
| 236 |
+
type AzResult<T> = { value: Array<T> };
|
| 237 |
+
type AdUser = {
|
| 238 |
+
userPrincipalName: string;
|
| 239 |
+
id: string;
|
| 240 |
+
accountEnabled: boolean;
|
| 241 |
+
};
|
| 242 |
+
```
|
| 243 |
+
|
| 244 |
+
#### 5. Implement Functions
|
| 245 |
+
|
| 246 |
+
##### a. Retrieve Inactive Accounts
|
| 247 |
+
|
| 248 |
+
```typescript
|
| 249 |
+
async function getInactiveAccounts(cutoffDate: Dayjs): Promise<AdUser[]> {
|
| 250 |
+
/** Query all the accounts that has signInActivity date before the expected parameter date */
|
| 251 |
+
const accounts = (await client
|
| 252 |
+
.api("/users/")
|
| 253 |
+
.filter(`signInActivity/lastSignInDateTime lt ${cutoffDate.toISOString()}`)
|
| 254 |
+
.select("id,userPrincipalName,accountEnabled")
|
| 255 |
+
.get()) as AzResult<AdUser>;
|
| 256 |
+
|
| 257 |
+
/** Filter the enabled account only here
|
| 258 |
+
* as the API filter has limitation that not allows to query based on both signInActivity and accountEnabled */
|
| 259 |
+
return accounts.value.filter(m => m.accountEnabled);
|
| 260 |
+
}
|
| 261 |
+
```
|
| 262 |
+
|
| 263 |
+
> **Note**: The Microsoft Graph API may paginate results. The loop ensures all pages are retrieved.
|
| 264 |
+
|
| 265 |
+
##### b. Disable Accounts
|
| 266 |
+
|
| 267 |
+
```typescript
|
| 268 |
+
async function disableAccounts(users: AdUser[]): Promise<void> {
|
| 269 |
+
return await Promise.all(
|
| 270 |
+
accounts.map(async u => {
|
| 271 |
+
/* Check and keep the account if found in the excludedAccounts */
|
| 272 |
+
if (
|
| 273 |
+
EXCLUDED_ACCOUNTS.find(a =>
|
| 274 |
+
u.userPrincipalName.toLowerCase().includes(a.toLowerCase())
|
| 275 |
+
)
|
| 276 |
+
) {
|
| 277 |
+
console.log(
|
| 278 |
+
`User account ${u.userPrincipalName} has been excluded from disabling.`
|
| 279 |
+
);
|
| 280 |
+
return;
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
// Perform the account disabling
|
| 284 |
+
await client.api(`/users/${u.id}`).update({
|
| 285 |
+
accountEnabled: false,
|
| 286 |
+
});
|
| 287 |
+
|
| 288 |
+
console.log(
|
| 289 |
+
`User account with ID ${u.userPrincipalName} has been disabled.`
|
| 290 |
+
);
|
| 291 |
+
})
|
| 292 |
+
);
|
| 293 |
+
}
|
| 294 |
+
```
|
| 295 |
+
|
| 296 |
+
##### c. Retrieve Disabled Accounts
|
| 297 |
+
|
| 298 |
+
```typescript
|
| 299 |
+
async function getDisabledAccounts(): Promise<AdUser[]> {
|
| 300 |
+
/** Query all the accounts that has accountEnabled is false */
|
| 301 |
+
const rs = (await client
|
| 302 |
+
.api("/users/")
|
| 303 |
+
.filter(`accountEnabled eq false`)
|
| 304 |
+
.select("id,userPrincipalName,accountEnabled")
|
| 305 |
+
.get()) as AzResult<AdUser>;
|
| 306 |
+
|
| 307 |
+
return rs.value;
|
| 308 |
+
}
|
| 309 |
+
```
|
| 310 |
+
|
| 311 |
+
##### d. Print Accounts
|
| 312 |
+
|
| 313 |
+
```typescript
|
| 314 |
+
function printAccounts(message: string, accounts: AdUser[]): void {
|
| 315 |
+
console.log(message);
|
| 316 |
+
accounts.forEach((user, index) => {
|
| 317 |
+
console.log(
|
| 318 |
+
`${index + 1}. ${user.userPrincipalName} (Enabled: ${user.accountEnabled})`
|
| 319 |
+
);
|
| 320 |
+
});
|
| 321 |
+
}
|
| 322 |
+
```
|
| 323 |
+
|
| 324 |
+
#### 6. Main Execution Function
|
| 325 |
+
|
| 326 |
+
Finally, create the main function to orchestrate the process:
|
| 327 |
+
|
| 328 |
+
```typescript
|
| 329 |
+
(async () => {
|
| 330 |
+
try {
|
| 331 |
+
//1. Scanning account that inactive for more than 2 months
|
| 332 |
+
const cutoffDate = dayjs().subtract(INACTIVITY_THRESHOLD_MONTHS, "month");
|
| 333 |
+
console.log(
|
| 334 |
+
`Scanning for accounts inactive since before ${cutoffDate.format("YYYY-MM-DD")}...\n`
|
| 335 |
+
);
|
| 336 |
+
|
| 337 |
+
// Retrieve inactive accounts
|
| 338 |
+
const inactiveAccounts = await getInactiveAccounts(cutoffDate);
|
| 339 |
+
printAccounts(
|
| 340 |
+
`Found ${inactiveAccounts.length} inactive account(s):`,
|
| 341 |
+
inactiveAccounts
|
| 342 |
+
);
|
| 343 |
+
|
| 344 |
+
// Disable inactive accounts
|
| 345 |
+
if (inactiveAccounts.length > 0) {
|
| 346 |
+
await disableAccounts(inactiveAccounts);
|
| 347 |
+
} else {
|
| 348 |
+
console.log("No inactive accounts to disable.");
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
// Retrieve and print disabled accounts
|
| 352 |
+
const disabledAccounts = await getDisabledAccounts();
|
| 353 |
+
printAccounts(`\nCurrently disabled accounts:`, disabledAccounts);
|
| 354 |
+
} catch (error) {
|
| 355 |
+
console.error("An error occurred:", error);
|
| 356 |
+
}
|
| 357 |
+
})();
|
| 358 |
+
```
|
| 359 |
+
|
| 360 |
+
#### 7. Running the Program
|
| 361 |
+
|
| 362 |
+
Ensure the environment variables are set:
|
| 363 |
+
|
| 364 |
+
```bash
|
| 365 |
+
export AZURE_TENANT_ID=your_tenant_id
|
| 366 |
+
export AZURE_CLIENT_ID=your_client_id
|
| 367 |
+
export AZURE_CLIENT_SECRET=your_client_secret
|
| 368 |
+
```
|
| 369 |
+
|
| 370 |
+
Compile and run the program:
|
| 371 |
+
|
| 372 |
+
```bash
|
| 373 |
+
npx ts-node src/index.ts
|
| 374 |
+
```
|
| 375 |
+
|
| 376 |
+
---
|
| 377 |
+
|
| 378 |
+
## 4. Scheduling the Script with Azure DevOps
|
| 379 |
+
|
| 380 |
+
To automate the execution of the script, we'll use Azure DevOps to schedule it as part of a pipeline.
|
| 381 |
+
|
| 382 |
+
### Steps to Schedule the Script
|
| 383 |
+
|
| 384 |
+
#### 1. Commit the Code to a Repository
|
| 385 |
+
|
| 386 |
+
- Create a Git repository in Azure DevOps.
|
| 387 |
+
- Commit all your code, including the `package.json`, `tsconfig.json`, and `src` directory.
|
| 388 |
+
|
| 389 |
+
#### 2. Create a Variable Group
|
| 390 |
+
|
| 391 |
+
Navigate to **Pipelines** > **Library** in Azure DevOps.
|
| 392 |
+
|
| 393 |
+
- Click **"Variable groups"** and then **"Add variable group"**.
|
| 394 |
+
- Name the variable group, e.g., `AzureEntraIDCredentials`.
|
| 395 |
+
- Add the following variables:
|
| 396 |
+
- `AZURE_TENANT_ID`
|
| 397 |
+
- `AZURE_CLIENT_ID`
|
| 398 |
+
- `AZURE_CLIENT_SECRET`
|
| 399 |
+
- For each variable, enter the corresponding value and mark it as **secret**.
|
| 400 |
+
- Save the variable group.
|
| 401 |
+
|
| 402 |
+

|
| 403 |
+
|
| 404 |
+
#### 3. Create the Pipeline
|
| 405 |
+
|
| 406 |
+
In **Pipelines**, click **"Create Pipeline"** and follow the prompts to set up a YAML pipeline.
|
| 407 |
+
|
| 408 |
+
##### a. Define the YAML Pipeline
|
| 409 |
+
|
| 410 |
+
Create a `azure-pipelines.yml` file in your repository with the following content:
|
| 411 |
+
|
| 412 |
+
```yaml
|
| 413 |
+
trigger: none
|
| 414 |
+
|
| 415 |
+
schedules:
|
| 416 |
+
- cron: "0 0 * * 0" # Runs at midnight every Sunday
|
| 417 |
+
displayName: "Weekly Sunday Run"
|
| 418 |
+
branches:
|
| 419 |
+
include:
|
| 420 |
+
- main
|
| 421 |
+
always: true
|
| 422 |
+
batch: false
|
| 423 |
+
|
| 424 |
+
pool:
|
| 425 |
+
vmImage: "ubuntu-latest"
|
| 426 |
+
|
| 427 |
+
variables:
|
| 428 |
+
- group: AzureEntraIDCredentials
|
| 429 |
+
|
| 430 |
+
steps:
|
| 431 |
+
- task: NodeTool@0
|
| 432 |
+
inputs:
|
| 433 |
+
versionSpec: "14.x" # Adjust Node.js version as needed
|
| 434 |
+
displayName: "Install Node.js"
|
| 435 |
+
|
| 436 |
+
- script: |
|
| 437 |
+
npm ci
|
| 438 |
+
npx ts-node src/index.ts
|
| 439 |
+
displayName: "Install dependencies and run script"
|
| 440 |
+
env:
|
| 441 |
+
AZURE_TENANT_ID: $(AZURE_TENANT_ID)
|
| 442 |
+
AZURE_CLIENT_ID: $(AZURE_CLIENT_ID)
|
| 443 |
+
AZURE_CLIENT_SECRET: $(AZURE_CLIENT_SECRET)
|
| 444 |
+
```
|
| 445 |
+
|
| 446 |
+
##### b. Pipeline Explanation
|
| 447 |
+
|
| 448 |
+
- **Trigger**: Set to `none` to prevent automatic builds on code changes.
|
| 449 |
+
- **Schedules**: Configured to run every Sunday at midnight.
|
| 450 |
+
- **Pool**: Uses the latest Ubuntu VM image.
|
| 451 |
+
- **Variables**: Includes the variable group with your credentials.
|
| 452 |
+
- **Steps**:
|
| 453 |
+
- **NodeTool**: Ensures Node.js is available on the agent.
|
| 454 |
+
- **Script**: Installs dependencies and runs the script.
|
| 455 |
+
|
| 456 |
+
#### 4. Run and Monitor the Pipeline
|
| 457 |
+
|
| 458 |
+
- Save and run the pipeline manually to test it.
|
| 459 |
+
- Monitor the pipeline's execution in the **Pipelines** section.
|
| 460 |
+
- Ensure that the script runs successfully and performs the expected actions.
|
| 461 |
+
|
| 462 |
+
#### 5. Secure the Pipeline
|
| 463 |
+
|
| 464 |
+
- **Permissions**: Ensure only authorized personnel can modify the pipeline and variable group.
|
| 465 |
+
- **Secret Variables**: Keep your credentials secure by marking them as secrets and avoiding logging sensitive information.
|
| 466 |
+
|
| 467 |
+
---
|
| 468 |
+
|
| 469 |
+
## 5. Conclusion
|
| 470 |
+
|
| 471 |
+
Automating the management of inactive Azure Entra ID accounts enhances your organization's security posture by reducing potential attack surfaces. By leveraging TypeScript and Azure DevOps, you can create a scalable and maintainable solution that integrates seamlessly with your existing workflows.
|
| 472 |
+
|
| 473 |
+
> You can refer the **Full Working Source Code here**: [drunkcoding public code](https://dev.azure.com/drunk24/drunkcoding-public/_git/az.tools?path=/az-entraID-scan&version=GBmain)
|
| 474 |
+
|
| 475 |
+
### Key Takeaways
|
| 476 |
+
|
| 477 |
+
- **Security First**: Regularly auditing and managing inactive accounts is critical for security and compliance.
|
| 478 |
+
- **Automation**: Automating tasks reduces manual effort and the likelihood of human error.
|
| 479 |
+
- **Scalability**: Using TypeScript and Azure DevOps allows for easy updates and scalability as your organization grows.
|
| 480 |
+
|
| 481 |
+
### Next Topic
|
| 482 |
+
|
| 483 |
+
- **Enhancements**: Extend the script to send email notifications before disabling accounts.
|
| 484 |
+
- **Logging**: Integrate logging mechanisms for better auditing and monitoring.
|
| 485 |
+
- **Policy Compliance**: Ensure the solution complies with your organization's policies and any applicable regulations.
|
| 486 |
+
|
| 487 |
+
---
|
| 488 |
+
|
| 489 |
+
> **Important**: Accessing certain Microsoft Graph API endpoints requires appropriate licensing. Ensure you have the necessary Microsoft Entra ID P2 or equivalent licenses to use the AuditLog API and other premium features.
|
| 490 |
+
|
| 491 |
+
---
|
| 492 |
+
|
| 493 |
+
## Thank You
|
| 494 |
+
|
| 495 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 496 |
+
|
| 497 |
+
**Steven** | *[GitHub](https://github.com/baoduy)*
|
tools-az-service-bus-dead-letters-cleanup.md
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-08-26T12:00:00Z
|
| 4 |
+
title: "[Tools] Cleaning Up Azure Service Bus Dead-Letter Queues with .NET"
|
| 5 |
+
postSlug: tools-az-service-bus-dead-letters-cleanup
|
| 6 |
+
featured: false
|
| 7 |
+
draft: false
|
| 8 |
+
tags:
|
| 9 |
+
- azure-servicebus-cleanup
|
| 10 |
+
- deadletters-cleanup
|
| 11 |
+
- tools
|
| 12 |
+
description: "This post highlights the importance of regularly cleaning Azure Service Bus Dead-Letter Queues (DLQs) to prevent `QuotaExceededException` storage issues and maintain performance.
|
| 13 |
+
It explains how to automate the process with a .NET background service that moves dead-letter messages to Azure Blob Storage for future analysis,
|
| 14 |
+
along with a ready-to-use Docker image for easy deployment."
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
## Introduction
|
| 18 |
+
|
| 19 |
+
In cloud-based applications, message queues are critical for enabling reliable, asynchronous communication between services. **Azure Service Bus** is a robust messaging platform that facilitates this communication in distributed systems. However, messages that cannot be processed or delivered successfully may end up in the **Dead-Letter Queue (DLQ)**. If left unmanaged, these dead-letter messages can accumulate, leading to storage issues and degraded system performance.
|
| 20 |
+
|
| 21 |
+
In this article, we'll explore the importance of regularly cleaning up dead-letter queues in Azure Service Bus. We'll guide you through implementing a .NET background service that automates this cleanup process by moving dead-letter messages to Azure Blob Storage. This approach ensures your messaging system remains efficient while preserving problematic messages for future analysis or reprocessing.
|
| 22 |
+
|
| 23 |
+
## Table of Contents
|
| 24 |
+
|
| 25 |
+
## Understanding Dead-Letter Queues
|
| 26 |
+
|
| 27 |
+
A **Dead-Letter Queue (DLQ)** is a sub-queue associated with each Azure Service Bus entity (queue or topic subscription). It holds messages that cannot be delivered or processed successfully. Messages may be moved to the DLQ for several reasons:
|
| 28 |
+
|
| 29 |
+
- **Exceeding Maximum Delivery Attempts**: A message is retried multiple times but still cannot be processed successfully.
|
| 30 |
+
- **Message Expiration**: The message's **Time to Live (TTL)** expires before it is processed.
|
| 31 |
+
- **Filter Violations**: The message does not match the filter criteria of a subscription.
|
| 32 |
+
- **Processing Errors**: An application explicitly moves a message to the DLQ due to a processing failure.
|
| 33 |
+
|
| 34 |
+
By design, the DLQ provides a way to isolate faulty messages, allowing your system to continue processing valid messages without interruption.
|
| 35 |
+
|
| 36 |
+
## Why Regularly Clean Up Dead-Letter Messages?
|
| 37 |
+
|
| 38 |
+
### 1. Prevent Storage Overruns
|
| 39 |
+
|
| 40 |
+
Dead-letter messages accumulate over time, consuming storage resources. If left unchecked, this can lead to a `QuotaExceededException`, where the maximum size limit for a Service Bus entity is reached:
|
| 41 |
+
|
| 42 |
+
```
|
| 43 |
+
Microsoft.Azure.ServiceBus.QuotaExceededException:
|
| 44 |
+
The maximum entity size has been reached or exceeded for Topic:
|
| 45 |
+
'YourTopicName'. Size of entity in bytes: 2147489161, Max entity size in bytes: 2147483648.
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
This exception can disrupt normal operations, preventing new messages from being sent or received.
|
| 49 |
+
|
| 50 |
+
### 2. Maintain System Performance and Reliability
|
| 51 |
+
|
| 52 |
+
Large volumes of dead-letter messages can degrade the performance of your Service Bus namespace. They can slow down operations such as message retrieval and monitoring, leading to bottlenecks in your system.
|
| 53 |
+
|
| 54 |
+
### 3. Enable Effective Error Handling and Analysis
|
| 55 |
+
|
| 56 |
+
By archiving dead-letter messages to Azure Blob Storage, you retain the ability to analyze and diagnose issues without impacting the performance of your messaging system. This allows your team to:
|
| 57 |
+
|
| 58 |
+
- **Investigate Failures**: Understand why messages failed and identify patterns.
|
| 59 |
+
- **Reprocess Messages**: Correct issues and resend messages if necessary.
|
| 60 |
+
- **Improve Resilience**: Implement fixes to prevent similar failures in the future.
|
| 61 |
+
|
| 62 |
+
## Implementing a Dead-Letter Cleanup Service with .NET
|
| 63 |
+
|
| 64 |
+
To automate the cleanup process, we'll create a .NET background service that:
|
| 65 |
+
|
| 66 |
+
1. **Retrieves dead-letter messages** from all queues and topic subscriptions.
|
| 67 |
+
2. **Archives messages** to Azure Blob Storage.
|
| 68 |
+
3. **Deletes messages** from the DLQ after successful archiving.
|
| 69 |
+
|
| 70 |
+
### Prerequisites
|
| 71 |
+
|
| 72 |
+
- **Azure Service Bus Namespace**: With appropriate permissions (Manage rights) to access queues and topics.
|
| 73 |
+
- **Azure Storage Account**: For storing archived dead-letter messages.
|
| 74 |
+
- **.NET 6 SDK**: Installed on your development machine.
|
| 75 |
+
- **Docker**: (Optional) For containerized deployment.
|
| 76 |
+
|
| 77 |
+
### Getting the Source Code
|
| 78 |
+
|
| 79 |
+
The source code for the cleanup tool is available on GitHub:
|
| 80 |
+
|
| 81 |
+
- **Repository**: [Azure Service Bus Dead-Letter Cleanup Tool](https://github.com/baoduy/tool-serviceBus-deadLetters-cleanup)
|
| 82 |
+
|
| 83 |
+
### Service Configuration
|
| 84 |
+
|
| 85 |
+
The service uses an `appsettings.json` file for configuration:
|
| 86 |
+
|
| 87 |
+
```json
|
| 88 |
+
{
|
| 89 |
+
"ServiceBus": {
|
| 90 |
+
"ConnectionString": "YOUR_SERVICE_BUS_CONNECTION_STRING"
|
| 91 |
+
},
|
| 92 |
+
"StorageAccount": {
|
| 93 |
+
"ConnectionString": "YOUR_STORAGE_ACCOUNT_CONNECTION_STRING",
|
| 94 |
+
"ContainerName": "bus-dead-letters"
|
| 95 |
+
},
|
| 96 |
+
"Logging": {
|
| 97 |
+
"LogLevel": {
|
| 98 |
+
"Default": "Information",
|
| 99 |
+
"Microsoft": "Warning"
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
}
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
- **ServiceBus**:
|
| 106 |
+
- `ConnectionString`: Your Azure Service Bus connection string with Manage permissions.
|
| 107 |
+
- **StorageAccount**:
|
| 108 |
+
- `ConnectionString`: Your Azure Storage Account connection string.
|
| 109 |
+
- `ContainerName`: The name of the Blob Storage container where dead-letter messages will be stored.
|
| 110 |
+
|
| 111 |
+
> **Security Note**: For production environments, consider using Azure Key Vault or environment variables to securely manage connection strings.
|
| 112 |
+
|
| 113 |
+
### How the Cleanup Service Works
|
| 114 |
+
|
| 115 |
+
1. **Connect to Azure Service Bus**: The service connects to your Service Bus namespace using the provided connection string.
|
| 116 |
+
|
| 117 |
+
2. **Discover Entities**: It retrieves all queues and topic subscriptions in the namespace.
|
| 118 |
+
|
| 119 |
+
3. **Process Dead-Letter Messages**:
|
| 120 |
+
|
| 121 |
+
- For each entity, it checks the DLQ for messages.
|
| 122 |
+
- If messages are found, it reads them and saves each message as a JSON file in Azure Blob Storage.
|
| 123 |
+
- The messages are organized in folders by entity name and date, making them easy to locate.
|
| 124 |
+
|
| 125 |
+
4. **Delete Processed Messages**: After successfully archiving, the messages are deleted from the DLQ.
|
| 126 |
+
|
| 127 |
+
### Archiving Structure in Blob Storage
|
| 128 |
+
|
| 129 |
+
The messages are stored in Azure Blob Storage with the following structure:
|
| 130 |
+
|
| 131 |
+
```
|
| 132 |
+
bus-dead-letters/
|
| 133 |
+
├── queues/
|
| 134 |
+
│ ├── queue1/
|
| 135 |
+
│ │ └── 2023-09-20/
|
| 136 |
+
│ │ ├── message1.json
|
| 137 |
+
│ │ └── message2.json
|
| 138 |
+
│ └── queue2/
|
| 139 |
+
│ └── 2023-09-20/
|
| 140 |
+
│ └── message1.json
|
| 141 |
+
└── topics/
|
| 142 |
+
├── topic1/
|
| 143 |
+
│ ├── subscription1/
|
| 144 |
+
│ │ └── 2023-09-20/
|
| 145 |
+
│ │ └── message1.json
|
| 146 |
+
│ └── subscription2/
|
| 147 |
+
│ └── 2023-09-20/
|
| 148 |
+
│ └── message1.json
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
### Setting Up the Service
|
| 152 |
+
|
| 153 |
+
#### Option 1: Running Locally
|
| 154 |
+
|
| 155 |
+
1. **Clone the Repository**:
|
| 156 |
+
|
| 157 |
+
```bash
|
| 158 |
+
git clone https://github.com/baoduy/tool-serviceBus-deadLetters-cleanup.git
|
| 159 |
+
cd tool-serviceBus-deadLetters-cleanup
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
2. **Configure the Service**:
|
| 163 |
+
|
| 164 |
+
- Update `appsettings.json` with your connection strings.
|
| 165 |
+
- Alternatively, set the environment variables `ServiceBus__ConnectionString`, `StorageAccount__ConnectionString`, and `StorageAccount__ContainerName`.
|
| 166 |
+
|
| 167 |
+
3. **Build and Run the Service**:
|
| 168 |
+
|
| 169 |
+
```bash
|
| 170 |
+
dotnet build
|
| 171 |
+
dotnet run
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
#### Option 2: Using Docker
|
| 175 |
+
|
| 176 |
+
A Docker image is available for easy deployment:
|
| 177 |
+
|
| 178 |
+
- **Docker Image**: [baoduy2412/servicebus-cleanup](https://hub.docker.com/r/baoduy2412/servicebus-cleanup)
|
| 179 |
+
|
| 180 |
+
##### Running with Docker Compose
|
| 181 |
+
|
| 182 |
+
Create a `docker-compose.yml` file:
|
| 183 |
+
|
| 184 |
+
```yaml
|
| 185 |
+
version: "3.8"
|
| 186 |
+
|
| 187 |
+
services:
|
| 188 |
+
servicebus-cleanup:
|
| 189 |
+
image: baoduy2412/servicebus-cleanup:latest
|
| 190 |
+
environment:
|
| 191 |
+
ServiceBus__ConnectionString: YOUR_SERVICE_BUS_CONNECTION_STRING
|
| 192 |
+
StorageAccount__ConnectionString: YOUR_STORAGE_ACCOUNT_CONNECTION_STRING
|
| 193 |
+
StorageAccount__ContainerName: bus-dead-letters
|
| 194 |
+
restart: unless-stopped
|
| 195 |
+
```
|
| 196 |
+
|
| 197 |
+
Run the service:
|
| 198 |
+
|
| 199 |
+
```bash
|
| 200 |
+
docker-compose up -d
|
| 201 |
+
```
|
| 202 |
+
|
| 203 |
+
##### Running with Docker Command Line
|
| 204 |
+
|
| 205 |
+
```bash
|
| 206 |
+
docker run -d \
|
| 207 |
+
-e ServiceBus__ConnectionString=YOUR_SERVICE_BUS_CONNECTION_STRING \
|
| 208 |
+
-e StorageAccount__ConnectionString=YOUR_STORAGE_ACCOUNT_CONNECTION_STRING \
|
| 209 |
+
-e StorageAccount__ContainerName=bus-dead-letters \
|
| 210 |
+
baoduy2412/servicebus-cleanup:latest
|
| 211 |
+
```
|
| 212 |
+
|
| 213 |
+
### Managing Storage Costs with Lifecycle Policies
|
| 214 |
+
|
| 215 |
+
Over time, archived messages in Blob Storage can accumulate and consume significant storage space. To manage this:
|
| 216 |
+
|
| 217 |
+
1. **Set Up Lifecycle Management**:
|
| 218 |
+
|
| 219 |
+
- In the Azure Portal, navigate to your Storage Account.
|
| 220 |
+
- Select **Lifecycle management** under **Blob service**.
|
| 221 |
+
|
| 222 |
+
2. **Create a Rule**:
|
| 223 |
+
|
| 224 |
+
- **Name**: e.g., `DeleteOldArchivedMessages`.
|
| 225 |
+
- **Scope**: Apply to the container `bus-dead-letters`.
|
| 226 |
+
- **Filter**: Optionally specify filters if needed.
|
| 227 |
+
- **Action**: Delete blobs older than a specified number of days (e.g., 30 days).
|
| 228 |
+
|
| 229 |
+
3. **Save the Rule**: Azure will automatically delete archived messages older than the specified retention period.
|
| 230 |
+
|
| 231 |
+
## Conclusion
|
| 232 |
+
|
| 233 |
+
Dead-letter queues are an integral part of Azure Service Bus, providing a mechanism to handle messages that cannot be processed. However, without regular maintenance, they can lead to storage overruns and impact system performance.
|
| 234 |
+
|
| 235 |
+
By implementing the .NET background service described in this article, you can automate the cleanup of dead-letter queues:
|
| 236 |
+
|
| 237 |
+
- **Automated Cleanup**: Keeps DLQs empty, preventing storage issues.
|
| 238 |
+
- **Message Archiving**: Stores messages for future analysis without impacting Service Bus performance.
|
| 239 |
+
- **Scalability**: The tool operates at the namespace level, handling all queues and topics automatically.
|
| 240 |
+
- **Cost Management**: Utilizes storage lifecycle policies to control storage costs.
|
| 241 |
+
|
| 242 |
+
This approach ensures your messaging system remains reliable and efficient while preserving valuable data for troubleshooting and improvement.
|
| 243 |
+
|
| 244 |
+
## Additional Resources
|
| 245 |
+
|
| 246 |
+
- **GitHub Repository**: [Azure Service Bus Dead-Letter Cleanup Tool](https://github.com/baoduy/tool-serviceBus-deadLetters-cleanup)
|
| 247 |
+
- **Docker Image**: [baoduy2412/servicebus-cleanup](https://hub.docker.com/r/baoduy2412/servicebus-cleanup)
|
| 248 |
+
- **Azure Service Bus Documentation**:
|
| 249 |
+
- [Dead-letter Queues](https://docs.microsoft.com/azure/service-bus-messaging/service-bus-dead-letter-queues)
|
| 250 |
+
- [Service Bus Quotas and Limits](https://docs.microsoft.com/azure/service-bus-messaging/service-bus-quotas)
|
| 251 |
+
- **Azure Blob Storage**:
|
| 252 |
+
- [Lifecycle Management Overview](https://docs.microsoft.com/azure/storage/blobs/lifecycle-management-overview)
|
| 253 |
+
- [Optimize Costs by Automating Data Lifecycle Management](https://docs.microsoft.com/azure/storage/blobs/storage-lifecycle-management-concepts)
|
| 254 |
+
|
| 255 |
+
---
|
| 256 |
+
|
| 257 |
+
By automating dead-letter queue management, you enhance the stability and maintainability of your messaging infrastructure, ensuring it continues to meet the demands of your applications.
|
| 258 |
+
|
| 259 |
+
---
|
| 260 |
+
|
| 261 |
+
## Thank You
|
| 262 |
+
|
| 263 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding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atetime: 2024-08-21T12:00:00Z
|
| 4 |
+
title: "[DevOps] Automating Branch Cleanup in Azure DevOps with Node.js"
|
| 5 |
+
postSlug: tools-devops-repositories-branches-cleanup
|
| 6 |
+
featured: false
|
| 7 |
+
draft: false
|
| 8 |
+
tags:
|
| 9 |
+
- azure-devops
|
| 10 |
+
- repo-cleanup
|
| 11 |
+
- tools
|
| 12 |
+
description: "A comprehensive guide on automating the cleanup of old branches in Azure DevOps Git repositories using a Node.js script.
|
| 13 |
+
The script identifies branches that haven't been updated in the last 90 days and deletes them if they meet certain criteria."
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
## Introduction
|
| 17 |
+
|
| 18 |
+
As software projects evolve, Git repositories can become cluttered with outdated or redundant branches. This clutter makes repository navigation cumbersome and can introduce confusion or errors in the development process. Automating the cleanup of these branches helps maintain an organized and efficient development environment.
|
| 19 |
+
|
| 20 |
+
In this guide, we'll walk through setting up a TypeScript script that automatically deletes old, unnecessary branches in Azure DevOps. We'll cover the essential steps, focusing on the implementation and automation of the cleanup process.
|
| 21 |
+
|
| 22 |
+
---
|
| 23 |
+
|
| 24 |
+
## Table of Contents
|
| 25 |
+
|
| 26 |
+
- [Introduction](#introduction)
|
| 27 |
+
- [Table of Contents](#table-of-contents)
|
| 28 |
+
- [Why Automate Branch Cleanup?](#why-automate-branch-cleanup)
|
| 29 |
+
- [Prerequisites](#prerequisites)
|
| 30 |
+
- [Project Setup](#project-setup)
|
| 31 |
+
- [Configuration File](#configuration-file)
|
| 32 |
+
- [Implementing the TypeScript Script](#implementing-the-typescript-script)
|
| 33 |
+
- [1. Loading Environment Variables](#1-loading-environment-variables)
|
| 34 |
+
- [2. Defining the Configuration Interface](#2-defining-the-configuration-interface)
|
| 35 |
+
- [3. Setting Constants](#3-setting-constants)
|
| 36 |
+
- [4. Getting the Git API Client](#4-getting-the-git-api-client)
|
| 37 |
+
- [5. Loading the Configuration](#5-loading-the-configuration)
|
| 38 |
+
- [6. Retrieving Repositories and Branches](#6-retrieving-repositories-and-branches)
|
| 39 |
+
- [7. Determining the Last Commit Date](#7-determining-the-last-commit-date)
|
| 40 |
+
- [8. Checking if a Branch is Merged](#8-checking-if-a-branch-is-merged)
|
| 41 |
+
- [9. Deleting a Branch](#9-deleting-a-branch)
|
| 42 |
+
- [10. Compiling the Exclusion List](#10-compiling-the-exclusion-list)
|
| 43 |
+
- [11. Cleaning Up Branches](#11-cleaning-up-branches)
|
| 44 |
+
- [Automating with Azure DevOps Pipeline](#automating-with-azure-devops-pipeline)
|
| 45 |
+
- [Conclusion](#conclusion)
|
| 46 |
+
- [Additional Resources](#additional-resources)
|
| 47 |
+
- [Thank You](#thank-you)
|
| 48 |
+
|
| 49 |
+
---
|
| 50 |
+
|
| 51 |
+
## Why Automate Branch Cleanup?
|
| 52 |
+
|
| 53 |
+
Automating branch cleanup is essential for several reasons:
|
| 54 |
+
|
| 55 |
+
- **Reduce Clutter**: Keeps the repository clean, making it easier for developers to navigate.
|
| 56 |
+
- **Improve Performance**: Enhances CI/CD pipeline performance by reducing overhead.
|
| 57 |
+
- **Prevent Confusion**: Minimizes the risk of developers working on or merging outdated branches.
|
| 58 |
+
- **Enhance Security**: Removes obsolete branches that may contain vulnerabilities.
|
| 59 |
+
|
| 60 |
+
---
|
| 61 |
+
|
| 62 |
+
## Prerequisites
|
| 63 |
+
|
| 64 |
+
Ensure you have the following before starting:
|
| 65 |
+
|
| 66 |
+
- **Azure DevOps Account**: Access to your organization's Azure DevOps instance.
|
| 67 |
+
- **Personal Access Token (PAT)**: A PAT with permissions to access and manage repositories.
|
| 68 |
+
- **Node.js and npm**: Installed on your machine (Node.js version 14 or later).
|
| 69 |
+
- **TypeScript**: Installed globally (`npm install -g typescript`).
|
| 70 |
+
- **Azure DevOps Node API Package**: Install via `npm install azure-devops-node-api`.
|
| 71 |
+
- **dotenv Package**: Install via `npm install dotenv`.
|
| 72 |
+
|
| 73 |
+
---
|
| 74 |
+
|
| 75 |
+
## Project Setup
|
| 76 |
+
|
| 77 |
+
1. **Create a New Directory**: Initialize a new Node.js project.
|
| 78 |
+
|
| 79 |
+
```bash
|
| 80 |
+
mkdir azure-devops-branch-cleanup
|
| 81 |
+
cd azure-devops-branch-cleanup
|
| 82 |
+
npm init -y
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
2. **Install Dependencies**:
|
| 86 |
+
|
| 87 |
+
```bash
|
| 88 |
+
npm install @azure/identity @microsoft/microsoft-graph-client azure-devops-node-api dayjs dotenv
|
| 89 |
+
npm install --save-dev typescript @types/node
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
---
|
| 93 |
+
|
| 94 |
+
## Configuration File
|
| 95 |
+
|
| 96 |
+
Create a `config.json` file in your project root to specify branches that should be excluded from deletion:
|
| 97 |
+
|
| 98 |
+
```json
|
| 99 |
+
{
|
| 100 |
+
"globalExcludes": ["master", "develop", "main", "release"],
|
| 101 |
+
"repositoryExcludes": {
|
| 102 |
+
"your-repo-name": ["feature/important-branch"]
|
| 103 |
+
}
|
| 104 |
+
}
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
- **globalExcludes**: Branches excluded from deletion across all repositories.
|
| 108 |
+
- **repositoryExcludes**: Specific branches to exclude in specific repositories.
|
| 109 |
+
|
| 110 |
+
---
|
| 111 |
+
|
| 112 |
+
## Implementing the TypeScript Script
|
| 113 |
+
|
| 114 |
+
Create a TypeScript file, e.g., `cleanup.ts`, and implement the following steps:
|
| 115 |
+
|
| 116 |
+
### 1. Loading Environment Variables
|
| 117 |
+
|
| 118 |
+
Use the `dotenv` package to load environment variables.
|
| 119 |
+
|
| 120 |
+
```typescript
|
| 121 |
+
import * as dotenv from "dotenv";
|
| 122 |
+
dotenv.config();
|
| 123 |
+
|
| 124 |
+
const isDryRun = process.env.DryRun === "true";
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
**Environment Variables Required**:
|
| 128 |
+
|
| 129 |
+
- `AZURE_DEVOPS_URL`: Your Azure DevOps organization URL.
|
| 130 |
+
- `AZURE_DEVOPS_PAT`: Your Personal Access Token.
|
| 131 |
+
- `AZURE_DEVOPS_PROJECT`: Your project name.
|
| 132 |
+
- `DryRun`: Set to `"true"` for dry-run mode (no actual deletions).
|
| 133 |
+
|
| 134 |
+
### 2. Defining the Configuration Interface
|
| 135 |
+
|
| 136 |
+
Define an interface to ensure type safety.
|
| 137 |
+
|
| 138 |
+
```typescript
|
| 139 |
+
interface Config {
|
| 140 |
+
globalExcludes: string[];
|
| 141 |
+
repositoryExcludes: {
|
| 142 |
+
[repoName: string]: string[];
|
| 143 |
+
};
|
| 144 |
+
}
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
### 3. Setting Constants
|
| 148 |
+
|
| 149 |
+
Define constants used in the script.
|
| 150 |
+
|
| 151 |
+
```typescript
|
| 152 |
+
const DAYS_90_MS = 90 * 24 * 60 * 60 * 1000; // 90 days in milliseconds
|
| 153 |
+
```
|
| 154 |
+
|
| 155 |
+
### 4. Getting the Git API Client
|
| 156 |
+
|
| 157 |
+
Authenticate and obtain the Git API client.
|
| 158 |
+
|
| 159 |
+
```typescript
|
| 160 |
+
import * as azdev from "azure-devops-node-api";
|
| 161 |
+
import * as GitApi from "azure-devops-node-api/GitApi";
|
| 162 |
+
|
| 163 |
+
async function getGitApi(): Promise<GitApi.IGitApi> {
|
| 164 |
+
const orgUrl = process.env.AZURE_DEVOPS_URL;
|
| 165 |
+
const token = process.env.AZURE_DEVOPS_PAT;
|
| 166 |
+
|
| 167 |
+
if (!orgUrl || !token) {
|
| 168 |
+
throw new Error(
|
| 169 |
+
"Azure DevOps URL or PAT is not set in environment variables."
|
| 170 |
+
);
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
const authHandler = azdev.getPersonalAccessTokenHandler(token);
|
| 174 |
+
const connection = new azdev.WebApi(orgUrl, authHandler);
|
| 175 |
+
return await connection.getGitApi();
|
| 176 |
+
}
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
### 5. Loading the Configuration
|
| 180 |
+
|
| 181 |
+
Load the `config.json` file.
|
| 182 |
+
|
| 183 |
+
```typescript
|
| 184 |
+
import * as fs from "fs";
|
| 185 |
+
import * as path from "path";
|
| 186 |
+
|
| 187 |
+
function loadConfig(): Config {
|
| 188 |
+
const configPath = path.join(__dirname, "config.json");
|
| 189 |
+
const configContent = fs.readFileSync(configPath, "utf-8");
|
| 190 |
+
return JSON.parse(configContent) as Config;
|
| 191 |
+
}
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
### 6. Retrieving Repositories and Branches
|
| 195 |
+
|
| 196 |
+
Get the list of repositories and branches.
|
| 197 |
+
|
| 198 |
+
```typescript
|
| 199 |
+
import * as GitInterfaces from "azure-devops-node-api/interfaces/GitInterfaces";
|
| 200 |
+
|
| 201 |
+
async function getRepositories(
|
| 202 |
+
gitApi: GitApi.IGitApi,
|
| 203 |
+
project: string
|
| 204 |
+
): Promise<GitInterfaces.GitRepository[]> {
|
| 205 |
+
return await gitApi.getRepositories(project);
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
async function getBranches(
|
| 209 |
+
gitApi: GitApi.IGitApi,
|
| 210 |
+
project: string,
|
| 211 |
+
repoId: string
|
| 212 |
+
): Promise<GitInterfaces.GitRef[]> {
|
| 213 |
+
const branches = await gitApi.getRefs(repoId, project);
|
| 214 |
+
return branches.filter(b => b.name.startsWith("refs/heads/"));
|
| 215 |
+
}
|
| 216 |
+
```
|
| 217 |
+
|
| 218 |
+
### 7. Determining the Last Commit Date
|
| 219 |
+
|
| 220 |
+
Get the date of the last commit on a branch.
|
| 221 |
+
|
| 222 |
+
```typescript
|
| 223 |
+
async function getLastCommitDate(
|
| 224 |
+
gitApi: GitApi.IGitApi,
|
| 225 |
+
project: string,
|
| 226 |
+
repoId: string,
|
| 227 |
+
branchName: string
|
| 228 |
+
): Promise<Date | null> {
|
| 229 |
+
const commits = await gitApi.getCommits(
|
| 230 |
+
repoId,
|
| 231 |
+
{ itemVersion: { version: branchName } },
|
| 232 |
+
project,
|
| 233 |
+
undefined,
|
| 234 |
+
1
|
| 235 |
+
);
|
| 236 |
+
|
| 237 |
+
if (commits.length > 0) {
|
| 238 |
+
const commitDate = commits[0].committer.date || commits[0].author.date;
|
| 239 |
+
return new Date(commitDate);
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
return null;
|
| 243 |
+
}
|
| 244 |
+
```
|
| 245 |
+
|
| 246 |
+
### 8. Checking if a Branch is Merged
|
| 247 |
+
|
| 248 |
+
Check if a branch is merged into any of the target branches.
|
| 249 |
+
|
| 250 |
+
```typescript
|
| 251 |
+
import { GitVersionType } from "azure-devops-node-api/interfaces/GitInterfaces";
|
| 252 |
+
|
| 253 |
+
async function isBranchMerged(
|
| 254 |
+
gitApi: GitApi.IGitApi,
|
| 255 |
+
project: string,
|
| 256 |
+
repoId: string,
|
| 257 |
+
branch: string,
|
| 258 |
+
targetBranches: string[]
|
| 259 |
+
): Promise<boolean> {
|
| 260 |
+
for (const targetBranch of targetBranches) {
|
| 261 |
+
const diff = await gitApi.getCommitDiffs(
|
| 262 |
+
repoId,
|
| 263 |
+
project,
|
| 264 |
+
true,
|
| 265 |
+
1,
|
| 266 |
+
undefined,
|
| 267 |
+
{ baseVersionType: GitVersionType.Branch, baseVersion: branch },
|
| 268 |
+
{ targetVersionType: GitVersionType.Branch, targetVersion: targetBranch }
|
| 269 |
+
);
|
| 270 |
+
|
| 271 |
+
if (diff && diff.aheadCount === 0) {
|
| 272 |
+
return true;
|
| 273 |
+
}
|
| 274 |
+
}
|
| 275 |
+
return false;
|
| 276 |
+
}
|
| 277 |
+
```
|
| 278 |
+
|
| 279 |
+
### 9. Deleting a Branch
|
| 280 |
+
|
| 281 |
+
Delete the branch if it meets the criteria.
|
| 282 |
+
|
| 283 |
+
```typescript
|
| 284 |
+
async function deleteBranch(
|
| 285 |
+
gitApi: GitApi.IGitApi,
|
| 286 |
+
project: string,
|
| 287 |
+
repoId: string,
|
| 288 |
+
branch: GitInterfaces.GitRef
|
| 289 |
+
): Promise<void> {
|
| 290 |
+
if (!isDryRun) {
|
| 291 |
+
if (branch.isLocked) {
|
| 292 |
+
await gitApi.updateRef(
|
| 293 |
+
{ name: branch.name, isLocked: false },
|
| 294 |
+
repoId,
|
| 295 |
+
"",
|
| 296 |
+
project
|
| 297 |
+
);
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
await gitApi.updateRefs(
|
| 301 |
+
[
|
| 302 |
+
{
|
| 303 |
+
name: branch.name,
|
| 304 |
+
newObjectId: "0000000000000000000000000000000000000000",
|
| 305 |
+
oldObjectId: branch.objectId,
|
| 306 |
+
},
|
| 307 |
+
],
|
| 308 |
+
repoId,
|
| 309 |
+
"",
|
| 310 |
+
project
|
| 311 |
+
);
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
console.log(`Deleted branch: ${branch.name} (Dry Run: ${isDryRun})`);
|
| 315 |
+
}
|
| 316 |
+
```
|
| 317 |
+
|
| 318 |
+
### 10. Compiling the Exclusion List
|
| 319 |
+
|
| 320 |
+
Combine global and repository-specific exclusions.
|
| 321 |
+
|
| 322 |
+
```typescript
|
| 323 |
+
function getExclusionList(config: Config, repoName: string): string[] {
|
| 324 |
+
const globalExcludes = config.globalExcludes || [];
|
| 325 |
+
const repoSpecificExcludes = config.repositoryExcludes[repoName] || [];
|
| 326 |
+
return [...new Set([...globalExcludes, ...repoSpecificExcludes])];
|
| 327 |
+
}
|
| 328 |
+
```
|
| 329 |
+
|
| 330 |
+
### 11. Cleaning Up Branches
|
| 331 |
+
|
| 332 |
+
Main function orchestrating the cleanup.
|
| 333 |
+
|
| 334 |
+
```typescript
|
| 335 |
+
async function cleanUpBranches(): Promise<void> {
|
| 336 |
+
const project = process.env.AZURE_DEVOPS_PROJECT;
|
| 337 |
+
if (!project) {
|
| 338 |
+
throw new Error(
|
| 339 |
+
"Azure DevOps project name is not set in environment variables."
|
| 340 |
+
);
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
const config = loadConfig();
|
| 344 |
+
const now = new Date();
|
| 345 |
+
const gitApi = await getGitApi();
|
| 346 |
+
const repositories = await getRepositories(gitApi, project);
|
| 347 |
+
|
| 348 |
+
for (const repo of repositories) {
|
| 349 |
+
console.log(`Processing repository: ${repo.name}`);
|
| 350 |
+
const excludeBranches = getExclusionList(config, repo.name);
|
| 351 |
+
const branches = await getBranches(gitApi, project, repo.id);
|
| 352 |
+
|
| 353 |
+
for (const branch of branches) {
|
| 354 |
+
const branchName = branch.name.replace("refs/heads/", "");
|
| 355 |
+
|
| 356 |
+
if (excludeBranches.includes(branchName)) {
|
| 357 |
+
console.log(`Skipping excluded branch: ${branchName}`);
|
| 358 |
+
continue;
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
const lastCommitDate = await getLastCommitDate(
|
| 362 |
+
gitApi,
|
| 363 |
+
project,
|
| 364 |
+
repo.id,
|
| 365 |
+
branchName
|
| 366 |
+
);
|
| 367 |
+
|
| 368 |
+
if (
|
| 369 |
+
!lastCommitDate ||
|
| 370 |
+
now.getTime() - lastCommitDate.getTime() < DAYS_90_MS
|
| 371 |
+
) {
|
| 372 |
+
console.log(`Branch is recent or active: ${branchName}`);
|
| 373 |
+
continue;
|
| 374 |
+
}
|
| 375 |
+
|
| 376 |
+
const isMerged = await isBranchMerged(
|
| 377 |
+
gitApi,
|
| 378 |
+
project,
|
| 379 |
+
repo.id,
|
| 380 |
+
branchName,
|
| 381 |
+
config.globalExcludes
|
| 382 |
+
);
|
| 383 |
+
|
| 384 |
+
if (isMerged) {
|
| 385 |
+
await deleteBranch(gitApi, project, repo.id, branch);
|
| 386 |
+
} else {
|
| 387 |
+
console.log(`Branch is not merged: ${branchName}`);
|
| 388 |
+
}
|
| 389 |
+
}
|
| 390 |
+
}
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
cleanUpBranches().catch(err => {
|
| 394 |
+
console.error("An error occurred:", err);
|
| 395 |
+
});
|
| 396 |
+
```
|
| 397 |
+
|
| 398 |
+
---
|
| 399 |
+
|
| 400 |
+
## Automating with Azure DevOps Pipeline
|
| 401 |
+
|
| 402 |
+
To automate the script execution, set up an Azure DevOps Pipeline.
|
| 403 |
+
|
| 404 |
+
1. **Create a Variable Group**:
|
| 405 |
+
|
| 406 |
+
- Navigate to **Pipelines** > **Library** in Azure DevOps.
|
| 407 |
+
- Click **"Variable groups"** > **"Add variable group"**.
|
| 408 |
+
- Name the group, e.g., `az-devops`.
|
| 409 |
+
- Add the variables:
|
| 410 |
+
- `AZURE_DEVOPS_URL`
|
| 411 |
+
- `AZURE_DEVOPS_PAT` (set as secret)
|
| 412 |
+
- `AZURE_DEVOPS_PROJECT`
|
| 413 |
+
- Save the variable group.
|
| 414 |
+
|
| 415 |
+
2. **Create the Pipeline YAML File**:
|
| 416 |
+
|
| 417 |
+
Create a `azure-pipelines.yml` file in your repository:
|
| 418 |
+
|
| 419 |
+
```yaml
|
| 420 |
+
trigger: none
|
| 421 |
+
|
| 422 |
+
schedules:
|
| 423 |
+
- cron: "0 0 * * 0" # Runs every Sunday at 00:00
|
| 424 |
+
displayName: "Weekly Branch Cleanup"
|
| 425 |
+
branches:
|
| 426 |
+
include:
|
| 427 |
+
- main
|
| 428 |
+
always: true
|
| 429 |
+
batch: false
|
| 430 |
+
|
| 431 |
+
pool:
|
| 432 |
+
vmImage: ubuntu-latest
|
| 433 |
+
|
| 434 |
+
variables:
|
| 435 |
+
- group: az-devops
|
| 436 |
+
|
| 437 |
+
steps:
|
| 438 |
+
- task: NodeTool@0
|
| 439 |
+
inputs:
|
| 440 |
+
versionSpec: "14.x"
|
| 441 |
+
displayName: "Install Node.js"
|
| 442 |
+
|
| 443 |
+
- script: |
|
| 444 |
+
npm ci
|
| 445 |
+
npx ts-node cleanup.ts
|
| 446 |
+
displayName: "Run Branch Cleanup Script"
|
| 447 |
+
env:
|
| 448 |
+
AZURE_DEVOPS_URL: $(AZURE_DEVOPS_URL)
|
| 449 |
+
AZURE_DEVOPS_PAT: $(AZURE_DEVOPS_PAT)
|
| 450 |
+
AZURE_DEVOPS_PROJECT: $(AZURE_DEVOPS_PROJECT)
|
| 451 |
+
```
|
| 452 |
+
|
| 453 |
+
- **Notes**:
|
| 454 |
+
- Replace `cleanup.ts` with the path to your script.
|
| 455 |
+
- Ensure the pipeline has access to the variable group.
|
| 456 |
+
|
| 457 |
+
---
|
| 458 |
+
|
| 459 |
+
## Conclusion
|
| 460 |
+
|
| 461 |
+
Automating branch cleanup ensures your repositories remain organized, improving developer productivity and reducing potential errors. By following this guide, you can set up a script to automatically identify and delete old, unused branches in Azure DevOps, and schedule it using Azure Pipelines for regular maintenance.
|
| 462 |
+
|
| 463 |
+
**Benefits**:
|
| 464 |
+
|
| 465 |
+
- **Efficiency**: Saves time and resources.
|
| 466 |
+
- **Consistency**: Maintains a consistent repository state.
|
| 467 |
+
- **Scalability**: Easily extends to multiple projects and repositories.
|
| 468 |
+
|
| 469 |
+
---
|
| 470 |
+
|
| 471 |
+
## Additional Resources
|
| 472 |
+
|
| 473 |
+
- **Full Working Source Code**: [drunkcoding public code](https://dev.azure.com/drunk24/drunkcoding-public/_git/az.tools?path=/az-devops-delete-branches&version=GBmain)
|
| 474 |
+
- **Azure DevOps Node API Documentation**: [Git API Reference](https://github.com/microsoft/azure-devops-node-api/blob/master/api/GitApi.ts)
|
| 475 |
+
- **Azure DevOps REST API Reference**: [Git Repositories](https://docs.microsoft.com/en-us/rest/api/azure/devops/git/repositories)
|
| 476 |
+
|
| 477 |
+
---
|
| 478 |
+
|
| 479 |
+
**Note**: Always test scripts in a controlled environment before deploying them in production. Ensure compliance with your organization's policies and procedures.
|
| 480 |
+
|
| 481 |
+
---
|
| 482 |
+
|
| 483 |
+
## Thank You
|
| 484 |
+
|
| 485 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 486 |
+
|
| 487 |
+
**Steven** | *[GitHub](https://github.com/baoduy)*
|
tools-sql-database-cleanup.md
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
author: Steven Hoang
|
| 3 |
+
pubDatetime: 2024-08-26T12:00:00Z
|
| 4 |
+
title: "[Tools] Automating SQL Data Cleanup in Development and Sandbox Environments"
|
| 5 |
+
postSlug: tools-sql-server-data-cleanup
|
| 6 |
+
featured: false
|
| 7 |
+
draft: true
|
| 8 |
+
tags:
|
| 9 |
+
- database-cleanup
|
| 10 |
+
- tools
|
| 11 |
+
description: "The post introduces the **SQL Data Cleanup** tool, which automates the removal of old records from SQL databases,
|
| 12 |
+
improving performance and saving storage costs in development environments. It includes configuration options and Docker support for easy setup."
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
### Introduction
|
| 16 |
+
|
| 17 |
+
In development and sandbox environments, data can pile up quickly—old transaction records, exchange rates, logs, you name it! Without regular cleanup, databases become bloated, making it harder to work efficiently and often leading to increased storage costs. To tackle this, I’ve created the **SQL Data Cleanup** program, a handy tool that automates the removal of outdated records from SQL databases based on flexible configurations.
|
| 18 |
+
|
| 19 |
+
Let’s dive into why this matters and how this tool can help streamline your database management.
|
| 20 |
+
|
| 21 |
+
### Why Bother Cleaning Up?
|
| 22 |
+
|
| 23 |
+
Here are a few great reasons to stay on top of your data cleanup game:
|
| 24 |
+
|
| 25 |
+
- **Reduce Clutter**: As databases grow, they can get messy, making it harder to find relevant data and slowing down development work.
|
| 26 |
+
- **Boost Performance**: A lean database runs smoother! Regular cleanup helps keep things fast and efficient.
|
| 27 |
+
- **Save Money**: In cloud environments, storage costs can sneak up on you. Cleaning up old, unnecessary data helps keep your budget under control.
|
| 28 |
+
- **Avoid Confusion**: Nobody wants to mistakenly work with outdated records. Keeping only the relevant data ensures developers don’t accidentally reference old info in their code.
|
| 29 |
+
|
| 30 |
+
### The Solution: SQL Data Cleanup Program
|
| 31 |
+
|
| 32 |
+
To solve this, I’ve created a simple yet powerful tool that automates the cleanup of specific databases and tables. You can find the code and more details here: [GitHub: SQL Data Cleanup Tool](https://github.com/baoduy/tool-sql-data-cleanup).
|
| 33 |
+
|
| 34 |
+
The program allows you to configure which data to remove, how long to keep it, and what fields to use when determining the age of records. Here’s a basic example configuration:
|
| 35 |
+
|
| 36 |
+
```json
|
| 37 |
+
{
|
| 38 |
+
"DbCleanup": {
|
| 39 |
+
"OlderThanDays": 365,
|
| 40 |
+
"ConnectionString": "YOUR_CONNECTION_STRING",
|
| 41 |
+
"PrimaryField": "Id",
|
| 42 |
+
"ConditionFields": ["CreatedOn"],
|
| 43 |
+
"Databases": {
|
| 44 |
+
"database-1": {
|
| 45 |
+
"PrimaryField": "Id",
|
| 46 |
+
"ConditionFields": ["UpdateOn"],
|
| 47 |
+
"Tables": {
|
| 48 |
+
"table-1": { "PrimaryField": "Id" },
|
| 49 |
+
"random-table-2": { "PrimaryField": "Id" }
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
}
|
| 54 |
+
}
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
### Configuration Breakdown
|
| 58 |
+
|
| 59 |
+
The configuration has three levels: **Global**, **Database**, and **Table**, giving you full control over the cleanup process.
|
| 60 |
+
|
| 61 |
+
- **Global Settings**:
|
| 62 |
+
|
| 63 |
+
- **OlderThanDays**: Specify how long to keep data (in this case, 365 days).
|
| 64 |
+
- **ConnectionString**: The SQL connection string template.
|
| 65 |
+
- **PrimaryField**: The key field used to identify records in all tables.
|
| 66 |
+
- **ConditionFields**: These fields determine the age of the records to be cleaned up.
|
| 67 |
+
|
| 68 |
+
- **Database-Level Settings**:
|
| 69 |
+
|
| 70 |
+
- Similar to global settings but applied to specific databases.
|
| 71 |
+
|
| 72 |
+
- **Table-Level Settings**:
|
| 73 |
+
- Customize which fields to use for each table, ensuring flexibility in how you manage each dataset.
|
| 74 |
+
|
| 75 |
+
### Docker Support
|
| 76 |
+
|
| 77 |
+
To make things even easier, I’ve built the program into a Docker image, available on Docker Hub. You can run it on both ARM and AMD platforms without any hassle!
|
| 78 |
+
|
| 79 |
+
- **Docker Image**: [baoduy2412/tool-sql-cleanup](https://hub.docker.com/r/baoduy2412/tool-sql-cleanup)
|
| 80 |
+
|
| 81 |
+
Here’s a sample `docker-compose.yml` configuration to get you started:
|
| 82 |
+
|
| 83 |
+
```yaml
|
| 84 |
+
services:
|
| 85 |
+
app:
|
| 86 |
+
image: baoduy2412/tool-sql-cleanup:latest
|
| 87 |
+
environment:
|
| 88 |
+
DbCleanup__OlderThanDays: "365"
|
| 89 |
+
DbCleanup__ConnectionString: "YOUR_CONNECTION_STRING"
|
| 90 |
+
DbCleanup__PrimaryField: "Id"
|
| 91 |
+
DbCleanup__ConditionFields__0: "CreatedOn"
|
| 92 |
+
DbCleanup__Databases__database-1__PrimaryField: "Id"
|
| 93 |
+
DbCleanup__Databases__database-1__ConditionFields__0: "UpdateOn"
|
| 94 |
+
DbCleanup__Databases__database-1__Tables__table-1__PrimaryField: "Id"
|
| 95 |
+
DbCleanup__Databases__database-1__Tables__random-table-2__PrimaryField: "Id"
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
### Conclusion
|
| 99 |
+
|
| 100 |
+
The **SQL Data Cleanup** program is a lifesaver for keeping your development and sandbox environments lean and efficient. It helps automate the process of removing outdated data, boosts performance, reduces costs, and ensures your database doesn’t become a tangled mess. Best of all, it’s fully configurable—you choose which tables to clean up and how long to keep your data.
|
| 101 |
+
|
| 102 |
+
Feel free to give it a try, and as always, I’d love to hear your feedback! Let’s keep our databases tidy! 🚀
|
| 103 |
+
|
| 104 |
+
---
|
| 105 |
+
|
| 106 |
+
## Thank You
|
| 107 |
+
|
| 108 |
+
Thank you for taking the time to read this guide! I hope it has been helpful, feel free to explore further, and happy coding! 🌟✨
|
| 109 |
+
|
| 110 |
+
**Steven** | *[GitHub](https://github.com/baoduy)*
|