<?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 NarinderKaur Makkar on Medium]]></title>
        <description><![CDATA[Stories by NarinderKaur Makkar on Medium]]></description>
        <link>https://medium.com/@narinderkaurmakkar1?source=rss-f90561ae570f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*hI57n1CcxKV3_F3G.</url>
            <title>Stories by NarinderKaur Makkar on Medium</title>
            <link>https://medium.com/@narinderkaurmakkar1?source=rss-f90561ae570f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:38:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@narinderkaurmakkar1/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[Distributed locks]]></title>
            <link>https://medium.com/@narinderkaurmakkar1/distributed-locks-9eacc4cffeb8?source=rss-f90561ae570f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eacc4cffeb8</guid>
            <category><![CDATA[distributed-locks]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[NarinderKaur Makkar]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 07:01:21 GMT</pubDate>
            <atom:updated>2026-03-02T07:01:21.499Z</atom:updated>
            <content:encoded><![CDATA[<p>A distributed locking is a mechanism used in distributed systems to ensure that only one process, service, or node can access a shared resource at a time, even when those processes are running on different machines.</p><p>It’s like a normal lock (e.g., a mutex), but instead of protecting threads inside one program, it protects resources across multiple servers.</p><p><strong>Why do we need distributed locking?</strong></p><p>In the era of microservices and distributed processing, multiple instances of a service might try to update the same database record or process the same job or write to the same file or access a shared cache.</p><p>Without coordination between parallely running services, this can cause race conditions and data corruption. This can also increase the data inconsistency and duplicasy.</p><p>A distributed lock make sure that various machine or services are mutual exclusive while performing any write operations.</p><p>Let us take an example:</p><p>Imagine 3 instances of a payment service running on different servers. All of them try to process the same order at the same time. With a distributed lock:</p><p>One instance of the service acquires the lock(based on fifo preferences) (e.g., order-123-lock).</p><p>Other instances must wait or fail.</p><p>The first instance finishes processing.</p><p>The lock is released and available for others to consume.</p><p>Another instance can acquire the lock for its processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MU-IZD4yYU0LIEJ176Kbbg.png" /><figcaption>Distributed locking</figcaption></figure><p>Distributed locks are usually built using shared infrastructure. Some tools which can be used to implement it are:</p><ul><li>Redis (e.g., using SETNX or Redlock algorithm)</li><li>Apache ZooKeeper</li><li>etcd</li><li>Consul</li><li>Database-based locking (e.g., row-level locks)</li></ul><p>These systems act as a central authority to coordinate lock ownership.</p><p>redsync is an open-source Go (Golang) library that implements the Redlock algorithm for distributed mutual exclusion using Redis. It enables multiple processes or services to coordinate access to shared resources safely in a distributed system. One code example to use the redsync:</p><pre>client := goredislib.NewClient(&amp;goredislib.Options{<br>  Addr: &quot;localhost:6379&quot;,<br> })<br> pool := goredis.NewPool(client) // or, pool := redigo.NewPool(...)<br><br> // Create an instance of redsync to be used to obtain a mutual exclusion<br> // lock.<br> rs := redsync.New(pool)<br><br> // Obtain a new mutex by using the same name for all instances wanting the<br> // same lock.<br> mutexname := &quot;my-global-mutex&quot;<br> mutex := rs.NewMutex(mutexname)<br><br> // Obtain a lock for our given mutex. After this is successful, no one else<br> // can obtain the same lock (the same mutex name) until we unlock it.<br> if err := mutex.Lock(); err != nil {<br>  panic(err)<br> }<br><br> // Do your work that requires the lock.<br><br> // Release the lock so other processes or threads can obtain a lock.<br> if ok, err := mutex.Unlock(); !ok || err != nil {<br>  panic(&quot;unlock failed&quot;)<br> }</pre><p>A good Distributed Lock should comprise of following properties to make it reliable:</p><ul><li><strong>Mutual exclusion: </strong>Only one instance should be able to hold a lock at the given time.</li><li><strong>Deadlock safety: </strong>Locks must have a lease time (TTL — Time To Live) so they automatically expire.Without TTL, lock remains forever and can cause system to stuck in a deadlock.</li><li><strong>Fault tolerance: </strong>In distributed systems, failure is normal. The locking mechanism should continue to work even if some nodes crash or network partitions happen or minority of lock servers fail</li><li><strong>Fairness</strong>: Locks are granted in the order requested (First-Come-First-Served). It prevents starvation where one client repeatedly fails to acquire the lock.</li><li><strong>Ownership: </strong>Only the client that acquired the lock should be able to release it. Otherwise, one client might accidentally delete another’s lock.</li><li><strong>In network partitions</strong>, Two different nodes must not both believe they hold the lock. This is the hardest problem and why consensus-based systems (like etcd/ZooKeeper) are more reliable than naive Redis setups.</li></ul><p>Distributed lock make sense, when You want to ensure a single execution globally. The critical task is short and rare process. You can not achieve idempotency for some tasks and strong coordination is required.</p><p>But then there are some very important scenarios where one must try to rethink on alternatives of distributed locking or avoid it.</p><ul><li>If your operation can be made idempotent, you don’t need a lock. For example, instead of locking to prevent double payment processing, use a unique transaction ID, enforce a database unique constraint and safely retry requests.</li><li>Databases already provide strong concurrency guarantees. Instead of, acquiring a distributed lock and then updating a row, better approach would be to utilize row-level locking, transactions, optimistic locking (with versions), unique constraints.</li><li>If the operation can be made atomic, a distributed lock is unnecessary.</li><li>Distributed locks add overheads of network round trips increased contention, become bottlenecks and reducing horizontal scalability. If many instances constantly compete for one lock, system can be effectively serialized and lose scalability benefits.</li><li>If a task takes long time to complete or has unpredictable execution time, locks become dangerous because TTL may expire mid-task, and another instance may acquire the lock. Two processes may execute simultaneously, which will beat the purpose of distributed locking. For such tasks, job and schedulers are better options.</li></ul><p><strong>CRUX: </strong>If you find yourself using a distributed lock to protect shared mutable state, coordinate many services, serialize business logic, Try to redesign a system to avoid global coordination, because distributed locks reduce scalability, increase failure modes and are notoriously hard to get 100% correct.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eacc4cffeb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Headless Service: A Complete Guide]]></title>
            <link>https://medium.com/@narinderkaurmakkar1/kubernetes-headless-service-a-complete-guide-d7d129ab9c9e?source=rss-f90561ae570f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7d129ab9c9e</guid>
            <dc:creator><![CDATA[NarinderKaur Makkar]]></dc:creator>
            <pubDate>Fri, 09 Jan 2026 09:09:56 GMT</pubDate>
            <atom:updated>2026-01-09T09:09:56.159Z</atom:updated>
            <content:encoded><![CDATA[<p>Kubernetes Services are a fundamental abstraction that defines how pods are accessed within a cluster. While most people are familiar with <strong>ClusterIP</strong>, <strong>NodePort</strong>, and <strong>LoadBalancer</strong> services, <strong>Headless Services</strong> serve a very different and powerful purpose.</p><p>This article covers what a Kubernetes Headless Service is, why it exists, how it works, and when to use it</p><h3>What Is a Headless Service?</h3><p>A <strong>Headless Service</strong> is a Kubernetes Service without<strong> a Cluster IP</strong>. Instead of a single virtual IP and load balancing, it provides direct pod IP access via DNS.</p><p>You create a headless service by setting:</p><pre>spec:<br>  clusterIP: None</pre><p>When this is done:</p><ul><li>Kubernetes does <strong>not</strong> allocate a virtual IP.</li><li>Kube-proxy does <strong>not</strong> perform load balancing.</li><li>DNS returns <strong>pod IPs directly</strong>, not a single service IP.</li></ul><h3>Why Headless Services Exist</h3><p>Traditional services abstract away individual pods and provide load balancing. However, some applications <strong>need to know exactly which pod they are talking to</strong>. There are some scenarios where more fine grained controlled is needed on which pod we want to connect for a specific need.</p><p>Common reasons can include:</p><ul><li>Stateful applications (databases, message brokers, caching systems)</li><li>Leader–follower architectures</li><li>Custom client-side load balancing</li><li>Peer discovery systems</li></ul><p>Headless services enable <strong>service discovery without traffic routing</strong>.</p><h3>How Headless Services Work</h3><h3>With a Normal Service</h3><p>DNS query:</p><pre>my-service.default.svc.cluster.local</pre><p>Returns a service IP:</p><pre>10.96.0.15</pre><p>Traffic is load-balanced across pods.</p><h3>With a Headless Service</h3><p>DNS query:</p><pre>my-headless-service.default.svc.cluster.local</pre><p>Returns:</p><pre>10.244.1.5<br>10.244.2.8<br>10.244.3.12</pre><p>Each IP corresponds to a <strong>pod</strong>, not the service.</p><p>The client has the control to decide:</p><ul><li>Which pod to connect to</li><li>How to load-balance or route traffic</li></ul><h3>Creating a Headless Service</h3><p>To create a headless service, clusterIP needs to be set to <strong>None</strong> in the definition of a clusterIP server. Here is an example :</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: my-headless-service<br>spec:<br>  clusterIP: None<br>  selector:<br>    app: my-app<br>  ports:<br>   - port: 80<br>     targetPort: 8080</pre><p>Key points:</p><ul><li><strong>clusterIP: None</strong> makes it headless</li><li>Pods matching the selector are published via DNS.</li><li>No virtual IP is created.</li></ul><h3>Headless Service with StatefulSets</h3><p>Headless services are most commonly used with <strong>StatefulSets</strong>.</p><p><strong>Why do we need it?</strong></p><p>StatefulSets give each pod:</p><ul><li>A stable hostname</li><li>A stable network identity</li><li>Persistent storage</li></ul><p>Example DNS names:</p><pre>pod-0.my-headless-service.default.svc.cluster.local<br>pod-1.my-headless-service.default.svc.cluster.local</pre><p>This is ideal for:</p><ul><li>Databases like Cassandra, MongoDB, MySQL</li><li>Kafka and Zookeeper</li><li>etcd clusters</li></ul><h3>DNS Records in Headless Services</h3><p>Depending on the configuration, Kubernetes creates:</p><ul><li><strong>A records</strong> → One per pod IP</li><li><strong>SRV records</strong> → For named ports</li></ul><p>Example SRV lookup:</p><pre>_my-port._tcp.my-headless-service.default.svc.cluster.local</pre><p>This allows advanced clients to discover:</p><ul><li>Pod IP</li><li>Port</li><li>Protocol</li></ul><h3>When to Use a Headless Service</h3><p>Use a headless service when:</p><ul><li>You need <strong>direct pod-to-pod communication.</strong></li><li>Clients must <strong>discover all pods.</strong></li><li>You want <strong>custom or client-side load balancing.</strong></li><li>You’re running <strong>stateful or clustered applications.</strong></li></ul><p>Do <strong>not</strong> use it when:</p><ul><li>You just want simple load balancing.</li><li>You want a single stable service IP.</li><li>The app does not need pod awareness.</li></ul><h3>Advantages and Limitations</h3><h4>Advantages</h4><ul><li>Full control over traffic routing.</li><li>Essential for stateful workloads.</li><li>Works seamlessly with StatefulSets.</li><li>Enables advanced service discovery.</li></ul><h4>Limitations</h4><ul><li>No built-in load balancing.</li><li>Client logic becomes more complex.</li><li>Not suitable for simple stateless apps.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7d129ab9c9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bloom Filters in action]]></title>
            <link>https://medium.com/@narinderkaurmakkar1/a-bloom-filter-is-a-probabilistic-data-structure-that-efficiently-checks-whether-an-element-is-ad3f79eabab3?source=rss-f90561ae570f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad3f79eabab3</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[space-efficiency]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[probabilistic-memberships]]></category>
            <category><![CDATA[bloom-filter]]></category>
            <dc:creator><![CDATA[NarinderKaur Makkar]]></dc:creator>
            <pubDate>Wed, 10 Sep 2025 08:57:52 GMT</pubDate>
            <atom:updated>2025-09-10T09:30:59.757Z</atom:updated>
            <content:encoded><![CDATA[<p>A Bloom filter is a <strong>probabilistic data structure</strong> that efficiently checks whether an element is possibly in a set, offering fast and memory-saving membership testing with a small chance of false positives. Below is an in-depth guide on Bloom filters, use cases, hash function selection, limitations, implementation in Go, popular databases utilizing Bloom filters, and performance metrics.</p><h3>What is a Bloom Filter?</h3><p>A Bloom filter operates as a bit array of length n, initialized to zeros. To add an element, the value is hashed using k(we will see later, how to calculate value of k) independent hash functions, and the resulting positions in the array are set to one. To check if an item exists, it is hashed and the corresponding bits are examined. If all are set, the item might be present; if any bit is zero, the item is definitely absent. This structure is highly space-efficient and admits some probability of false positives, but never false negatives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJkDm-KrHV7Jr1siUaRh4Q.png" /></figure><h3>Use Cases</h3><p>Key use cases include:</p><ul><li><strong>Web caching/CDNs:</strong> Quickly test cache memberships and avoid expensive cache lookups. With any cache write operation, an entry in bloom filter is updated to make actual cache and bloom filter in sync, but it saves a lot of disk or memory lookups resulting in increase in performance.</li><li><strong>Database optimization:</strong> Databases such as Cassandra and Redis check for key existence before triggering disk access.</li><li><strong>deduplication:</strong> Prevent repeated events or entries with fast, probabilistic checking.</li><li><strong>Spam filtering and intrusion detection:</strong> Track malicious URLs/IP addresses with minimal memory overhead.</li><li><strong>Distributed systems:</strong> Speed up event log searches or resource existence checks. Distributed database systems use Bloom filters to determine if a key exists in a particular node’s SSTable (a log-structured table) before performing expensive disk operations.</li><li><strong>Data synchronisation:</strong> Bloom filters can be used to perform approximate data synchronisation, where a node can use a filter to check what data a peer node has, and then exchange only the differing elements</li></ul><h3>Recommended Hash Functions</h3><p>For Bloom filters, <strong>independent and uniformly distributed hash functions</strong> are preferred. Since security is not a concern in bloom filtersm, the selection of hash functions is made around non-cryptographic hashing functions which are fast and simple. these minimize collisions and balance set bits in the array. Common choices in practice include:</p><ul><li><strong>FNV-1a</strong> (used in this article for Go implementations for speed and distribution)</li><li><strong>MurmurHash</strong></li><li><strong>CityHash</strong></li></ul><p>Multiple hash functions can be derived from double hashing to further optimize performance and reduce memory needs.</p><h3>How to Calculate Number of Hash Functions</h3><p>Given you have 1000(n) elements to store in your bloom filter. And acceptable false positive rate is 5(p)%.<br>then size of bloom filter(m = number of bits in bloom filter):</p><p>m = -n*ln(p) / (ln(2)²)</p><p>And number of hash functions(k) required is calculated as:</p><p>k = m/n * ln(2)</p><h3>When Not to Use Bloom Filters</h3><p>There are many problems and situations where Bloom filters is not a good fit, such as:</p><ul><li><strong>Exact membership (no tolerance for false positives):</strong> If guaranteeing no false positives, use hash tables or trees.</li><li><strong>Frequent deletions:</strong> Standard Bloom filters lack native support for removing items.(though can be handled in advanced scalable bloom filters)</li><li><strong>Small datasets:</strong> Simpler structures (hashmaps) suffice and are more practical for smaller datasets.</li><li><strong>Unbounded insertions:</strong> Beyond a certain limit, false positive rates may rise as bloom filter becomes more dense. This can be handled using scalable and counting Bloom filters. This is advanced versions that handle dynamic datasets and item deletions(not discussed in detailed in this article)</li><li><strong>Detailed data retrieval:</strong> Bloom filters only answer set membership queries in booleans. If requirement is to fetch detailed data, then it is not a good choice.</li></ul><h3>Bloom Filter Implementation in Go</h3><p>Below is a basic Bloom filter implementation in Go using FNV hash functions. The requirement is to store 1000 elements with 1% of allowed false positive rate. The program below uses the function estimateParameters to calculate the size of bloom filter bit size and number of hash functions.</p><p>Once calculated, it used the hash functions inside add functions to calculate the bit for each hash method and sets the bits.</p><p>In checkIfExists function, it is again passed through same hash functions to calculate the bits and if all of the bit calculated are found in the bitmap, result is true. Else it returns false.</p><pre>package main<br>import (<br>  &quot;fmt&quot;<br>  &quot;hash/fnv&quot;<br>  &quot;math&quot;<br>)<br><br>type BloomFilter struct {<br>  m uint64      // Size of bit array<br>  k uint64      // Number of hash functions<br>  bits []byte   // Bit array<br>}<br>// calculate bit size of bloom filter and number of hash functions<br>func estimateParameters(n uint64, p float64) (uint64, uint64) {<br>  m := uint64(math.Ceil(-(float64(n) * math.Log(p)) / (math.Ln2 * math.Ln2)))<br>  k := uint64(math.Ceil((float64(m) / float64(n)) * math.Ln2))<br>  if k &lt; 1 { k = 1 }<br>  return m, k<br>}<br><br>func NewBloomFilter(n uint64, p float64) *BloomFilter {<br>  m, k := estimateParameters(n, p)<br>  return &amp;BloomFilter{<br>    m: m,<br>    k: k,<br>    bits: make([]byte, (m+7)/8),<br>  }<br>}<br><br>func (bf *BloomFilter) getHashes(data []byte) []uint64 {<br>  hashes := make([]uint64, bf.k)<br>  h1 := fnv.New64()<br>  h1.Write(data)<br>  hash1Val := h1.Sum64()<br>  h2 := fnv.New64a()<br>  h2.Write(data)<br>  hash2Val := h2.Sum64()<br>  for i := uint64(0); i &lt; bf.k; i++ {<br>    hashes[i] = (hash1Val + i*hash2Val) % bf.m<br>  }<br>  return hashes<br>}<br><br>func (bf *BloomFilter) Add(data []byte) {<br>  for _, h := range bf.getHashes(data) {<br>    byteIndex := h / 8<br>    bitOffset := h % 8<br>    bf.bits[byteIndex] |= (1 &lt;&lt; bitOffset)<br>  }<br>}<br><br>func (bf *BloomFilter) checkIfExists(data []byte) bool {<br>  for _, h := range bf.getHashes(data) {<br>    byteIndex := h / 8<br>    bitOffset := h % 8<br>    if bf.bits[byteIndex]&amp;(1&lt;&lt;bitOffset) == 0 {<br>      return false<br>    }<br>  }<br>  return true<br>}<br>func main() {<br>  bf := NewBloomFilter(1000, 0.01)<br>  bf.Add([]byte(&quot;apple&quot;))<br>  bf.Add([]byte(&quot;banana&quot;))<br>  fmt.Println(&quot;MightContain &#39;apple&#39;:&quot;, bf.checkIfExists([]byte(&quot;apple&quot;))) // True<br>  fmt.Println(&quot;MightContain &#39;cherry&#39;:&quot;, bf.checkIfExists([]byte(&quot;cherry&quot;))) // False<br>}</pre><h3>Databases Using Bloom Filters</h3><p>Several widely-used databases employ Bloom filters, including:</p><ul><li><strong>Redis:</strong> for cache key existence tests.</li><li><strong>Apache Cassandra:</strong> avoids unnecessary disk reads.</li><li><strong>Apache HBase:</strong> optimizes row lookup performance.</li><li><strong>Other distributed stores and cloud databases:</strong> leveraging Bloom filters for partitioned cache checks and fast key filtering.</li></ul><h3>Efficiency and Performance Metrics</h3><p>Bloom filters dramatically improve computation and memory efficiency. Following we have some metrics to claim the same.</p><ul><li>Bloom filter provides <strong>O(1) query time</strong> for membership checks.</li><li>Saving up to <strong>90% memory</strong> compared to storing all elements for large sets.</li><li>Reducing expensive cache/database lookups by serving as a fast preliminary filter.</li><li>False positive rate can be tuned by adjusting bit array size (m) and number of hash functions (k), often keeping false positives below 1% for massive datasets.</li><li>In practice, real-time systems leverage Bloom filters to process millions of requests with minimal overhead.</li></ul><h3>Conclusion</h3><p>Bloom filters are <strong>space-efficient, fast set membership queries</strong> in areas like caches and databases, as long as false positives are tolerable and deletions are not frequent. By selecting robust hash functions and tuning structure parameters, Bloom filters can dramatically speed up application workflows and reduce resource usage in real-world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad3f79eabab3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Provider Debugging: A step by step guide]]></title>
            <link>https://medium.com/@narinderkaurmakkar1/terraform-provider-debugging-a-step-by-step-guide-8c6d771637a1?source=rss-f90561ae570f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c6d771637a1</guid>
            <category><![CDATA[debugging-terraform]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[goland]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[NarinderKaur Makkar]]></dc:creator>
            <pubDate>Sat, 05 Aug 2023 16:05:49 GMT</pubDate>
            <atom:updated>2023-08-05T16:05:49.859Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Terraform Provider Debugging: A step by step guide</strong></p><p>Terraform is HashiCorp’s infrastructure as code (IAC) tool. It lets you define resources and infrastructure in human-readable, declarative configuration files, and manages your infrastructure’s lifecycle. Terraform plugins let terraform interact with cloud platforms and other services via their APIs. These plugins are called Providers. Many providers have been written by HashiCorp and open-source communities.</p><p>While developing a provider (currently allowed only in Golang), I faced some challenges when I needed to debug the code. In this article, I want to share my experience about debugging process while developing and hope it would be helpful for everyone struggling with the same.</p><p>NOTE: here, we will be using IBM cloud terraform examples for references. I am using mac, so paths can vary based on OS.</p><p>So, let’s start.</p><p>The first thing to understand is that, terraform by default invokes the provider from HashiCorp’s default registry location. So, in following terraform config, where no specific registry path (private or custom) is mentioned, it is pointing to IBM cloud terraform provider from <a href="https://registry.terraform.io/providers/IBM-Cloud/ibm">this location</a>.</p><pre>terraform {<br>required_providers {<br>ibm = {<br>source = “IBM-Cloud/ibm”<br>version = “1.46.0”<br>      }<br>  }<br>}<br>provider “ibm” {}</pre><p>This is useful only when the provider has been tested thoroughly and pushed to registry. But this is not the case while the development is in progress. We developers need to test the provider while the changes are on our local environment. And it becomes tricky because providers are not executable binaries. I will discuss three strategies to test the things locally.</p><p><strong>Strategy I:</strong></p><p><strong>Define the provider source in the terraform config: </strong>When we have a provider executable in good shape and we need to test it:</p><ul><li>Go to your IBM terraform provider directory and run <em>“make build” </em>command to install a binary. <em>[Optionally, you can also build a binary using a build command, but recommended way is to disable all optimization and inlining.]</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lcfoe7WhOpzgirbE8t2BRQ.png" /></figure><ul><li>This step will create a provider binary file in bin folder, but note that it is not executable, so you will receive an error if you try to run it directly:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSCSsT9E3zaBAbyZL6URFw.png" /></figure><ul><li>Terraform by default, looks up for the plugins in $HOME/.terraform.d/plugins (unix based systems) &amp; %APPDATA%/.terraform.d/plugins (for windows) directory. We will try to build a path in the following pattern, so terraform can recognise it as per recommendation by terraform (https://developer.hashicorp.com/terraform/language/modules/sources#terraform-registry).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TAksfKuhhdv-xooOLbjCg.png" /></figure><p>Here <strong>site URL</strong> can be any dummy URL, <strong>provider namespace reference</strong> can also be custom and version can also be user defined.</p><ul><li>Put the terraform binary in this path and it should look like this:</li></ul><p><em>/Users/narinderkaur/.terraform.d/plugins/terraform.example.com/IBMCloud/ibm/1.44.0/darwin_amd64/ terraform-provider-ibm</em></p><ul><li>Now we are ready to test our binary, let us see how we will put this local provider in terraform config file:</li></ul><pre>terraform {<br>required_providers {<br>ibm = {<br>source = “terraform.example.com/IBMCloud/ibm”<br>version = “1.44.0”<br>      }<br>   }<br>}<br>provider “ibm” {}</pre><p>With this config file, terraform would try to run IBM provider from your local.</p><p><strong>Strategy II:</strong></p><p><strong>Override the provider source in the terraform CLI configuration file: </strong>In this second approach, we need to understand that terraform works on default configuration settings and in order to override these settings, terraform has given the users a way to define it in .terraformrc file (on Unix systems) and terraform.rc(on windows systems), whose default location is <strong><em>$HOME</em> or <em>%APPDATA% </em></strong><em>respectively</em>. Using environment variable TF_CLI_CONFIG_FILE, these default locations of CLI configurations can also be altered.</p><p>The CLI configuration file contains a provider_installation block, which allows overriding Terraform’s default installation behaviour.</p><pre>provider_installation {<br>dev_overrides {<br>“ibmcloud/ibm” = “/Users/narinderkaur/go/bin”<br>  }<br>}</pre><p>The above configuration overrides the package for the hashicorp/ibm provider binary with <em>/Users/narinderkaur/go/bin/terraform-provider-ibm</em>. This disables the version and checksum verifications for this provider and forces Terraform to look for the IBM provider plugin in the given directory.</p><p>Now we are ready to test our binary, let us see how we will mention this local provider in terraform config file:</p><pre>terraform {<br>required_providers {<br>ibm = {<br>source = “ ibmcloud/ibm”<br>      }<br>    }<br>}<br>provider “ibm” {}</pre><p>The above two methods are almost similar, the only difference is that in second case, terraform would skip the version and checksum verification. And you will not require to run a <em>terraform init</em> command.</p><p><strong>Strategy III</strong></p><p><strong>Running the provider in debug mode:</strong> Sometimes, we come across a bug, which we can debug only by understanding how the code is behaving at run time and how the state of code is changing. In such situation, above two methods are not so useful, and we need a real debugger. Now because terraform providers are not executable binaries, we cannot simply put them into the debugger mode and run. Let’s follow the below described steps to achieve this.</p><ul><li>The first step is to build the binary of terraform provider with debug mode. And in this step, it is also important to note that when debug mode is true, we need to add ProviderAddr also to ServeOpts. This property is kept only for debug mode, if not provided, by default the provider will run with the name of “provider”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsWAHsj8QF-ZoZmPnlpOqw.png" /></figure><ul><li>Once added the required code modification, now it is time to build. Run the command “make build”. If everything is good, it will generate the binary in your go path’s bin folder with the name of terraform-provider-ibm.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQ7UCJEGair2B2CfrGpWXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2MMusoHPPOty1XYlmWymQ.png" /></figure><p>Next step is to mention the source of provider binary to terraform. We will not use anything new here, we will follow above mentioned strategy II and use <strong>provider_installation’s dev_overrides</strong> property to define the address for provider lookup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5lkyDWQqBQoFKgMadpwSA.png" /></figure><ul><li>When we run directly terraform provider in debug mode, it does not give error as described in Strategy I(step II). It will run successfully and would provide a message asking you to set the <strong>TF_REATTACH_PROVIDERS </strong>environment variable to the value shown. This environment variable will instruct Terraform Core to not to start a new subprocess for the given provider address and attach to this existing plugin process, to send its requests to the socket address.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HnllpKp5sh20d_rk1X-0XA.png" /></figure><ul><li>For debugging, we can use two ways, one is to use delv (<a href="https://github.com/go-delve/delve">https://github.com/go-delve/delve</a>). And other way is to use an ID. For simplicity, we will stick to debugging via Goland(go IDE by JetBrains). So now in Goland, we need to attach the debugger to a process, for that, go to Goland Menu-&gt;Run-&gt;Attach to Process.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6iefqTJqOKlbNoBCOlwCA.png" /></figure><ul><li>It will give you the list of running processes. Select the one from the list. You can use the process id to match from the previous output.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0eZGjyjBCn2Se6UsUZreA.png" /></figure><ul><li>You will see the output similar to following, informing about the server running in debug mode:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ajBh3V2Ig_7PyhM9Prx6w.png" /></figure><ul><li>Let us add some break points where ever we need to debug:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mc5Jnq3X-wFg2esJzE9Xg.png" /></figure><ul><li>As mentioned in step 4, create an environment variable <strong>TF_REATTACH_PROVIDERS </strong>as below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*heRcn_UpjVi94yldJT352g.png" /></figure><ul><li>Now everything looks nice and it is good time to test your terraform configuration. Let us create one. As you can see below, now we used source attribute to point to the binary of the provider.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G9sBUP1zMA0cl7IJQIcJgA.png" /></figure><ul><li>Let’s execute it now. Also note that in this case, you don’t need to run “<em>terraform init”</em> command. We will directly invoke terraform plan and terraform apply. And Tada!!! We got to our breakpoint to dig deeper.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rU4wb0-7Qghde8f5hTyNhA.png" /></figure><p>Conclusion: Through this blog, I have tried to explain various paths of terraform testing on local environment. Although, debug mode strategy is my favourite one, but because it is little more effort taking. If not required, one can use others ways to run the plugins from their local environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c6d771637a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>