<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Suhail Nepal on Medium]]></title>
        <description><![CDATA[Stories by Suhail Nepal on Medium]]></description>
        <link>https://medium.com/@suhail_nepal?source=rss-29bb791406e2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Suhail Nepal on Medium</title>
            <link>https://medium.com/@suhail_nepal?source=rss-29bb791406e2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:35:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@suhail_nepal/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Training to Deployment: Scikit-Learn Machine Learning Model on Azure Kubernetes Service (AKS)]]></title>
            <link>https://medium.com/@suhail_nepal/from-training-to-deployment-scikit-learn-machine-learning-model-on-azure-kubernetes-service-aks-de4e925670ca?source=rss-29bb791406e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/de4e925670ca</guid>
            <dc:creator><![CDATA[Suhail Nepal]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 14:30:48 GMT</pubDate>
            <atom:updated>2025-02-16T00:04:07.331Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently completed a project where I trained a machine learning model using Scikit-Learn and deployed it as a service on Azure Kubernetes Service (AKS). In this blog, I will walk you through the step-by-step process I followed to implement it, from training the model to deploying it on AKS.</p><h4>Background</h4><p>I wanted to learn the basics of Machine Learning (ML), particularly how datasets are prepared and used to train a model. I came across <a href="https://scikit-learn.org/stable/">Scikit-Learn</a>, which had a very good documentation and numerous blog posts.</p><p>The project idea was to create a simple dataset (`.csv`) containing a list of IT incidents and train a model using this dataset. Once trained, the model should be able to classify new incidents based on previous learning. The goal was that, for every new prompt, the model should determine whether the issue falls under network, server, or application problems, similar to how IT operations categorise incidents.</p><p>I initially tested the model locally using `<a href="http://testmodel.py/">testmodel.py</a>`, and was working as expected. I then decided to build a simple API using FastAPI, containerise it, and deploy it on Azure Kubernetes Service (AKS).</p><p>The primary goal here was to gain insights into both ML fundamentals and the process of deploying an ML model in a containerised format on AKS.</p><p>In this blog, I will walk you through the steps I followed to complete this project.</p><h4><a href="https://github.com/suhailnepal/MLforSRE/tree/main">Source code</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*UrfNbjdqze15yZdocmya_A.png" /></figure><h4>ML Fundamentals</h4><p>I have provided all the details for this section in <a href="https://github.com/suhailnepal/MLforSRE/blob/main/README.md)">README</a>.</p><p>For this project, I followed a three-stage process using a simple dataset (`incidents.csv`). The dataset contains two columns, and after data processing, I used Naive Bayes model to train the model.</p><p>1️⃣ Data Collection &amp; Preprocessing <br>2️⃣ Model Training <br>3️⃣ Model Testing</p><p>(`incidents.csv`)</p><pre>description,category<br>&quot;Cannot connect to VPN&quot;,&quot;Network Issue&quot;<br>&quot;Production server is down&quot;,&quot;Server Issue&quot;<br>&quot;Application crashes frequently&quot;,&quot;Application Issue&quot;<br>&quot;Multiple failed login attempts&quot;,&quot;Security Issue&quot;<br>&quot;Website is extremely slow&quot;,&quot;Testing Issue&quot;</pre><h4>API and Containerisation</h4><p>Once the model was trained and tested, I created a simple test Python script <a href="https://github.com/suhailnepal/MLforSRE/blob/main/testmodel.py)">testmodel.py</a> to verify predictions. The model was working as expected.</p><p>Recently, I’ve been reading a lot about AI/ML infrastructure and how Kubernetes (K8s) is gaining popularity in this space. I wanted to experiment with deploying an ML model in a containerised environment to get hands-on experience.</p><p>For deployment, I had two options:️ Use Flask in Python to create a web server or Build an API using FastAPI and containerise it. I decided to go with the API route using FastAPI, as it is lightweight, asynchronous, and designed for high-performance applications.</p><p>I created an Creating API using FastAPI and Uvicorn, Uvicorn acts as an ASGI server, listening for HTTP requests and routing them to the FastAPI application. Implementation here: <a href="https://github.com/suhailnepal/MLforSRE/blob/main/app.py">app.py</a></p><p>I included a category_mapping section in the code to make predictions more user-friendly. Since ML model returns numerical labels (e.g., 0, 1, 2), I mapped these numbers to their corresponding incident categories such as “Network Issue,” “Server Issue,” and so on.</p><p>For example, if the model predicts 1, instead of returning:</p><pre>{&quot;category&quot;: 1}</pre><p>the API maps it to:</p><pre>{&quot;category&quot;: &quot;Server Issue&quot;}</pre><p>Once the API was ready, I decided to created a docker file with the following setting</p><pre># Use a stable and compatible Python image<br>FROM python:3.12.6-slim<br><br># Set working directory<br>WORKDIR /app<br><br># Install system dependencies<br>RUN apt-get update &amp;&amp; apt-get install -y gcc<br><br># Copy only requirements first (optimizing caching)<br>COPY requirements.txt .<br><br># Installing dependencies<br>RUN pip install --no-cache-dir --upgrade pip &amp;&amp; \<br>    pip install --no-cache-dir -r requirements.txt<br><br># Copy the rest of the app files<br>COPY . .<br><br># Ensure entrypoint scripts have execute permissions<br>RUN chmod +x /app<br><br># Expose API port<br>EXPOSE 8000<br><br># Run FastAPI server<br>CMD [&quot;uvicorn&quot;, &quot;app:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p>It’s very simple, once system dependencies are updated and the files are added in, it exposes port 8000 and uses uvicorn to run fast api server.</p><p>I tested this locally first before I deployed it on Azure</p><p>Steps involved in testing locally</p><ul><li>Creating an image using the dockerfile, this creates a Docker image for the application; platform linux/amd64 ensures compatibility with AKS</li></ul><pre>docker build --platform linux/amd64 -t incident-classifier:latest .</pre><ul><li>Once the image was ready, I tested it by running the container</li></ul><pre>docker run -p 8000:8000 --rm incident-classifier:latest</pre><p>After starting the container, this is how I verfied if API is giving me the response:</p><pre>curl -X &#39;POST&#39; &#39;http://127.0.0.1:8000/predict/&#39; -H &#39;Content-Type: application/json&#39; -d &#39;{&quot;description&quot;: &quot;Computer is not responding&quot;}&#39;</pre><p>Expected outcome:</p><pre>{&quot;category&quot;: &quot;Server Issue&quot;}</pre><p>As a pre-req, before you complete the above steps, you need to have Docker installed the engine running locally on your machine.</p><h4>Azure</h4><p>This is where the real fun begins. Once I confirmed that the API was running locally, I decided to deploy it on AKS.</p><p>Don’t get me wrong — it wasn’t a straightforward process and came with its fair share of hiccups. One of the few issues I ran into was something as simple as image compatibility and had to ensure the Docker image was built for linux/amd64 to work with AKS. 🤦‍♂️</p><p>Before going any further, I want to admit that I created the infrastructure using Azure CLI (AZ-CLI) instead of Infrastructure as Code (IaC) via a pipeline. Since this is just a proof of concept (POC), I opted for the simpler approach.</p><p>Also, here as a pre-req, ensure that you have AZ-CLI installed and authenticated to your dedicated subscription before completing the following steps:</p><p>For the implementation, I had a resource group created in Azure rg-aks-ml and deployed the following services:</p><ul><li>Azure Container Registry (ACR) -&gt; To host the image before it gets deployed on AKS</li><li>Azure Kubertenes Service (AKS) -&gt; Managed Service for K8s service</li></ul><p>### Azure Container Registry (ACR)</p><p>ACR was deployed to host the Docker image and the following AZ -CLI commands were used:</p><ul><li>To create ACR, make sure that acr name does not take any dashes.</li></ul><pre>az acr create --resource-group rg-aks-ml --name acrmltesting --sku Basic --location australiaeast</pre><ul><li>Verify once it was created:</li></ul><pre>az acr list --resource-group rg-aks-ml --output table</pre><ul><li>Authenticate to ACR using AZ-CLI, this ensures that your local Docker CLI is authenticated with ACR</li></ul><pre>az acr login --name acrmltesting</pre><ul><li>Before pushing to ACR, the local images has to be tagged to match ACR format</li></ul><pre>docker tag incident-classifier:latest acrmltesting.azurecr.io/incident-classifier:v1</pre><ul><li>incident-classifier:latest is the local image name.</li><li>acrmltesting.azurecr.io/incident-classifier:v1 is the new tag that aligns with ACR.</li><li>Push the image to ACR, depending on your image size, this might take some time</li></ul><pre>docker push acrmltesting.azurecr.io/incident-classifier:v1</pre><ul><li>Verify that the image is in ACR</li></ul><pre>az acr repository show-tags --name acrmltesting --repository incident-classifier --output table</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aWArZXCZ4yd2ffAFivoeCw.png" /></figure><p>Once the process is complete, you should also be able to verify it from Azure portal for ACR (under Repositories)</p><p>You are now ready to deploy the image on AKS 🚀</p><h4>Azure Kubertenes Service (AKS)</h4><p>Exactly like ACR, I deployed AKS using AZ-CLI as well and the following steps were performed:</p><ul><li>Deploy AKS service;</li></ul><pre>az aks create \<br>    --resource-group rg-aks-ml \<br>    --name aks-ml-testing \<br>    --node-count 1 \<br>    --enable-cluster-autoscaler \<br>    --min-count 1 \<br>    --max-count 3 \<br>    --enable-managed-identity \<br>    --vm-set-type VirtualMachineScaleSets \<br>    --load-balancer-sku basic \<br>    --network-plugin kubenet \<br>    --node-resource-group rg-aks-ml-node \<br>    --no-wait</pre><p>The idea was to create a basic service with minum configuration, node group which creates a VMSS (Virtual Machine Scale Set) is to deployed on resource group rg-aks-ml-node</p><ul><li>Grant AKS access to ACR to pull images, I had enabled Managed Identity (MI) when creating AKS and will be assiging on ACR for AcrPull role:</li></ul><pre>az aks show --resource-group rg-aks-ml --name aks-ml-testing --query &quot;identityProfile.kubeletidentity.objectId&quot; --output tsv</pre><p>The above generates Object ID for MI, copy it and use it on the following command:</p><pre>az role assignment create --assignee &quot;&lt;OBJECT_ID_&gt;&quot; --role &quot;AcrPull&quot; --scope $(az acr show --name acrmltesting --query id --output tsv)</pre><ul><li>Login to AKS</li></ul><pre>az aks get-credentials --resource-group rg-aks-ml --name aks-ml-testing --overwrite-existing</pre><ul><li>Verify connections and nodes are up and running</li></ul><pre>kubectl get nodes</pre><ul><li>Apply deployment and service configuration from deployment.yaml</li></ul><pre>kubectl apply -f deployment.yaml</pre><ul><li>Check the deployment status</li></ul><pre>kubectl get pods</pre><p>Expect output like the below:</p><pre>NAME                                   READY   STATUS    RESTARTS   AGE<br>incident-classifier-xxxxx-mdt97   1/1     Running   0          10s</pre><p>My Deployment file had the following component</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: incident-classifier<br>  labels:<br>    app: incident-classifier<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: incident-classifier<br>  template:<br>    metadata:<br>      labels:<br>        app: incident-classifier<br>    spec:<br>      containers:<br>      - name: incident-classifier<br>        image: acrmltesting.azurecr.io/incident-classifier:v1<br>        imagePullPolicy: Always<br>        ports:<br>        - containerPort: 8000<br>        resources:<br>          limits:<br>            cpu: &quot;500m&quot;<br>            memory: &quot;512Mi&quot;<br>          requests:<br>            cpu: &quot;250m&quot;<br>            memory: &quot;256Mi&quot;<br>        readinessProbe:<br>          httpGet:<br>            path: &quot;/health&quot;<br>            port: 8000<br>          initialDelaySeconds: 5<br>          periodSeconds: 10<br>        livenessProbe:<br>          httpGet:<br>            path: &quot;/health&quot;<br>            port: 8000<br>          initialDelaySeconds: 10<br>          periodSeconds: 20<br>      restartPolicy: Always<br><br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: incident-classifier-service<br>spec:<br>  selector:<br>    app: incident-classifier<br>  ports:<br>  - protocol: TCP<br>    port: 80<br>    targetPort: 8000<br>  type: LoadBalancer</pre><p>The configuration above defines a Deployment and a Service for the API.</p><p>Deployment runs two replicas of a containerised FastAPI application, pulling image from ACR. It also specifies resource limits for CPU and memory to optimise performance and includes probes that checks the /health endpoint.</p><p>The Service exposes the application using a LoadBalancer, mapping port 80 externally to port 8000 inside the container, allowing external access to the API.</p><p>You should now be able to get the IP address of load balancer using the command below</p><pre>kubectl get service</pre><p>Expected Outcome</p><pre>NAME                          TYPE           CLUSTER-IP     EXTERNAL-IP     PORT(S)        AGE<br>incident-classifier-service   LoadBalancer   10.0.177.150   34.120.45.78    80:30879/TCP   5m<br>kubernetes                    ClusterIP      10.0.0.1       &lt;none&gt;          443/TCP        10m</pre><p>Test the API using the command below:</p><pre>curl -X &#39;POST&#39; &#39;http://34.120.45.78/predict/&#39; -H &#39;Content-Type: application/json&#39; -d &#39;{&quot;description&quot;: &quot;Server is not responding&quot;}&#39;</pre><p>Expected outcome 🤞</p><pre>{&quot;category&quot;: &quot;Server Issue&quot;}</pre><p><strong>Next Steps</strong></p><p>This was my first machine learning project, and I really enjoyed learning about the fundamental concepts. I want to dive deeper into ML concepts and explore how ML-related infrastructure is built. The ML-Ops space is also seems quite exciting.</p><p>For the Azure infrastructure part of this project, I want to deploy it using Infrastructure as Code (IaC) tools with GitHub Actions. I also plan to explore AKS further by building and deploying more applications and APIs on it.</p><p>This was just a proof of concept, and I had a great time working on it. If you’re working on something similar, feel free to test it out. Any feedback, comments, or questions are welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de4e925670ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Azure SDK for Go]]></title>
            <link>https://medium.com/@suhail_nepal/getting-started-with-azure-sdk-for-go-6aae9ba9e8ee?source=rss-29bb791406e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6aae9ba9e8ee</guid>
            <dc:creator><![CDATA[Suhail Nepal]]></dc:creator>
            <pubDate>Thu, 23 Jan 2025 13:36:51 GMT</pubDate>
            <atom:updated>2025-01-23T13:36:51.184Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s been a while since I have posted anything here, I have recently started a new role and been learning Golang. In this blog post, I will show you initial steps of using the Azure SDK for Go, demonstrating with a simple example how to list blobs from an existing Azure Storage account.</p><p>I have tried my best to make this a starter guide and tried to address all the queries I had when I first started using it.</p><h3>Why Go ?</h3><p>Go has been very popular in the DevOps and SRE community for quite some time now, and I’ve always wanted to learn it. Its robust standard library, combined with features like concurrency, parallelism, and garbage collection, make it particularly appealing. I am still exploring concurrency and plan to write a blog post dedicated to it soon. Also, not to forget documentation for GO is amazing, and most documentation can be found <a href="https://go.dev/doc/">here</a></p><p>My interest in Golang grew when I learned about the Azure SDK for Go, allowing me to combine my learning journey with practical applications in Azure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*hajmApuXowie4Z6_InbhRQ.png" /></figure><h3>Azure SDK for GO</h3><p>Let’s get straight into it, the AZ SDK for Go is a set of client libraries to interact with different Azure services. These libraries provide a programmatic interface with Azure services, making it easier to automate, manage the resources directly from Go applications.</p><p>The general structure of the SDK has two parts:</p><ul><li><strong>Management plane</strong> — Starts with a prefix of arm (Azure Resource Manager). This includes a set of client libraries to create and manage resources on Azure programmatically, much like Terraform, Bicep, or ARM templates. <a href="https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager">View on GitHub</a></li><li><strong>Data plane</strong> — Starts with a prefix of az (Azure). This includes a set of libraries to interact with or manage particular services. For example, listing files on a storage account or sending messages to Event Hub. At the time of this writing, there are only a handful of data plane libraries published. <a href="https://github.com/Azure/azure-sdk-for-go/tree/main/sdk">View on GitHub</a></li></ul><p>You can find the entire list <a href="https://github.com/Azure/azure-sdk-for-go/tree/main/sdk">here</a></p><p>For most GO programmers, goto place for packages is <a href="https://pkg.go.dev/">https://pkg.go.dev/</a> and look for documentation. For Azure SDK for go, this will link you to the above mentioned Github pages.</p><h3>Authentication</h3><p>Authentication is the most vital part of the interaction process, and I have used azidentity packages from the <a href="https://medium.com/%5Bgithub.com/Azure/azure-sdk-for-go/sdk/azidentity%5D(%3Chttp://github.com/Azure/azure-sdk-for-go/sdk/azidentity%3E)">module</a></p><p>This package initiates token-based authentication, and the function NewDefaultAzureCredential is designed to work across different environments via predefined authentication method, in my use it is az-cli.</p><p>You can also use chain based authentication ChainedTokenCredential which can link multiple credential instances to be tried sequently when authenticating. For instance, in a local environment, if you&#39;ve authenticated via the Azure CLI with az login, ChainedTokenCredential will automatically pick up those credentials, simplifying the development process. Alternatively, in an Azure-hosted environment like a VM with a managed identity, it will use that identity without needing any additional setup from your side. This flexibility ensures that your Go application can authenticate against Azure services with minimal configuration changes across development, testing, and production environments.</p><p>This flexibility ensures that your Go application can authenticate against Azure services with minimal configuration changes across development, testing, and production environments.</p><p>The documentation for azidentity package is very well written <a href="https://medium.com/%5Bpkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity%5D(%3Chttps://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#section-readme%3E).">link</a></p><pre>func main() {<br> // Create a default Azure credential<br> cred, err := azidentity.NewDefaultAzureCredential(nil)<br> if err != nil {<br>  log.Fatal(err)<br> }</pre><p>NewDefaultCredentials creates a default authentication, pass nil for options to accept defaults.</p><p>Also, there is also an option to use connection string client, but please don’t use it :)</p><h3>Clients</h3><p>Creating a service client is another step taken before interacting with a particular service.</p><p>In the following example, once we are authenticated, we use it to initiate a serviceclient for Blob Storage.</p><pre> // Create a default Azure credential<br> cred, err := azidentity.NewDefaultAzureCredential(nil)<br> if err != nil {<br>  log.Fatal(err)<br> }<br><br> // Define the service URL<br> accountName := &quot;****&quot;<br> containerName := &quot;***&quot;<br> serviceURL := fmt.Sprintf(&quot;https://%s.blob.core.windows.net/&quot;, accountName)<br><br> // Create a new service client<br> serviceClient, err := azblob.NewClient(serviceURL, cred, nil)<br> if err != nil {<br>  log.Fatal(err)<br> }<br><br> // Create a new container client<br> containerClient := serviceClient.ServiceClient().NewContainerClient(containerName)</pre><p>In the example above, ServiceClient provides a broader, account-level interaction while the containerClient offers more focused, container-level interaction, hence the distinction is necessary.</p><p>In my case, I have hardcoded the account name, container name, again not a good practice. If you are running it on a local environment, the recommended approach is to use environment variables. os.Lookup(&quot;Azure_Storage_Name&quot;)</p><h3>Code Walk through</h3><p>It’s a very simple code, which interacts with Azure Storage account and list down all the files in a blob.</p><p>You can find the entire code <a href="https://github.com/suhailnepal/goJourney/blob/main/Azure_SDK/main.go">here</a></p><p>The following modules are imported.</p><pre>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br><br> &quot;github.com/Azure/azure-sdk-for-go/sdk/azidentity&quot;<br> &quot;github.com/Azure/azure-sdk-for-go/sdk/storage/azblob&quot;<br>)</pre><p>Once authentication is complete and service, blob clients are created, it will list down all blobs in the container using pager</p><pre>func main() {<br> // Create a default Azure credential<br> cred, err := azidentity.NewDefaultAzureCredential(nil)<br> if err != nil {<br>  log.Fatal(err)<br> }<br><br> // Define the service URL<br> accountName := &quot;rggolangstorage&quot;<br> containerName := &quot;test&quot;<br> serviceURL := fmt.Sprintf(&quot;https://%s.blob.core.windows.net/&quot;, accountName)<br><br> // Create a new service client<br> serviceClient, err := azblob.NewClient(serviceURL, cred, nil)<br> if err != nil {<br>  log.Fatal(err)<br> }<br><br> // Create a new container client<br> containerClient := serviceClient.ServiceClient().NewContainerClient(containerName)<br><br> // List blobs in the container<br> pager := containerClient.NewListBlobsFlatPager(&amp;azblob.ListBlobsFlatOptions{})<br><br> fmt.Println(&quot;All blobs in the container:&quot;)<br> for pager.More() {<br>  resp, err := pager.NextPage(context.TODO())<br>  if err != nil {<br>   log.Fatal(err)<br>  }<br>  for _, blob := range resp.Segment.BlobItems {<br>   fmt.Println(&quot;Blob name:&quot;, *blob.Name)<br>  }<br> }<br><br> // Example of listing blobs with a prefix<br> fmt.Println(&quot;\nBlobs with prefix &#39;test&#39;:&quot;)<br> listBlobsFlatOptions(serviceClient, containerName, &quot;test&quot;)<br>} </pre><p>When listing items, Azure SDK modules uses pagers to display output in a paged results. We need to iterate through the pages, and can access all blobs in the container.</p><p>Also, when listing items from a blob using the SDK, we can opt for a flat listing structure (which is what I’ve done) or a hierarchical listing structure, more detail <a href="https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blobs-list-go">here</a></p><pre>func listBlobsFlatOptions(client *azblob.Client, containerName string, prefix string) {<br> // List the blobs in the container with a prefix<br> pager := client.NewListBlobsFlatPager(containerName, &amp;azblob.ListBlobsFlatOptions{<br>  Prefix: &amp;prefix,<br> })<br><br> fmt.Println(&quot;List blobs with prefix:&quot;)<br> for pager.More() {<br>  resp, err := pager.NextPage(context.TODO())<br>  if err != nil {<br>   log.Fatal(err)<br>  }<br><br>  for _, blob := range resp.Segment.BlobItems {<br>   fmt.Println(*blob.Name)<br>  }<br> }<br>}</pre><p>The function listBlobsFlatOptions uses the Azure SDK&#39;s pager to list blobs in a container with a specified prefix. It iterates through the pages returned by the pager to print out the names of all blobs that matches the prefix. In my example above, when we called the function, our prefix is test</p><h3>Setup</h3><p>az login —&gt; Authenticate to Azure using creds which has access the storage account (existing), make sure that the identity has blob access on the storage account as well.</p><p>go mod init modulename —&gt; This initialises the module in the working directory creating a go.mod file that will manage dependencies for your Go project.</p><p>go get [github.com/Azure/azure-sdk-for-go/sdk/azidentity](&lt;http://github.com/Azure/azure-sdk-for-go/sdk/azidentity&gt;) —&gt; This command fetches and adds the azidentity package from the Azure SDK for Go, which is used for authentication with Azure services.</p><p>go get [github.com/Azure/azure-sdk-for-go/sdk/storage/azblob](&lt;http://github.com/Azure/azure-sdk-for-go/sdk/storage/azblob&gt;) —&gt; This fetches and adds the azblob package, which provides the client libraries to interact with Azure Blob Storage.</p><p>go run main.go → Run the main code.</p><p>As prerequisites, to run this code, you must have an existing Azure storage account and container, with appropriate access permissions on these resources.</p><p>Additionally, you need to have the Azure CLI (AZ-CLI) installed and configured on your system for local authentication.</p><h3>Next Steps</h3><p>Well, I have just started on Azure SDK for GO and continue to fine tune this code as I learn more about best practices. At some stage, I want to include concurrency in my codebase using goroutines to handle operations like blob uploads or downloads in parallel. Additionally, I plan to explore the use of multiple channels to manage different types of data flows to coordinate between different aspect of the code. Stay tuned !</p><p>Lastly, thank you for reading this blog post, any queries, feedback is highly appreciated.</p><p>Aspiring Gopher!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6aae9ba9e8ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Bicep 101]]></title>
            <link>https://medium.com/@suhail_nepal/azure-bicep-101-10cb93b3d1fd?source=rss-29bb791406e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/10cb93b3d1fd</guid>
            <category><![CDATA[azure-bicep]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Suhail Nepal]]></dc:creator>
            <pubDate>Sat, 16 Dec 2023 01:22:42 GMT</pubDate>
            <atom:updated>2025-02-15T12:42:53.009Z</atom:updated>
            <content:encoded><![CDATA[<p>I had recently given a presentation on best practices for using Bicep, here is the content</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fh5aN8qaWSao57XdZLFw1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rok8eTqptJGMEXKHXO2_0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mEn1frBt3mK-QjV8v9XMCw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTtYc3R_VnZe8Kup6-YHnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wdn_i8NNtqo7kTdUR40eLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTVYLlFbmQr89qkV3Do7Ng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-t6M42ZuLuGu4kwUmKGU9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5dUc1Rb-Ly7Nl0QT-KCbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9aHzAk5-0jvwffKXm_azGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g07O30xk6IAPsxxdCOrP_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B68qHEvZ8t_aP2QUvTImaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JlfCoqN6QQ-krFeGOPxSIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sqVCMcvlbnxrkxIjNNoyCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DRqo-YJJVijSbv4rMMskrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NmkkRPZkHAW-4qPydpjf7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_ZKdCfzd3jX4naPsBE-Gg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2yddCC386ynwThzR-VHj1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hGUlO30Li39sxH4Wmr-xOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCDd9YamUP9K-_Oz1A6lDA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10cb93b3d1fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hub and Spoke Network in Azure]]></title>
            <link>https://medium.com/@suhail_nepal/hub-and-spoke-in-azure-4102a1b7cb1a?source=rss-29bb791406e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4102a1b7cb1a</guid>
            <dc:creator><![CDATA[Suhail Nepal]]></dc:creator>
            <pubDate>Tue, 19 Sep 2023 14:12:41 GMT</pubDate>
            <atom:updated>2023-09-19T14:19:07.781Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I am going to write about setting up simple hub and spoke network in Azure. This was part of a POC which I had implemented to learn more about different Azure services.</p><p>Before you read the whole article, there are few considerations:</p><p>* The implemenation was done using clickops method (from Azure portal), it is highly recommended to use IAAC (Infrastructure as a code) with CI/CD. <br>* All the resources were deployed in AustraliaEast region. <br>* All the resources were created in the same subscription and resource group. <br>* I haven’t used NAT gateway which is again highly recommended for outgoing traffic. <br>* Lastly, I have created only 1 spoke for this implementation.</p><h4>Topology</h4><p>The network topology diagram is very simple, I have setup 2 VNets with the following details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*5FFZabACufuCNOVW7R194w.jpeg" /></figure><ul><li><strong>Hub Vnet</strong><br>Address Space: 10.1.0.0/16</li><li><strong>Spoke Vnet</strong><br>Address Space: 10.2.0.0/16</li></ul><h4>Implementation</h4><p>Azure Firewall has been setup in the hub Vnet and the Windows VM has been setup in Spoke Vnet. As part of this implementation, we are forcing all outgoing traffic from the Windows VM to the internet via firewall. Similarly, we want to RDP into the Windows VM from the firewall.</p><p>Please follow the steps below in order to complete the setup:</p><h4>VNET</h4><p>2 Vnets were created, one for hub and the other for spoke with the following details:</p><ul><li><strong>Hub Vnet</strong><br>Address Space: 10.1.0.0/16<br>Subnets: <br> * AzureFirewallSubnet: 10.1.1.0/24<br> * AzureFirewallManagementSubnet: 10.1.0.0/24</li><li><strong>Spoke Vnet</strong><br>Address Space: 10.2.0.0/16<br>Subnets: <br> * VM_Subnet: 10.2.0.0/24</li></ul><p>These Vnets were peered with each other with default configuration, once peered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y0Wkfg5JQ0fu5-wpld6b0w.png" /></figure><h4>Network Security Group (NSG)</h4><p>A default NSG was created in the spoke network and was attached in the subnet VM_Subnet , I didn’t change any rules in the VNET and left all the default configuration as is.</p><h4>Virtual Machine</h4><p>The next step was to create a virtual machine, again I chose a very simple Windows VM with the following configuration:</p><ul><li>Name: windowstest<br>OS: Windows Server 2016 Datacentre<br>Size: Standard B2s<br>Virtual network/subnet: spoke/VM_Subnet<br>Private IP: 10.2.0.4</li></ul><h4>Azure Firewall</h4><p>AzureFirewall was created in the hub VNET with the following configuration: <br>Please note that AzureFirewallSubnet and AzureFirewallManagementSubnet needs to be created in advance before you can setup AzureFirewall. Also you will need two Public IPs created for the firewall and managementIP.</p><p>Name: hubfirewall<br>SKU: Basic<br>Private IP: 10.1.1.4<br>FirewallPolicy: firewallpolicy (A new firewall policy was created and has been discussed below)<br>PublicIP: 68.218.*.* (New) <br>ManagementIP: 68.218.*.* (New)</p><h4>Route Table</h4><p>Route table was setup in the spoke VNET with the following rules:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rti-oyBZlaiIKaSMTXtyHA.png" /></figure><p>The idea here was that we wanted to route all internet traffic from the spoke network via the firewall. In the above, virtual appliance is the firewall and the private IP address of the firewall.</p><p>This Route table was later associated with the subnet VM_Subnet where the Windows VM is hosted.</p><h4>Firewall Policy</h4><p>This is probably one of the important step here and took me a while to figure it out as well. Now, we know that internet traffic will be routed from the spoke network to the firewall, we need to setup approriate policy in the firewall so that the firewall knows how to route the traffic.</p><p>With the firewall policy, created above (when creating a firewall), the following rules were added: I have used the default collection group for all the rules here.</p><p>Network Rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7V3YxRZk8NkSjvlYi4ONTw.png" /></figure><p>This was setup, so that the DNS traffic can be routed through external servers, 209.244.0.3,209.244.0.4.</p><p>DNAT Rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DPTl6kQF49yH_AoTcc9-jg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WAlthWDgCIW2-5eIxgLB7w.png" /></figure><p>In the above, source IP 194.193.*.* is my home IP address. 4000 was a random port number chosen. Destination IP 68.218.*.* is the public IP of the firewall and 10.2.0.4 is the VM’s IP. Translated port is the default RDP port 3389.</p><p>Once the above was setup, I was able to RDP into the VM through the firewall. While connecting, my hostname was 68.218.*.*:4000</p><p>Application Rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2ccnOKTuoKIgVMy6fpVjg.png" /></figure><p>This application rule was setup so that the VM could only reach out to google.com on port 80 and 443. The source IP is the VM_Subnet IP range where the VM is hosted.</p><h4>DNS Setup</h4><p>This is an optional step, I configured DNS on the network interface of the VM with the IPs 209.244.0.3,209.244.0.4. Again, this can also be configured at a VNET level.</p><h4>Testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*HOc510ExdqfM1CKK0oEeXA.png" /></figure><p>While the above input on Windows Desktop app, I was able to RDP into my Windows VM from my home network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*623F61noY2FBWG4Ubbi-Lg.png" /></figure><p>I was able to access google homepage on port 443.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KpWK6wbBQWhdrKLmI7yxiA.png" /></figure><p>When I tried any other URL, I got the above message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*mO7XGRz2q29rPbKJudOokw.png" /></figure><p>The next step was to identify the next hop that the VM takes when reaching out to the internet. I used the inbuilt tracert tool on cmd on Cloudflare’s IP, the first hop was 10.1.0.5, this is the IP from AzureManagementFirewall Subnet.</p><h4>Next steps</h4><p>Well, this was a simple implementation of hub and spoke and can be improved further. First thing first, I will be doing the same using IAAC (probably Bicep) on Azure devops for CICD. Also I want to setup multiple spokes with probably a NAT gateway for outbound traffic.</p><p>Any feedback/comment highly appreciated, it’s all part of learning :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4102a1b7cb1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AZ-104 Cert Renewal]]></title>
            <link>https://medium.com/@suhail_nepal/az-104-cert-renewal-139016439655?source=rss-29bb791406e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/139016439655</guid>
            <dc:creator><![CDATA[Suhail Nepal]]></dc:creator>
            <pubDate>Tue, 16 May 2023 03:41:47 GMT</pubDate>
            <atom:updated>2023-05-16T03:47:07.283Z</atom:updated>
            <content:encoded><![CDATA[<p>This is going to be a short post on how I renewed my Azure-104 certification. Things I will cover here are around topics like Microsoft certification renewal process, preparation, topics to cover, expected questions etc.</p><p>It has been a while since my last post as I have been heavily engaged with ongoing projects. However, I have also been taking some much-needed downtime to spend quality time with my beloved doggo on weekends. As much as we love technology, it’s equally important to disconnect and relax just to unwind and rejuvenate our minds and bodies. I wasn’t feeling well for last few days and decided to take few days off from work and felt that this is perfect time to renew my cert.</p><p>Btw Simba is still here with me in my bed accompanying me while I write this…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vRzzct-8ovFhqf42xtmMrg.png" /></figure><h4>Cert Renewal Process</h4><p>I received an email from Microsoft Certification titled “Action required — Your Microsoft Certification will expire in 30 days.” I had successfully passed this exam in June 2021 and it was due for renewal next month. This process is not valid if you cert has already expired, in that case you will need to sit for the actual exam.</p><p>Upon clicking the provided link in the email, I was directed to the certification homepage. On the page for the specific exam (AZ-104) that needed renewal, I found the Renewicon.</p><p>The renewal process involved an online test with 28 multiple-choice questions. It felt more like a set of online questions rather than an actual exam, as there were no time constraints. To pass, I needed a minimum score of 40%, and fortunately, I achieved 53% (let’s blame Covid for this).</p><p>You can find more information about this test from Microsoft here &gt; <a href="https://learn.microsoft.com/en-us/certifications/renew-your-microsoft-certification">Microsoft Certification Renewal | Microsoft Learn</a></p><h4>Preparation</h4><p>As part of preparation, Microsoft gives you a list of learning modules which you can complete before you sit for the test. Some of the learning modules have hand-on lab section which makes things very interesting.</p><p>This (page) [<a href="https://learn.microsoft.com/en-us/certifications/azure-administrator/renew/">https://learn.microsoft.com/en-us/certifications/azure-administrator/renew/</a>] has the list of all learning modules.</p><p>I deep dived into modules which covered the following topics:</p><ul><li>Azure Webapp (With hands on lab)</li><li>Docker/Containers/Azure Container Service</li><li>Securing Storage Account</li><li>Basic Networking (Mainly around Vnets and NSG)</li></ul><p>I have been using Azure for a while now so most of the things covered in these modules were more like a revision for me.</p><h4>Questions</h4><p>Don’t quote on me this, I found the exam relatively simpler than the actual test. Also it’s not as stressful as the real exam as there is no time constraint and there is no one watching you coughing/blinking your eyes :)</p><p>The questions were a mix of theoretical as well as scenario based. I felt most of networking questions around scenario which makes sense. Most of the questions are from the following topics (This could be different for different users).</p><ul><li>Azure webapp</li><li>General Networking (NSGs, NSG rules, vnet, subnet etc)</li><li>Azure Backup Service</li><li>Azure Storage account (General questions)</li><li>Azure Virtual machine (General questions)</li></ul><p>I immediately got the results which said I had passed and was bit relieved. I can also confirm that my cert has been renewed for another year. Anyways, that’s about about it before I start getting the covid chills again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFblPvFgqWYL9_amibWBRw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=139016439655" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide: Linux Commands Used in Devops]]></title>
            <link>https://medium.com/@suhail_nepal/linux-commands-used-in-devops-6a61aa3f433f?source=rss-29bb791406e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a61aa3f433f</guid>
            <dc:creator><![CDATA[Suhail Nepal]]></dc:creator>
            <pubDate>Tue, 28 Mar 2023 10:57:08 GMT</pubDate>
            <atom:updated>2023-03-28T11:17:11.928Z</atom:updated>
            <content:encoded><![CDATA[<p>This a guideline of some of the Linux commands that are commonly used in Devops space. I have tried my best to give a detailed explanation of each command with examples and best practices.</p><p>Please note that this page is WIP (Work in Progress) and will continue to update it as I go.</p><h3>Commands</h3><h3>free</h3><p>This command displays the amount of free and used memory of a system. In other words, it gives you a summary of phyiscal and swap memory, as well as free and used memory. Swap is a space on the disk which is used when the amount of physical RAM is full. By default swap partition is not present and only has swap files.</p><p>These are the fields that shows up by default:</p><ul><li>total: Total memory which can be used by the application</li><li>used: Total memory which has been used total - free - buffers - cache</li><li>free: Free memory</li><li>shared: NA</li><li>buff/cache: -w flag can dissect buff/cache into buffer and cache separately. More about buffer and cache below.</li><li>available: An estimate of total memory which be used for new application.</li></ul><p>Cache is used to store frequent data whereas buffer is used only once to improve the efficiency of the process such as data transfer.</p><p>There are multiple flgs you can use with free without any flags it will give the output in kilobytes.</p><p>Some of the frequently used flags could be:</p><p>free -m: Gives you the output in MB free -h: Gives the output in human readable format</p><h3>du / df</h3><p>du is used to find information on disk usage. If you want to find disk usage information for a particular folder you can use du {folder}.</p><p>Some of the most used flags are:</p><p>du -h: Gives output in human readable format. du -h -m: Gives output in MB in a human readable format.</p><p>df is used to find information on free disk space. df gives you an output for all mounted disk on the system.</p><p>Some of the most used flags are:</p><p>df -h: Gives output in human readable format. df -h --total: You can use this option when all mounted filesystem are on the same system.</p><h3>rsync</h3><p>This command is used to transfer a file/directories to a location over a shell. It is fast and provides differential transfer by only transferring the difference between source and destination.</p><p>This is pre-installed tool depending on your Linux distro, but if not it can be easily installed using your distribution package manager sudo apt install rsync or sudo yum install rsync</p><p>The basic syntax of rsync command is rsync options source destination</p><p>Some of the commonly used flags in rsysnc are:</p><p>-v: verbose -r: copies file recursivelt -a: archive mode -z: compress file data -h: human readable format — max-size: Set the max size for file transfer — include: you could use it for file extenstion ‘*.txt’ — exlude: can be used to exclude file — remove-source-files: remove source file after rsync is complete — dry-run</p><p>In the following example, we are copying file from existing directory into a new directory</p><p>rsync -zvh file1 fold1/ If the destination does not exists, rysync will create that destination folder as well.</p><p>To copy a file on a new machine, you can use the following command: rsync -avzh /fold1 root@192.168.0.1:/root/ This will copy the content of the folder in the home directory of root user.</p><p>To copy a file from a remote server using sshm you can use the following command: rsync -avzhe ssh root@192.168.0.1:/root/file1 /tmp</p><p>It’s highly recommended to use dry run before you rsync, the output will tell you what will be synced across: rsync --dry-run -zvh source destination</p><h3>top</h3><p>This command will show you the list of Linux processes. This is supposed to be a summary page and as soon as you type top, it will show you a dashboard of running processes in the Linux Kernel. You can type q to quit from the summary page.</p><p>The following columns are shown in the top dashboard:</p><p>-PID: Task unique process ID -PR: Process priority, the lower the number the higher is the priority -VIRT: Total virtual memory used by the task -USER: Owner of the task -%CPU: CPU usage -TIME: CPU time -SHR: Shared memory in KB used by a task -NI: Nice value of a task, a negative NIC implies higher priority and positive NI represents lower priority. -%MEM: Memory usage of a task -RES: How much physical RAM is the process using -COMMAND: The name of the command that stated the process.</p><p>This <a href="https://www.redhat.com/sysadmin/interpret-top-output">link</a> has all the detailed informaton on what the first 4 lines of the summary page.</p><p>Some of the most used commands are listed below</p><p>top -u suhail This command will list all the process for the user Suhail</p><p>top -s Runs in secure mode and has to run with root priveleges. By default top opens the console in interactive mode with full access to the system. In secure mode some information such as process owner and command line is hidden by default. Overall running top command in secure mode is good practice to enhance security and ensure that only authorised users have access to sensitive information.</p><h3>ps</h3><p>This command is used to display or view information related to processes running in a Linux system. The output of PS will have the following output</p><p>-PID: Unique process ID -TTY: The type of terminal that the user is logged into -Time: Time for which the process has been running for -CMD: The command that launches the process.</p><p>Some of the commonly used commands are listed below:</p><p>ps ax This will display all current running processes ps aux This will display the processes in BSD format ps -ef This will display the processes in full format list ps -u suhail This will diplay processes for user suhail ps -fG group_name: This will display processe for a group</p><h3>lsof</h3><p>This command will list all open files (as per man)</p><p>Some of the most used commands are below:</p><p>lsof -u suhail: Displays open file for user suhail lsof -i TCP:22: Displays process running on specific port 22 lsof -i 4: Shows IPv4 network files opened, 6 can be used for IPv6 lsof -i TCP:1-1024: Open files of TCP Port range from 1-1024 lsof -i -u^root: Exclude a particular user root lsof -i: Shows the list of all network connections Listening and Established</p><h3>uptime</h3><p>This is simple command which tells you the system uptime.</p><p>Some of the commonly used uptime commands are:</p><p>uptime -p: Pretty flag uptime -s: Uptime since</p><h3>dmesg</h3><p>This will display kernel-related messages used to control Kernel ring buffer. The output contains messages produced by the device drivers.</p><p>This <a href="https://www.howtogeek.com/449335/how-to-use-the-dmesg-command-on-linux/">link</a> has detailed explanation on how Linux’s Ring Buffer works.</p><p>dmesg has to be used with root privleges</p><p>Some of the frequently used commands are:</p><p>sudo dmesg -l info Extracting messages using -l level to list all informational messages sudo dmesg -l debug,notice Extracting messages (combining debug and notice) to extract debug and notice sudo dmesg --level=err,warn Extracting messages with error logs and warning messages sudo dmesg | grep -i eth0 Extracting message for eth0 user interface</p><h3>netstat</h3><p>This command gives you information about network connections, the ports that are in use, and the processes which are using them.</p><p>If this tool is not installed, you can install it by using the command</p><p>sudo apt install net-tools (Debian)</p><p>Some of the commonly used netstat commands are listed below:</p><p>netstat -a Output all connected and waiting sockets netstat -at All TCP connection netstat -au All UDP connection netstat -l Sockets that are in listening state netstat -st Statistics options with TCP netstat -p -at Shows process names and PID netstat -r This shows the routing table netstat -i Shows all network interfaces</p><h3>ss</h3><p>As per man, this is another tool to investiage sockets on a Linux machine. This is used for gathering network information and troubleshooting network issues.</p><p>The output of ss will list down all the open sockets (non listening) with established connections.</p><p>The output column shows the following:</p><ul><li>Netid: Type of socket, TCP, UDP, u_str (Unix stream), u_seq (Unix sequence)</li><li>State: Listening, Established</li><li>Recv-Q: Packets Received</li><li>Send-Q: Packets sent</li><li>Local address port: Address of local machine and port</li><li>Peer address port: Remote machine and port</li></ul><p>Some of the commonly used ss commands is listed below:</p><p>ss -a : Shows all listening and non-listening connections ss- l: Shows listening sockets ss -t: Shows TCP connections ss -u: Shows UDP connections ss dst 1.1.1.1: Filters by destination IP ss src 1.1.1.1: Filters by source IP ss -p: Shows process ID use</p><p>SS Vs netstat: SS seems to be a popular tool for networking stats and can also be seen as an alternative to netstat, it is lightweight, faster and has better filtering options.</p><h3>strace</h3><p>This command will trace for system calls and signals (as per man). This command is useeful when the source code is not readily available and can be used to intercept and records any syscall made by a command.</p><p>For example if you type strace ls, it will intercept and records all syscalls made by this command.</p><p>Some of the widely commands are listed below:</p><p>strace -t whoami: Records timing and duration information strace -c whoami: Gives statistics and reports it</p><p>You can also format the output and use regex expressions with strace</p><p>strace -e trace=fstat whoami: This filters to output only fstat syscalls.</p><h3>tcpdump</h3><p>This is another popular network diagnostic tool used for network analysis.</p><p>Let’s start with something very basic:</p><p>tcpdump -i eth0 will give you network traffic information on interface eth0. You need to hit CtrL+C/Z to exit from the terminal.</p><p>tcpdump host 8.8.8.8: This will listen for traffic coming or going out to 8.8.8.8</p><p>You can filter it by source or destination using:</p><p>tcpdump src 1.1.1.1 tcpdump dst 1.1.1.1</p><p>If you want to listen to traffic from a particular network:</p><p>tcpdump net 1.2.3.4/24</p><p>If you want to listen to traffic from a specific port</p><p>tcpdump port 22 tcpdump src port 22</p><p>With TCPDUMP, you can use the following flags to combine multiple entries together:</p><ul><li>AND</li><li>OR</li><li>EXCEPT tcpdump dst 1.1.1.1 and src net and not icmp</li></ul><p>There are much more advanced features of tcpdump which will cobvered later here.</p><h3>sar</h3><p>This command is used to get performance statics of different metrics for both real time and historical data.</p><p>It does not come by default on most linux distros, but can be easily installed using the following commands</p><p>sudo apt install sysstat sudo dnf install sysstat</p><p>It’s also a good idea to enable and start this process after you have finished installing it.</p><p>sudo systemctl enable sysstat sudo systemctl start sysstat</p><p>Start with the following command</p><p>sar -u 2 3</p><p>This shows CPU stats in steps of two seconds for three sets of data.</p><p>sar -P 1 1 3</p><p>This will show thress sets of data with 1 second between them for core 1.</p><p>sar -b 4 3</p><p>This show I/O transfer data for 3 data with 4 seconds in between them.</p><h3>vmstat</h3><p>This is another popular tool to report on virtual memory statistics.</p><p>This <a href="https://access.redhat.com/solutions/1160343">link</a> has useful information on how to read the ouput of vmstat command.</p><p>The basic syntax of vmstat looks like this: vmstat [options][delay [count]]</p><p>Some of the widely popular vmstat commands are listed below:</p><p>vmstat -a: Replaces buff and cache memory with active and inactive vmstat -s: More detailed information vmstat -d: Quick disk statistics vmstat -t: Adds Timestamp information</p><h3>iostat</h3><p>This tool is used for monitoring system I/O device loading as well CPU statistics.</p><p>If you type iostat without any flags, it will output CPU and I/O information for every partition of file system</p><p>If you want the output in MB, you can type iostat -m</p><p>The following colummns are shown in output:</p><p>tps: Number of transfer per second that was issued. Blk_read/s: The amount of data read from the device Blk_wrt/s: The amount of data written to the device Blk_read: The number of blocks read Blk_wrtn: The number of blocks written</p><h3>pidstat</h3><p>This is tool used to report statitics on Linux task. This can either monitor a specific PID or all the processes running on a system.</p><p>If you use pidstat -p ALL, this will report performance montoring stats for all the proess.</p><p>If you want to run it against a particular process, you will can type pdstat -p 1234 where 1234 is the PID</p><p>If you know the name of the process, you can type pdstat -C &quot;httpd&quot; where httpd is the name of the process</p><p>If you want to repeat this in certain interval, you can run pdstat -p 1234 1 (repeats every second)</p><h3>mpstat</h3><p>As per man, mpstat is a tool used to report on processors related statistics. This will accurately display the statics of CPU usage of the system.</p><p>You can run mpstat without any flag but if you type mpstat -P ALL, this will give you an ouput all the processor in the system.</p><p>The following command will display the processor number of all the CPUs working mpstat -A</p><p>If you want to filter it by specific proessor, you can type mpstat -P 0 This will show an output for 0th processor.</p><h3>uname</h3><p>This tool is used to print system information of a Unix system.</p><p>This command will can be further combined with the following flags to find further information of the system.</p><p>-s: Kernel information -n: Node name -r: kernel release -v: kernel version -m: hardware name -p: processor architecture -i: hardware platform -o: operating system -a: all the above information</p><h3>grep</h3><p>This is the most commonly used search tool in Linux which prints output based on string and pattern matching. It’s widely used by pipe command.</p><p>A simple example could be: Let’s say you have a file with a,b and c in three lines. If you type cat filename | grep a, it will show the output a. Alternatively you can run grep a filename</p><p>Some of the most commonly used grep commands are listed below:</p><p>grep -i: case insensitive grep -r: recursive grep -R: recursive dereference grep -v: Invert match grep -E: Extended regexp</p><p>You can use a combination of grep in a simple command</p><p>grep -i -r filename</p><p>While the command for both grep and fgrep is the same: grep [options] pattern [files] fgrep [options] pattern [files]</p><p>The basic difference between these are:</p><ul><li>fgrep interprets the Pattern as a list of fixed strings separated by newlines but grep has always been interpreted as regular expressions.</li></ul><h3>find</h3><p>This is another popular tool which is constantly used to search for a file in directory hirarchy.</p><p>A simple use case is find . -name filename This will search for filename in your current directory.</p><p>I find this command quite handy when working on Git repositories where I have work from the main directory. (This could be for multiple reasons)</p><p>Some of the most commonly used flags are listed below:</p><p>find ./root -name *.txt : Search with a pattern find ./root -name file.txt -exec rm -i {} \; Find and delete (USE with Caution) find ./root -empty Search for empty files and directories find ./root -perm 224 Search for file with given perm 224</p><h3>sort</h3><p>As the name suggests, this tool is used to sort lines of a text file.</p><p>Let’s say for example, if you have file with the following content f x q</p><p>If you type in sort filename, it will sort the filename in alpabhetical order. Similarly if you have a file with integars, it will arrange in ascending order. If you have a file with a combination of strings and integars, it will sort both string and integar but will output the integar first followed by string.</p><p>Please note that sort by default does not change the output of the file. You will need to use sort filename &gt; filename2</p><p>Some of the commonly used flags are:</p><p>sort -r Reverse order sort -nr: Reverse numerical order sort -c: Checks if the file is already sorted sort -m: Sort by month</p><h3>head</h3><p>This tool is used to display first lines of a file. If you have file with multiple lines, and if you type head filename it will show the first 10 lines of the file.</p><p>Some of the widely used head commands are listed below:</p><p>head -n 5: Number of lines to output head -c 6: Prints the num bytes from the file specified head -q: Quite mode head -v: Verbose</p><h3>tail</h3><p>This is a reverse of head and will print out the last line of the filesystem.</p><h3>tar</h3><p>This is an archiving utility used to archive and extract the archived files.</p><p>The basic syntax of tar looks like this: tar [options] [archive-file] [file or directory to be archived]</p><p>The following options can be used: -c : Creates Archive -x : Extract the archive -f : creates archive with given filename -t : displays or lists files in archived file -u : archives and adds to an existing archive file -v : Displays Verbose Information -A : Concatenates the archive files -z : zip, tells tar command that creates tar file using gzip -j : filter archive tar file using tbzip -W : Verify a archive file -r : update or add file or directory in already existed .tar file</p><p>tar cvf file.tar *.c The above command will create a tar file file.tar with the archive of all .c files in the current directory.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a61aa3f433f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Howto: Clean up Azure Resources on Schedule]]></title>
            <link>https://medium.com/@suhail_nepal/howto-clean-up-azure-resources-on-schedule-3c84c28013f1?source=rss-29bb791406e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c84c28013f1</guid>
            <category><![CDATA[azure-cli]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Suhail Nepal]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 09:59:16 GMT</pubDate>
            <atom:updated>2023-02-05T11:30:35.377Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to: Clean up Azure Resources on Schedule</h3><p>If you are like me and use your Azure account for test purposes and want to clean up resources on a schedule to avoid that extra cost, this could be helpful for you. There have been many instances where I have deployed resources from the portal and completely forget about nuking it. Please be very <strong>careful</strong> before using this script as it will delete all resources in a subscription, this depends on how you set up the subscription and this is just a guide. I will link all resources at the bottom of this article.</p><p>The tech stack for this method is straightforward. You will have a bash script (with AZ CLI) in the Azure DevOps repo which lists down all the resource groups in a subscription and deletes resources within that subscription. This script will run within Azure DevOps in the ubuntu-latest image and we will enable it to run on cron at 12 am every day. At the moment, this is limited to resources in one subscription and I haven’t considered things like a lock, delete protection, etc, this is something I will be testing out very soon.</p><p>I have divided this how to guide in three main sections:</p><ul><li>Prerequisites</li><li>Azure Devops Repo</li><li>Azure Devops Pipeline</li><li>Resources and Links</li></ul><h4>Prerequisites:</h4><p>I will start with the very basics, you will need an Azure account, with a billing profile and valid subscriptions. You also need a valid Azure DevOps account with parallelism enabled. Since I have a free tier account on Azure DevOps, I had to raise a ticket with Microsoft to enable this for me, the turnaround time was 2–3 days which was decent.</p><h4>Azure Devops Repo:</h4><p>Like any other version control system (Github, Gitlab, etc), Azure DevOps Repo is version control embedded within the Azure DevOps environment.</p><p>Please create a new repo in Azure DevOps and add the script cleanup.shin there. The link to the script is below:</p><p><a href="https://github.com/suhailnepal/azure_cli/tree/main/dailycleanup">azure_cli/dailycleanup at main · suhailnepal/azure_cli (github.com)</a></p><p>This script is written in bash and uses components of Azure CLI, please try to understand the code before you start using it.</p><p>Once you have added the code, commit and push it to the main branch. It is highly recommended to put up a README section in the repo.</p><h4>Azure Devops Pipeline:</h4><p>Before you start creating the pipeline, you will need to first create a <strong>service connection</strong> in the project. This is an authentication method that your image would use to access a resource within a subscription. This is also considered a safer method as the token are short-lived and only gets created when the connection is initialised.</p><p>Please follow the steps below to create a new service connection:</p><ul><li>Go to your project settings, and click on Service Connections</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*_6evU24-p1dFZjbwzKo0mA.png" /></figure><ul><li>Click on Create New Service Connection</li><li>Search for Azure Resource Manager (Service priniciple (automatic)) and click next</li><li>This will open up a new tab to authenticate to Azure portal, put in your credentials and login.</li><li>Back in Azure Devops portal, under scope select the subscription from where you want to delete the resources.</li><li>Give the connection a name, in my case I have called it Suhail_Subscription_January , leave the other fields as blank.</li><li>In my case, I have granted access permission to all the pipelines.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*BSMBynodZFua0-aadkmumA.png" /></figure><p>Now go back to <strong>Pipelines</strong> section and click on new Pipeline. Then follow the remaining steps as below:</p><ul><li>Where is your code ? Select Azure Repos Git</li><li>Select a repository ? Select the repository you had created in earlier step</li><li>Click on starter pipeline, this will open up a YAML text file.</li><li>Click on variables section from the top right section and create a new variable, you will need the name of your service connection here:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*DlwbJVW3dTrL1be85szgXg.png" /></figure><ul><li>Remove everything from the pipeline and replace it with the code pipeline.yaml from this repo</li></ul><p>These are the key components of the pipeline:</p><ul><li>The following code block ensures that the pipeline runs on schedule everyday at midnight</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KPZgpjwiW_MZCCwu15XwIQ.png" /></figure><ul><li>As mentioned above, I have created a variable for service connection which I have used here as $(service_connection)</li><li>The scriptPath is scriptPath is cleanup.sh which is the script that you have added in the repo</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*H2EcXK8pcbpTN-oGfNpWnw.png" /></figure><ul><li>Once verified, click on Save and run, if you are running it directly from main, you can select Commit directly to the main branch</li><li>You should now be able to view all the runs within that pipeline. You will notice that the pipeline will run on schedule as per your cron. No further action is required.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YnmuW0TQ-yWkzaqRHR5Btg.png" /></figure><h4>Resources and Links:</h4><p><a href="http://this link">Create Your Azure Free Account Today | Microsoft Azure</a></p><p><a href="https://learn.microsoft.com/en-us/azure/devops/pipelines/licensing/concurrent-jobs?view=azure-devops&amp;tabs=ms-hosted">Configure and pay for parallel jobs — Azure DevOps | Microsoft Learn</a></p><p><a href="https://github.com/suhailnepal/azure_cli/tree/main/dailycleanup">azure_cli/dailycleanup at main · suhailnepal/azure_cli (github.com)</a></p><p><a href="https://learn.microsoft.com/en-us/azure/devops/pipelines/library/service-endpoints?view=azure-devops&amp;tabs=yaml">Service connections in Azure Pipelines — Azure Pipelines | Microsoft Learn</a></p><h4>Lastly:</h4><p>I would highly appreciate any feedback and comment on this post, thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c84c28013f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure CLI | Tips and Tricks]]></title>
            <link>https://medium.com/@suhail_nepal/tips-and-tricks-azure-cli-64368c1c24f9?source=rss-29bb791406e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/64368c1c24f9</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-cli]]></category>
            <dc:creator><![CDATA[Suhail Nepal]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 07:12:41 GMT</pubDate>
            <atom:updated>2023-01-31T03:10:13.610Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been using Azure CLI for a few weeks now. To get started, I watched Azure CLI Basics/Fundamentals videos on YouTube and started writing code snippets for some of the operations tasks which I had been doing manually on the portal.</p><p>In this article, I will not be going through fundamentals and will be covering things like edge cases, tricks, and best practices (to some extent). I am only sharing my experience here and want to make it fun for others to read and follow.</p><p>This will be a working document and will update it as I go.</p><p>I will cover the following topics here:</p><ul><li>Sequencing</li><li>Finding help</li><li>Troubleshooting</li><li>Tools</li></ul><h3>Sequencing</h3><p>I run the following commands in sequence and want to make sure that the environment is up and ready before I start writing my scripts.</p><ul><li>az login</li></ul><p>To authenticate, you have a choice of using your default browser or can use any browser of your choice.</p><ul><li>az account list --all</li></ul><p>This will give you a list of all the subscriptions in the tenancy; You might want to know at a high level what subscriptions are available and which one you want to use to deploy your resources.</p><ul><li>az account set --subscription “Placeholder”</li></ul><p>In the command above, you are setting your subscription on your local profile, you have a choice of using either the subscription name or id.</p><ul><li>az group list --all</li></ul><p>Again, this is me being me, the command above is optional, it will list down all the resource groups in the subscription that you have just set.</p><h3>Finding Help</h3><p>There are multiple ways to get around this, but I think the source of truth is Microsoft Documentation for Azure CLI <a href="https://learn.microsoft.com/en-us/cli/azure/">Azure Command-Line Interface (CLI) — Overview | Microsoft Learn</a></p><p>There are quick start guides, and training materials in the link above, I had a look into a few of them, and they were easy to follow some content might be daunting if you are very new to Azure, Azure CLi world.</p><p>Coming from Bash and Linux world, man command has been my best friend and I wanted to find something equivalent to Azure CLI.</p><p>help in Azure CLI is very similar to man and you can find answers in the terminal if that’s the preferred choice.</p><p>By this stage, I assume you know the anatomy of Azure CLI, if not familiarise yourself here: <a href="https://techcommunity.microsoft.com/t5/microsoft-reactor/azure-cli-basics/m-p/3682226">Azure CLI Basics — Microsoft Community Hub</a></p><p>Let’s say for example, you want to list VMs that are deployed in a resource group, you can start with az vm --help. This will list down all the subgroups and the commands that you could use with it.</p><p>Looking at the output of the above command, let’s try this az vm list --help, you can now find information on things like flags, examples etc. The final command should look like this az vm list -g MyResourceGroup</p><p>Things that I haven’t tried are plugins in Vscode, ISE. I can write more about it when I explore them.</p><h3>Troubleshooting</h3><p>I have personally noticed that the error messages are easy to follow, most of them point you to Microsoft documentation which is cool.</p><p>There is a flag called debug which will spit out debug information when you run a command. The information given out by debug can be lengthy and if you follow it on sequence, it’s easy to read. You could use debug with something like this az group deployment list -g ResourceGroupName --debug</p><p>I was getting a very generic error message when I was trying to run a command az group deployment export --name $varname -g ResourceGroup in a loop. The error message was Operation returned an invalid status Bad Request I then started looking for debug logs and noticed that for my $varname, it had /r at the end of each item in an array. For example, if the variable had to [var1,var2], the command was taking var1\r as input.</p><p>It was a quick fix and realised the importance of using debug, I would highly recommend it for troubleshooting purposes.</p><h3>Tools</h3><p>This is something that I have been exploring for now and can talk more about it when I start using more tools. Ultimately, I want to be quicker, more productive, and more secure when using Azure CLI and these tools can be a great medium.</p><p>az interactive is an inbuilt tool that I have used, it’s mainly targeted for folks who are new to Az CLI world and needs that extra help. It gives you suggestions, when writing commands. I would say, give it a go, the interface is mad, but I loved it.</p><h3>Finally</h3><p>This is more of me sharing my journey, it might not work like in your project. This might give you a high-level overview and a good starting point on using Az CLI.</p><p>Any feedback/comment on this is highly appreciated, it’s all part of learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64368c1c24f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>