<?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 Sampark Mehrotra on Medium]]></title>
        <description><![CDATA[Stories by Sampark Mehrotra on Medium]]></description>
        <link>https://medium.com/@sampark02?source=rss-1f488fcaac66------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F-6j5QPqDBTvaYks2JveHA.jpeg</url>
            <title>Stories by Sampark Mehrotra on Medium</title>
            <link>https://medium.com/@sampark02?source=rss-1f488fcaac66------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:36:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sampark02/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[Essential Terraform Collection Functions with Real-World Examples |Part-1]]></title>
            <link>https://medium.com/@sampark02/essential-terraform-collection-functions-with-real-world-examples-part-1-c8a63992181a?source=rss-1f488fcaac66------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8a63992181a</guid>
            <category><![CDATA[terraforming]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Sampark Mehrotra]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 15:19:11 GMT</pubDate>
            <atom:updated>2025-04-15T15:19:11.340Z</atom:updated>
            <content:encoded><![CDATA[<p>Collections are everywhere in Terraform — lists of subnets, maps of tags, sets of users. Mastering collection functions allows you to filter, transform, and manipulate these values dynamically in your infrastructure code.</p><p>In this article, we’ll walk through <strong>5 powerful Terraform collection functions</strong>, their <strong>practical use cases</strong>, and the <strong>output</strong> you can expect from each.</p><h3>🧠 Covered Functions</h3><p>We’ll explore:</p><ol><li>length</li><li>tolist</li><li>tomap</li><li>keys</li><li>values</li></ol><h3>✅ 1. length(collection) – Count Items in a List, Map, or Set</h3><p><strong>Use Case:</strong> Validate number of availability zones, subnets, or users.</p><pre>variable &quot;subnet_ids&quot; {<br>  default = [&quot;subnet-123&quot;, &quot;subnet-456&quot;, &quot;subnet-789&quot;]<br>}</pre><pre>output &quot;subnet_count&quot; {<br>  value = length(var.subnet_ids)<br>  # Output: 3<br>}</pre><h3>✅ 2. tolist(value) – Convert a Set or Tuple to a List</h3><p><strong>Use Case:</strong> Convert a set (which is unordered) into an indexable list.</p><pre>locals {<br>  az_set = toset([&quot;us-east-1a&quot;, &quot;us-east-1b&quot;])<br>}</pre><pre>output &quot;az_list&quot; {<br>  value = tolist(local.az_set)<br>  # Output: [&quot;us-east-1a&quot;, &quot;us-east-1b&quot;]<br>}</pre><h3>✅ 3. tomap(value) – Convert a List of Objects to a Map</h3><p><strong>Use Case:</strong> Build a dynamic map for tags or configurations.</p><pre>locals {<br>  kv_list = [<br>    { key = &quot;env&quot;, value = &quot;prod&quot; },<br>    { key = &quot;team&quot;, value = &quot;devops&quot; }<br>  ]</pre><pre>  tag_map = tomap({ for item in local.kv_list : item.key =&gt; item.value })<br>}</pre><pre>output &quot;tags&quot; {<br>  value = local.tag_map<br>  # Output: {<br>  #   &quot;env&quot;  = &quot;prod&quot;<br>  #   &quot;team&quot; = &quot;devops&quot;<br>  # }<br>}</pre><h3>✅ 4. keys(map) – Get All Keys from a Map</h3><p><strong>Use Case:</strong> Loop through tags, parameters, or environment variables.</p><pre>locals {<br>  app_tags = {<br>    Name  = &quot;web&quot;<br>    Owner = &quot;teamA&quot;<br>    Env   = &quot;prod&quot;<br>  }<br>}</pre><pre>output &quot;tag_keys&quot; {<br>  value = keys(local.app_tags)<br>  # Output: [&quot;Env&quot;, &quot;Name&quot;, &quot;Owner&quot;]<br>}</pre><h3>✅ 5. values(map) – Get All Values from a Map</h3><p><strong>Use Case:</strong> Extract values for validation or comparison.</p><pre>locals {<br>  instance_types = {<br>    frontend = &quot;t3.micro&quot;<br>    backend  = &quot;t3.medium&quot;<br>  }<br>}</pre><pre>output &quot;all_instance_types&quot; {<br>  value = values(local.instance_types)<br>  # Output: [&quot;t3.micro&quot;, &quot;t3.medium&quot;]<br>}</pre><h3>🧩 Bonus Use Case: Combine Keys and Values</h3><p>You can also combine keys and values with zipmap or use loops for more advanced transformations.</p><h3>🚀 Conclusion</h3><p>These 5 collection functions — length, tolist, tomap, keys, and values — are foundational tools when working with dynamic infrastructure in Terraform. They make your configurations more flexible, readable, and powerful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8a63992181a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform String Functions — Real-World Examples with Output]]></title>
            <link>https://medium.com/@sampark02/terraform-string-functions-real-world-examples-with-output-64a15207cc5b?source=rss-1f488fcaac66------2</link>
            <guid isPermaLink="false">https://medium.com/p/64a15207cc5b</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[terraforming]]></category>
            <dc:creator><![CDATA[Sampark Mehrotra]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 15:14:46 GMT</pubDate>
            <atom:updated>2025-04-15T15:14:46.985Z</atom:updated>
            <content:encoded><![CDATA[<h3>Terraform String Functions — Real-World Examples with Output</h3><p>When managing infrastructure with Terraform, strings play a key role — from naming conventions and tagging to dynamic resource generation. Terraform offers a wide variety of <strong>string functions</strong> that help you manipulate and transform text effortlessly.</p><p>In this article, we’ll explore the most useful <strong>Terraform string functions</strong> with practical examples and expected output values to help you level up your IaC skills.</p><h3>📚 List of Terraform String Functions</h3><p>Here are the core string functions we’ll cover:</p><ul><li>chomp(string)</li><li>format(format, values...)</li><li>formatlist(format, list)</li><li>indent(count, string)</li><li>join(separator, list)</li><li>lower(string)</li><li>upper(string)</li><li>replace(string, substring, replacement)</li><li>split(separator, string)</li><li>substr(string, offset, length)</li><li>trimspace(string)</li><li>trimprefix(string, prefix)</li><li>trimsuffix(string, suffix)</li><li>length(string)</li><li>regex(pattern, string)</li><li>regexall(pattern, string)</li></ul><h3>✅ 1. chomp(string) – Remove Trailing Newline</h3><p><strong>Use Case:</strong> Clean up user input or file output.</p><pre>output &quot;cleaned&quot; {<br>  value = chomp(&quot;hello world\n&quot;) // Returns &quot;hello world&quot;<br>}</pre><h3>✅ 2. format(format, values...) – String Formatting</h3><p><strong>Use Case:</strong> Build consistent resource names.</p><pre>output &quot;resource_name&quot; {<br>  value = format(&quot;app-%s-%02d&quot;, &quot;prod&quot;, 5) // Returns &quot;app-prod-05&quot;<br>}</pre><h3>✅ 3. formatlist(format, list) – Format a List</h3><p><strong>Use Case:</strong> Create a list of tag strings.</p><pre>output &quot;formatted_tags&quot; {<br>  value = formatlist(&quot;env:%s&quot;, [&quot;dev&quot;, &quot;prod&quot;]) // Returns [&quot;env:dev&quot;, &quot;env:prod&quot;]<br>}</pre><h3>✅ 4. indent(count, string) – Add Indentation</h3><p><strong>Use Case:</strong> Format multi-line user data scripts.</p><pre>output &quot;indented_script&quot; {<br>  value = indent(4, &quot;line1\nline2&quot;) // Returns:<br>  /*<br>      line1<br>      line2<br>  */<br>}</pre><h3>✅ 5. join(separator, list) – Join List into a String</h3><p><strong>Use Case:</strong> Create comma-separated lists for inputs.</p><pre>output &quot;csv&quot; {<br>  value = join(&quot;,&quot;, [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]) // Returns &quot;a,b,c&quot;<br>}</pre><h3>✅ 6. lower(string) – Convert to Lowercase</h3><p><strong>Use Case:</strong> Standardize labels.</p><pre>output &quot;lowercase&quot; {<br>  value = lower(&quot;TeSt&quot;) // Returns &quot;test&quot;<br>}</pre><h3>✅ 7. upper(string) – Convert to Uppercase</h3><p><strong>Use Case:</strong> Enforce uppercase naming conventions.</p><pre>output &quot;uppercase&quot; {<br>  value = upper(&quot;dev&quot;) // Returns &quot;DEV&quot;<br>}</pre><h3>✅ 8. replace(string, substring, replacement) – Replace Text</h3><p><strong>Use Case:</strong> Modify URLs, names, or prefixes.</p><pre>output &quot;replaced&quot; {<br>  value = replace(&quot;web-prod-1&quot;, &quot;prod&quot;, &quot;stage&quot;) // Returns &quot;web-stage-1&quot;<br>}</pre><h3>✅ 9. split(separator, string) – Split a String into a List</h3><p><strong>Use Case:</strong> Parse CSV input.</p><pre>output &quot;split_list&quot; {<br>  value = split(&quot;,&quot;, &quot;a,b,c&quot;) // Returns [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]<br>}</pre><h3>✅ 10. substr(string, offset, length) – Extract a Substring</h3><p><strong>Use Case:</strong> Extract resource identifiers.</p><pre>output &quot;partial_id&quot; {<br>  value = substr(&quot;env-abc123&quot;, 4, 3) // Returns &quot;abc&quot;<br>}</pre><h3>✅ 11. trimspace(string) – Remove Leading and Trailing Whitespace</h3><p><strong>Use Case:</strong> Clean user input.</p><pre>output &quot;trimmed&quot; {<br>  value = trimspace(&quot;  hello  &quot;) // Returns &quot;hello&quot;<br>}</pre><h3>✅ 12. trimprefix(string, prefix) – Remove Prefix</h3><p><strong>Use Case:</strong> Normalize resource names.</p><pre>output &quot;without_prefix&quot; {<br>  value = trimprefix(&quot;dev-resource&quot;, &quot;dev-&quot;) // Returns &quot;resource&quot;<br>}</pre><h3>✅ 13. trimsuffix(string, suffix) – Remove Suffix</h3><p><strong>Use Case:</strong> Strip file extensions or IDs.</p><pre>output &quot;without_suffix&quot; {<br>  value = trimsuffix(&quot;name-prod&quot;, &quot;-prod&quot;) // Returns &quot;name&quot;<br>}</pre><h3>✅ 14. length(string) – Get String Length</h3><p><strong>Use Case:</strong> Validate input lengths.</p><pre>output &quot;name_length&quot; {<br>  value = length(&quot;terraform&quot;) // Returns 9<br>}</pre><h3>✅ 15. regex(pattern, string) – Extract First Match</h3><p><strong>Use Case:</strong> Extract an environment or version from a tag.</p><pre>output &quot;env&quot; {<br>  value = regex(&quot;env-(\\w+)&quot;, &quot;env-prod&quot;) // Returns &quot;prod&quot;<br>}</pre><h3>✅ 16. regexall(pattern, string) – Extract All Matches</h3><p><strong>Use Case:</strong> Extract multiple versions from text.</p><pre>output &quot;versions&quot; {<br>  value = regexall(&quot;v[0-9]+&quot;, &quot;v1 and v2&quot;) // Returns [&quot;v1&quot;, &quot;v2&quot;]<br>}</pre><h3>✅ 17. startswith(string, prefix) – Check If a String Starts With a Prefix</h3><p><strong>Use Case:</strong> Validate resource naming conventions.</p><pre>output &quot;starts_with_env&quot; {<br>  value = startswith(&quot;env-prod-server&quot;, &quot;env-&quot;) // Returns true<br>}</pre><h3>✅ 18. endswith(string, suffix) – Check If a String Ends With a Suffix</h3><p><strong>Use Case:</strong> Enforce resource type suffixes.</p><pre>output &quot;ends_with_server&quot; {<br>  value = endswith(&quot;web-prod-server&quot;, &quot;-server&quot;) // Returns true<br>}</pre><h3>✅ 19. title(string) – Capitalize Each Word</h3><p><strong>Use Case:</strong> Format display names for tags.</p><pre>output &quot;title_case&quot; {<br>  value = title(&quot;dev operations&quot;) // Returns &quot;Dev Operations&quot;<br>}</pre><h3>✅ 20. upper(string) – Convert to Uppercase</h3><p><strong>Use Case:</strong> Standardize environment tags.</p><pre>output &quot;to_upper&quot; {<br>  value = upper(&quot;staging&quot;) // Returns &quot;STAGING&quot;<br>}</pre><h3>✅ 21. lower(string) – Convert to Lowercase</h3><p><strong>Use Case:</strong> Normalize case for usernames or keys.</p><pre>output &quot;to_lower&quot; {<br>  value = lower(&quot;PROD_Account&quot;) // Returns &quot;prod_account&quot;<br>}</pre><h3>🎯 Conclusion</h3><p>Terraform string functions allow you to transform and validate data dynamically, making your configurations more powerful, maintainable, and reusable.</p><p>From naming conventions to advanced parsing, these string helpers unlock a new level of flexibility for writing smart infrastructure code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64a15207cc5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform Numeric Functions — Explained with Real-World Examples]]></title>
            <link>https://medium.com/@sampark02/terraform-numeric-functions-explained-with-real-world-examples-4630cab3ce32?source=rss-1f488fcaac66------2</link>
            <guid isPermaLink="false">https://medium.com/p/4630cab3ce32</guid>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Sampark Mehrotra]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 15:06:38 GMT</pubDate>
            <atom:updated>2025-04-15T15:06:38.416Z</atom:updated>
            <content:encoded><![CDATA[<h3>Terraform Numeric Functions — Explained with Real-World Examples</h3><p>When working with Terraform, you’re not just provisioning infrastructure — you’re also writing logic to control how resources are created. And when it comes to logic, <strong>numbers matter</strong>.</p><p>Terraform provides a set of <strong>numeric functions</strong> that help you work with integers and floats in powerful ways — from rounding values to generating random numbers or calculating values dynamically. These functions can make your configuration more flexible, DRY (Don’t Repeat Yourself), and smarter.</p><p>In this article, we’ll explore <strong>Terraform’s numeric functions</strong> with <strong>real-world use cases</strong> that show how to put them into practice.</p><h3>📚 List of Terraform Numeric Functions</h3><p>Here are the core numeric functions we’ll cover:</p><ul><li>abs(number)</li><li>ceil(number)</li><li>floor(number)</li><li>log(number, base)</li><li>max(number1, number2, ...)</li><li>min(number1, number2, ...)</li><li>parseint(string, base)</li><li>pow(base, exponent)</li><li>signum(number)</li><li>sqrt(number)</li><li>mod(a, b)</li></ul><h3>✅ 1. abs(number) – Absolute Value</h3><p><strong>What it does:</strong> Returns the absolute (positive) value of a number, removing any minus sign.<br> <strong>Use Case:</strong> Normalizing deviation values from monitoring data.</p><pre>variable &quot;cpu_deviation&quot; {<br>  default = -25<br>}</pre><pre>output &quot;normalized_cpu_deviation&quot; {<br>  value = abs(var.cpu_deviation) // Returns 25<br>}</pre><h3>✅ 2. ceil(number) – Round Up</h3><p><strong>What it does:</strong> Rounds a floating-point number <strong>up</strong> to the nearest whole number.<br> <strong>Use Case:</strong> Estimating the number of EC2 instances needed based on workload.</p><pre>variable &quot;users&quot; {<br>  default = 78<br>}</pre><pre>output &quot;required_instances&quot; {<br>  value = ceil(var.users / 20) // Returns 4<br>}</pre><h3>✅ 3. floor(number) – Round Down</h3><p><strong>What it does:</strong> Rounds a floating-point number <strong>down</strong> to the nearest whole number.<br> <strong>Use Case:</strong> Billing estimates with full-hour increments.</p><pre>variable &quot;usage_hours&quot; {<br>  default = 5.9<br>}</pre><pre>output &quot;billed_hours&quot; {<br>  value = floor(var.usage_hours) // Returns 5<br>}</pre><h3>✅ 4. log(number, base) – Logarithmic Value</h3><p><strong>What it does:</strong> Returns the logarithm of a number in the given base.<br> <strong>Use Case:</strong> Calculating exponential backoff.</p><pre>output &quot;backoff_interval&quot; {<br>  value = log(1000, 10) // Returns 3<br>}</pre><h3>✅ 5. max(...) – Maximum Value</h3><p><strong>What it does:</strong> Returns the <strong>highest</strong> number from a list of values.<br> <strong>Use Case:</strong> Ensure thresholds don’t go below a minimum.</p><pre>variable &quot;threshold&quot; { default = 3 }<br>variable &quot;default_value&quot; { default = 5 }</pre><pre>output &quot;applied_threshold&quot; {<br>  value = max(var.threshold, var.default_value) // Returns 5<br>}</pre><h3>✅ 6. min(...) – Minimum Value</h3><p><strong>What it does:</strong> Returns the <strong>lowest</strong> number from a list of values.<br> <strong>Use Case:</strong> Restricting autoscaling to a defined maximum.</p><pre>variable &quot;user_count&quot; { default = 3 }<br>variable &quot;asg_max&quot; { default = 5 }</pre><pre>output &quot;instances_to_launch&quot; {<br>  value = min(var.user_count, var.asg_max) // Returns 3<br>}</pre><h3>✅ 7. parseint(string, base) – Convert String to Integer</h3><p><strong>What it does:</strong> Parses a string as a number in a given base (like binary, hex).<br> <strong>Use Case:</strong> Converting hexadecimal subnet masks.</p><pre>output &quot;subnet_size&quot; {<br>  value = parseint(&quot;0x1A&quot;, 16) // Returns 26<br>}</pre><h3>✅ 8. pow(base, exponent) – Power Function</h3><p><strong>What it does:</strong> Raises a base number to the power of the exponent.<br> <strong>Use Case:</strong> Projecting data growth or pricing.</p><pre>output &quot;storage_cost_factor&quot; {<br>  value = pow(2, 4) // Returns 16<br>}</pre><h3>✅ 9. signum(number) – Sign of a Number</h3><p><strong>What it does:</strong> Returns -1, 0, or 1 depending on whether the number is negative, zero, or positive.<br> <strong>Use Case:</strong> Health trend analysis.</p><pre>output &quot;trend_direction&quot; {<br>  value = signum(-3) // Returns -1<br>}</pre><h3>✅ 10. sqrt(number) – Square Root</h3><p><strong>What it does:</strong> Returns the square root of a number.<br> <strong>Use Case:</strong> Grid sizing or spatial distribution.</p><pre>variable &quot;tasks&quot; {<br>  default = 100<br>}</pre><pre>output &quot;grid_nodes&quot; {<br>  value = ceil(sqrt(var.tasks)) // Returns 10<br>}</pre><h3>✅ 11. mod(a, b) – Modulo Operation</h3><p><strong>What it does:</strong> Returns the remainder when one number is divided by another.<br> <strong>Use Case:</strong> Distributing resources across availability zones.</p><pre>variable &quot;index&quot; {<br>  default = 7<br>}</pre><pre>output &quot;zone_id&quot; {<br>  value = mod(var.index, 3) // Returns 1<br>}</pre><h3>🧠 Bonus: Chaining Numeric Functions</h3><p>You can also <strong>combine</strong> multiple numeric functions:</p><pre>output &quot;smart_value&quot; {<br>  value = max(1, min(ceil(75 / 10), 5)) // Returns 5<br>}</pre><blockquote><em>Ensures the result is between 1 and 5.</em></blockquote><h3>🧾 Conclusion</h3><p>Terraform isn’t just about writing declarative code — it’s about writing smart, <strong>dynamic infrastructure-as-code</strong>. Numeric functions allow you to make your configurations adaptive, reusable, and logic-driven.</p><p>Whether you’re provisioning instances, calculating costs, or building cloud-native automation, mastering these numeric functions gives you the power to write cleaner and smarter Terraform code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4630cab3ce32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Module Source Types in Terraform — A Complete Guide]]></title>
            <link>https://medium.com/@sampark02/understanding-module-source-types-in-terraform-a-complete-guide-01a50aa56b78?source=rss-1f488fcaac66------2</link>
            <guid isPermaLink="false">https://medium.com/p/01a50aa56b78</guid>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Sampark Mehrotra]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 07:52:38 GMT</pubDate>
            <atom:updated>2025-04-14T07:52:38.937Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Module Source Types in Terraform — A Complete Guide</h3><h3>🌱 Introduction</h3><p>As cloud infrastructure grows increasingly complex, writing repetitive Terraform code for every project can become time-consuming, error-prone, and hard to maintain. This is where <strong>Terraform modules</strong> come into play.</p><p>Modules allow you to package and reuse Terraform configurations in a standardized way. Whether it’s creating an S3 bucket, setting up a VPC, or deploying an EKS cluster — if you’ve done it once, there’s no need to rewrite it. Just import the module, supply variables, and you’re good to go.</p><p>But there’s one key detail when using modules: <strong>Where does the module live?</strong><br> That’s where the source argument becomes crucial. It defines the <strong>location</strong> from which Terraform will download the module code.</p><p>In this article, we’ll walk through the different types of module sources Terraform supports, with real-world examples, pros and cons, and tips to help you choose the right one for your use case.</p><h3>🔍 What is a Module Source in Terraform?</h3><p>When you define a module block in Terraform, you use the source argument to specify where to get the module code from. Think of it like importing a library in any programming language.</p><p>Here’s a basic module block:</p><pre>module &quot;network&quot; {<br>  source = &quot;./modules/network&quot;<br>  vpc_cidr = &quot;10.0.0.0/16&quot;<br>}</pre><p>In the above example, ./modules/network is the <strong>source path</strong> — it tells Terraform to look in a local directory.</p><p>But that’s just one type. Let’s look at <strong>all the options</strong> available.</p><h3>🧩 Types of Module Sources in Terraform</h3><p>Terraform supports multiple ways to pull in module code, depending on where you store your reusable components:</p><h4>1. Local Path</h4><p>Used when your module is in the same repository or file system.</p><pre>module &quot;logging&quot; {<br>  source = &quot;./modules/logging&quot;<br>}</pre><ul><li>✅ Fast and simple during development.</li><li>❌ Doesn’t work well in remote CI/CD pipelines unless paths are preserved.</li></ul><h4>2. Terraform Registry</h4><p>The official <a href="https://registry.terraform.io/">Terraform Registry</a> hosts thousands of modules.</p><pre>module &quot;vpc&quot; {<br>  source  = &quot;terraform-aws-modules/vpc/aws&quot;<br>  version = &quot;3.14.0&quot;<br>}</pre><ul><li>✅ Easy version management.</li><li>✅ Well-tested community modules.</li><li>❌ Requires internet access.</li><li>❌ Less control over code if module is external.</li></ul><h4>3. Git (GitHub, GitLab, Bitbucket, etc.)</h4><p>You can point to a Git repo directly.</p><pre>module &quot;network&quot; {<br>  source = &quot;git::https://github.com/myorg/tf-modules.git//vpc?ref=v1.0.0&quot;<br>}</pre><ul><li>✅ Ideal for internal shared modules.</li><li>✅ You can pin to a branch, tag, or commit.</li><li>❌ May require credentials or SSH setup for private repos.</li></ul><h4>4. Git Submodules</h4><p>If you keep multiple modules in a mono-repo, you can point to subfolders.</p><pre>source = &quot;git::https://github.com/myorg/infra-modules.git//modules/db?ref=main&quot;</pre><ul><li>✅ Keeps modules centralized.</li><li>❌ Repo structure becomes tightly coupled with source references.</li></ul><h4>5. Generic HTTP URLs or S3 Buckets</h4><p>You can host modules as zipped files on S3 or a web server.</p><pre>module &quot;custom&quot; {<br>  source = &quot;https://example.com/modules/monitoring.zip&quot;<br>}</pre><p>Or using S3:</p><pre>module &quot;s3_module&quot; {<br>  source = &quot;s3::https://s3.amazonaws.com/mybucket/terraform-modules/vpc.zip&quot;<br>}</pre><ul><li>✅ Works well for controlled distribution.</li><li>❌ Needs proper versioning &amp; zip packaging.</li><li>❌ Requires manual uploads and ACL setup.</li></ul><h3>📌 Best Practices for Using Module Sources</h3><ul><li><strong>Pin versions</strong>: Always use a specific tag or commit hash to avoid unexpected changes.</li><li><strong>Use semantic versioning</strong>: Helps you know what changes are safe.</li><li><strong>Keep local paths for dev only</strong>: Replace them with Git or Registry sources before production.</li><li><strong>Structure repos wisely</strong>: If using Git submodules or mono-repos, keep paths consistent.</li></ul><h3>🚨 Common Pitfalls to Avoid</h3><ul><li>Forgetting to run terraform get or terraform init after changing sources.</li><li>Using relative paths in CI/CD pipelines without packaging the module folder.</li><li>Using main or master branches without version control (can break things later).</li><li>Not testing modules independently before reuse.</li></ul><h3>🏁 Conclusion</h3><p>Choosing the right <strong>module source type</strong> is just as important as writing good Terraform code. It affects how easily your infrastructure can scale, how maintainable your setup is, and how fast your teams can collaborate.</p><p>Use local paths during development, the Terraform Registry for community standards, Git for internal modules, and HTTP/S3 when you need full control over distribution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01a50aa56b78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Terraform State Locking Without DynamoDB : A New S3 Backend Feature]]></title>
            <link>https://medium.com/@sampark02/terraform-state-locking-without-dynamodb-a-new-s3-backend-feature-21be8be3ff45?source=rss-1f488fcaac66------2</link>
            <guid isPermaLink="false">https://medium.com/p/21be8be3ff45</guid>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Sampark Mehrotra]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 15:48:39 GMT</pubDate>
            <atom:updated>2025-04-12T15:48:39.984Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Terraform State Locking Without DynamoDB : A New S3 Backend Feature</strong></p><p>State locking has always been a critical feature in Terraform to prevent race conditions and conflicts during concurrent operations. Until now, if you were using the <strong>S3 backend</strong>, Terraform required a <strong>DynamoDB table</strong> to implement locking.</p><p>But with recent updates, Terraform introduces a <strong>game-changing feature</strong>: <strong>S3-native state locking</strong> — allowing you to manage state locks without DynamoDB.</p><p>Let’s dive into how this works, what’s new, and how to enable it.</p><h3>🚀 What’s New?</h3><p>With the release of Terraform <strong>v1.8+</strong> and enhancements to the <strong>AWS S3 backend</strong>, state locking is now <strong>natively supported at the S3 level</strong>, leveraging <strong>object metadata and conditional requests</strong> — no more DynamoDB!</p><h3>✅ Benefits of S3-Native Locking</h3><ul><li>❌ No need to manage or provision DynamoDB</li><li>✅ Fewer resources to maintain</li><li>✅ Simple backend configuration</li><li>✅ Suitable for smaller teams or cost-conscious setups</li><li>✅ Still prevents concurrent operations on the state file</li></ul><h3>⚙️ How to Enable It</h3><p>In your Terraform backend configuration, simply set the following:</p><pre>terraform {<br>  backend &quot;s3&quot; {<br>    bucket         = &quot;my-terraform-state&quot;<br>    key            = &quot;env/prod/terraform.tfstate&quot;<br>    region         = &quot;us-east-1&quot;<br>    use_lockfile   = true  # Enables S3-managed locking<br>  }<br>}</pre><blockquote><em>✅ No need for </em><em>dynamodb_table anymore!</em></blockquote><p>The use_lockfile = true flag is the key. It tells Terraform to <strong>use S3 object locks and conditional writes</strong> under the hood.</p><h3>💡 How It Works Under the Hood</h3><p>Terraform uses <strong>S3’s object versioning and metadata (like ETag)</strong> to simulate locking:</p><p>When a user runs terraform apply, Terraform fetches the state and keeps track of its ETag. Before writing, it verifies that no one else has modified the file using If-Match headers.</p><p>If another operation has changed the state, it aborts — effectively acting as a <strong>lock</strong>.</p><h3>🔐 Comparison: Old vs New</h3><p>Feature DynamoDB Locking S3 Lockfile (use_lockfile = true) Lock Mechanism DynamoDB item S3 object ETag / conditional writes Additional Resource Yes (DynamoDB) No Setup Complexity Higher Simpler Ideal For Large teams, strict HA Small teams, cost-sensitive setups</p><h3>📝 Things to Keep in Mind</h3><ul><li>Requires <strong>Terraform v1.8+</strong></li><li>May not yet support all advanced locking use cases (e.g., lease durations, TTL)</li><li>Works best when only one CI/CD pipeline modifies the same state file at a time</li></ul><h3>🧪 Example Backend Block Without DynamoDB</h3><pre>terraform {<br>  backend &quot;s3&quot; {<br>    bucket        = &quot;my-tf-bucket&quot;<br>    key           = &quot;prod/terraform.tfstate&quot;<br>    region        = &quot;us-west-2&quot;<br>    encrypt       = true<br>    use_lockfile  = true  # 💡 New addition<br>  }<br>}</pre><h3>✅ When Should You Use It?</h3><ul><li>You’re managing simple infra and want less AWS setup</li><li>You don’t want to deal with provisioning DynamoDB</li><li>You’re running infra updates from a single pipeline or user</li><li>You want to save costs and simplify backend management</li></ul><h3>🧠 Final Thoughts</h3><p>Terraform’s new S3-native locking (use_lockfile = true) is a fantastic step forward in simplifying infrastructure as code. It&#39;s ideal for teams that want to reduce overhead and still benefit from safe, conflict-free state file operations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21be8be3ff45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Terraform Modules: Define, Call, and Use Output]]></title>
            <link>https://medium.com/@sampark02/a-beginners-guide-to-terraform-modules-define-call-and-use-output-910a564d310a?source=rss-1f488fcaac66------2</link>
            <guid isPermaLink="false">https://medium.com/p/910a564d310a</guid>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Sampark Mehrotra]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 15:48:14 GMT</pubDate>
            <atom:updated>2025-04-12T15:48:14.755Z</atom:updated>
            <content:encoded><![CDATA[<p>Terraform modules are the building blocks of reusable infrastructure-as-code. Whether you’re managing a few AWS resources or an entire multi-cloud setup, modules help you organize, reuse, and maintain your code effectively.</p><p>In this article, we’ll cover:</p><ul><li>✅ How to <strong>define</strong> a module</li><li>📦 How to <strong>call</strong> a module from your main Terraform code</li><li>🔁 How to <strong>use output values</strong> from a module and pass them to other resources</li></ul><p>Let’s get started!</p><h3>📁 1. Define a Terraform Module</h3><p>A module is just a folder with Terraform configuration files (main.tf, variables.tf, outputs.tf, etc.).</p><h3>📌 Example: Create an S3 Bucket Module</h3><p><strong>Directory Structure:</strong></p><pre>modules/<br>└── s3_bucket/<br>    ├── main.tf<br>    ├── variables.tf<br>    └── outputs.tf</pre><h3>🧱 main.tf (inside modules/s3_bucket/)</h3><pre>resource &quot;aws_s3_bucket&quot; &quot;this&quot; {<br>  bucket = var.bucket_name<br>  acl    = var.acl<br>}</pre><h3>📥 variables.tf</h3><pre>variable &quot;bucket_name&quot; {<br>  type = string<br>}</pre><pre>variable &quot;acl&quot; {<br>  type    = string<br>  default = &quot;private&quot;<br>}</pre><h3>📤 outputs.tf</h3><pre>output &quot;bucket_arn&quot; {<br>  value = aws_s3_bucket.this.arn<br>}</pre><h3>🔄 2. Call the Module</h3><p>Now in your root Terraform code (e.g., main.tf at the root level), you can call this module:</p><pre>module &quot;my_bucket&quot; {<br>  source      = &quot;./modules/s3_bucket&quot;<br>  bucket_name = &quot;my-terraform-bucket-123&quot;<br>  acl         = &quot;private&quot;<br>}</pre><p>The source can be:</p><ul><li>A local path (as shown above)</li><li>A GitHub repo: source = &quot;git::https://github.com/user/repo.git//modules/s3_bucket&quot;</li><li>A Terraform Registry module</li></ul><h3>📤 3. Use Module Output in Another Resource</h3><p>Let’s say you want to create an <strong>SNS topic policy</strong> that grants access to this bucket using the ARN from the module output:</p><pre>resource &quot;aws_sns_topic&quot; &quot;my_topic&quot; {<br>  name = &quot;my-topic&quot;<br>}</pre><pre>resource &quot;aws_sns_topic_policy&quot; &quot;example&quot; {<br>  arn    = aws_sns_topic.my_topic.arn</pre><pre>  policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [<br>      {<br>        Effect = &quot;Allow&quot;<br>        Principal = &quot;*&quot;<br>        Action = &quot;sns:Publish&quot;<br>        Resource = aws_sns_topic.my_topic.arn<br>        Condition = {<br>          ArnEquals = {<br>            &quot;aws:SourceArn&quot; = module.my_bucket.bucket_arn<br>          }<br>        }<br>      }<br>    ]<br>  })<br>}</pre><blockquote><em>🔗 We’re referencing the module output using </em><em>module.&lt;module_name&gt;.&lt;output_name&gt;.</em></blockquote><h3>✅ Summary</h3><p>Step Action Description 1️⃣ Define a module Create main.tf, variables.tf, and outputs.tf in a folder 2️⃣ Call the module Use module block with source and variables 3️⃣ Use output Reference using module.module_name.output_name</p><h3>💡 Pro Tips</h3><ul><li>Keep modules <strong>small and focused</strong></li><li>Use meaningful input/output variables</li><li>Store common modules in a shared repo</li><li>Use versioning for modules in Git</li></ul><h3>📁 Full Working Directory Structure</h3><pre>project/<br>├── main.tf<br>├── variables.tf<br>├── modules/<br>│   └── s3_bucket/<br>│       ├── main.tf<br>│       ├── variables.tf<br>│       └── outputs.tf</pre><h3>🧠 Final Thoughts</h3><p>Terraform modules are essential for clean, reusable, and scalable infrastructure-as-code. Once you start using them, your projects become much easier to maintain and collaborate on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=910a564d310a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Root Module vs Child Module in Terraform: What’s the Difference and Why It Matters]]></title>
            <link>https://medium.com/@sampark02/root-module-vs-child-module-in-terraform-whats-the-difference-and-why-it-matters-8daad52a5cfc?source=rss-1f488fcaac66------2</link>
            <guid isPermaLink="false">https://medium.com/p/8daad52a5cfc</guid>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Sampark Mehrotra]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 15:47:48 GMT</pubDate>
            <atom:updated>2025-04-12T15:47:48.788Z</atom:updated>
            <content:encoded><![CDATA[<p>Terraform modules help organize infrastructure code into reusable components. But terms like <strong>root module</strong> and <strong>child module</strong> can be confusing when you’re getting started.</p><p>In this article, we’ll break down:</p><ul><li>What is a root module?</li><li>What is a child module?</li><li>Key differences and use cases</li><li>How they work together</li></ul><p>Let’s simplify Terraform modules once and for all!</p><h3>🧱 What is a Root Module?</h3><p>The <strong>root module</strong> is the directory where you run Terraform commands like:</p><pre>terraform init  <br>terraform plan  <br>terraform apply</pre><p>This is usually your <strong>top-level directory</strong>, where Terraform starts evaluating your infrastructure.</p><h3>✅ Example:</h3><pre>project/<br>├── main.tf<br>├── variables.tf<br>├── outputs.tf<br>└── modules/</pre><p>Here, the project/ directory is the <strong>root module</strong>.</p><blockquote><em>💡 Any </em><em>.tf files directly inside the working directory where Terraform is executed are part of the </em><strong><em>root module</em></strong><em>.</em></blockquote><h3>📦 What is a Child Module?</h3><p>A <strong>child module</strong> is any module that is <strong>called from another module</strong> — usually from the root.</p><p>You define it using the module block:</p><pre>module &quot;vpc&quot; {<br>  source = &quot;./modules/vpc&quot;<br>  cidr_block = &quot;10.0.0.0/16&quot;<br>}</pre><p>This vpc module is a <strong>child module</strong> because it’s being used inside the root module.</p><blockquote><em>🔁 Child modules can themselves call other modules — forming a </em><strong><em>module tree</em></strong><em>.</em></blockquote><h3>🧬 Relationship Between Root and Child Modules</h3><p>Think of it like this:</p><pre>Root Module<br> └── calls ──&gt; Child Module (vpc)<br>                    └── calls ──&gt; Child Module (subnets)</pre><p>Terraform processes everything starting from the <strong>root</strong> and follows the hierarchy of module calls.</p><h3>🔄 Example Setup</h3><h3>Root module (main.tf)</h3><pre>module &quot;networking&quot; {<br>  source     = &quot;./modules/vpc&quot;<br>  cidr_block = &quot;10.0.0.0/16&quot;<br>}</pre><h3>Child module (modules/vpc/main.tf)</h3><pre>resource &quot;aws_vpc&quot; &quot;this&quot; {<br>  cidr_block = var.cidr_block<br>}</pre><p>The networking module is a <strong>child</strong> of the root, and the root module triggers its creation.</p><h3>🔍 Key Differences</h3><p>Feature Root Module Child Module Location Where Terraform is executed Called from another module Execution Entry point for terraform CLI Executed as part of the root/module tree Purpose Controls environment-wide resources Encapsulates reusable logic Output/Variables Can expose and consume outputs Typically uses variables.tf and outputs.tf Reusability Usually environment-specific Highly reusable across projects</p><h3>✅ Best Practices</h3><ul><li>Use the <strong>root module</strong> for <strong>environment-specific orchestration</strong></li><li>Use <strong>child modules</strong> for <strong>encapsulated logic</strong> (VPC, RDS, ECS, etc.)</li><li>Avoid putting too much logic in the root module — keep it clean and high-level</li><li>Pass variables clearly and expose outputs only when needed</li></ul><h3>📁 Typical Project Structure</h3><pre>terraform/<br>├── main.tf                  # Root module<br>├── variables.tf<br>├── outputs.tf<br>└── modules/<br>    ├── vpc/                 # Child module<br>    │   ├── main.tf<br>    │   ├── variables.tf<br>    │   └── outputs.tf<br>    └── rds/                 # Another child module</pre><h3>🧠 Final Thoughts</h3><p>Understanding the difference between root and child modules is essential for writing clean, modular, and scalable Terraform code. The <strong>root module</strong> is your environment’s entry point, and <strong>child modules</strong> are the reusable blueprints that keep your infrastructure DRY (Don’t Repeat Yourself).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8daad52a5cfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Provider Inheritance in Terraform with configuration_aliases]]></title>
            <link>https://medium.com/@sampark02/simplifying-provider-inheritance-in-terraform-with-configuration-aliases-ca9e07fa8346?source=rss-1f488fcaac66------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca9e07fa8346</guid>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Sampark Mehrotra]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 18:07:58 GMT</pubDate>
            <atom:updated>2025-04-10T18:07:58.113Z</atom:updated>
            <content:encoded><![CDATA[<p>When using Terraform modules in real-world projects, passing providers (especially <strong>aliased ones</strong>) between modules can be tricky.</p><p>Terraform 1.3+ introduced a powerful feature:</p><h3>👉 configuration_aliases</h3><p>This lets you explicitly <strong>declare which provider aliases your module expects</strong> — making your code cleaner and more predictable.</p><p>In this article, we’ll explore:</p><ul><li>Why provider aliasing matters</li><li>How configuration_aliases simplifies module usage</li><li>A practical example with nested modules</li></ul><h3>🤔 Why Provider Aliases?</h3><p>Provider aliases are used when:</p><ul><li>You deploy to <strong>multiple accounts or regions</strong></li><li>You need <strong>different credentials</strong> or roles</li><li>You have <strong>multi-cloud</strong> setups</li></ul><p>Example:</p><pre>provider &quot;aws&quot; {<br>  alias  = &quot;east&quot;<br>  region = &quot;us-east-1&quot;<br>}</pre><pre>provider &quot;aws&quot; {<br>  alias  = &quot;west&quot;<br>  region = &quot;us-west-2&quot;<br>}</pre><h3>🧩 The Old Way (Before configuration_aliases)</h3><p>Before Terraform 1.3, if you passed an aliased provider to a module, the module had to <strong>declare the aliased provider block itself</strong>, like:</p><pre>provider &quot;aws&quot; {<br>  alias = &quot;east&quot;<br>}</pre><p>And Terraform could <strong>not validate</strong> whether the alias was expected or not.</p><h3>✅ The New Way: configuration_aliases</h3><p>Now, modules can declare <strong>which aliases they need</strong> using configuration_aliases. This makes provider usage more:</p><ul><li><strong>Explicit</strong> (self-documented)</li><li><strong>Safe</strong> (Terraform validates them)</li><li><strong>Modular</strong> (better reusability)</li></ul><h3>🛠️ How to Use configuration_aliases</h3><h3>🔹 In the module (modules/app/main.tf):</h3><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>      configuration_aliases = [ aws.east ]<br>    }<br>  }<br>}</pre><p>Now your module says:</p><blockquote><em>“Hey, I expect to be passed a provider called </em><em>aws.east.”</em></blockquote><p>You can now <strong>use </strong><strong>provider = aws.east</strong> in your resources, but you <strong>don’t need to re-declare the provider block inside the module</strong>. Cleaner code!</p><h3>🧱 Root Module Example</h3><pre>provider &quot;aws&quot; {<br>  alias  = &quot;east&quot;<br>  region = &quot;us-east-1&quot;<br>}</pre><pre>module &quot;app&quot; {<br>  source = &quot;./modules/app&quot;</pre><pre>  providers = {<br>    aws.east = aws.east<br>  }<br>}</pre><p>Now Terraform <strong>knows</strong> the module wants aws.east, and you’re passing it correctly.</p><h3>🚫 Without configuration_aliases?</h3><p>Terraform would throw an error or assume defaults like aws without the alias, leading to confusion and potential misconfigurations.</p><h3>📦 Full Working Example</h3><h3>🔹 Root Module</h3><pre>provider &quot;aws&quot; {<br>  alias  = &quot;east&quot;<br>  region = &quot;us-east-1&quot;<br>}</pre><pre>module &quot;backend&quot; {<br>  source = &quot;./modules/backend&quot;</pre><pre>  providers = {<br>    aws.east = aws.east<br>  }<br>}</pre><h3>🔹 Child Module (modules/backend/main.tf)</h3><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>      configuration_aliases = [ aws.east ]<br>    }<br>  }<br>}</pre><pre>resource &quot;aws_s3_bucket&quot; &quot;bucket&quot; {<br>  bucket   = &quot;my-special-bucket&quot;<br>  provider = aws.east<br>}</pre><h3>🧠 Why It’s Awesome</h3><p>✅ Self-documenting - Modules declare which aliases they use</p><p>✅ No re-declaring - You no longer need provider blocks in every module</p><p>✅ Safer Terraform validates the alias relationships</p><p>✅ Reusable Easier to plug-and-play modules in large architectures</p><h3>🔍 Bonus: Multiple Aliases</h3><pre>terraform {<br>  required_providers {<br>    mycloud = {<br>      source  = &quot;mycorp/mycloud&quot;<br>      version = &quot;~&gt; 1.0&quot;<br>      configuration_aliases = [<br>        mycloud.dev,<br>        mycloud.prod<br>      ]<br>    }<br>  }<br>}</pre><p>This is super handy in multi-account or multi-environment setups!</p><h3>🧠 Final Thoughts</h3><p>configuration_aliases is one of those under-the-radar features that solves a <strong>real pain point</strong> in Terraform: safely managing provider inheritance with aliases.</p><p>If you’re building reusable modules, <strong>embrace </strong><strong>configuration_aliases</strong> — it’s a game-changer for clean, scalable, and predictable Terraform code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca9e07fa8346" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Provider Aliases in Terraform: Deploy to Multiple Accounts or Regions with Ease]]></title>
            <link>https://medium.com/@sampark02/mastering-provider-aliases-in-terraform-deploy-to-multiple-accounts-or-regions-with-ease-ff726e1d3b3c?source=rss-1f488fcaac66------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff726e1d3b3c</guid>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Sampark Mehrotra]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 18:07:44 GMT</pubDate>
            <atom:updated>2025-04-10T18:07:44.177Z</atom:updated>
            <content:encoded><![CDATA[<p>Terraform’s provider block is powerful, but what happens when you need to interact with <strong>multiple regions</strong>, <strong>different AWS accounts</strong>, or even <strong>different cloud providers</strong> in a single configuration?</p><p>That’s where <strong>provider aliases</strong> come into play.</p><p>In this article, you’ll learn:</p><ul><li>What provider aliases are ?</li><li>Why and when to use them ?</li><li>How to pass aliases to modules ?</li><li>Best practices with real-world examples</li></ul><h3>🧠 What Is a Provider Alias?</h3><p>In Terraform, you typically define a provider like this:</p><pre>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}</pre><p>This is fine for single-region or single-account deployments.</p><p>But what if you want to:</p><ul><li>Create a VPC in us-east-1</li><li>Spin up an EC2 instance in us-west-2</li><li>Or assume roles across AWS accounts?</li></ul><p>You’ll need <strong>multiple provider configurations</strong>, each with a unique alias.</p><h3>🔖 Syntax for Aliased Providers</h3><pre>provider &quot;aws&quot; {<br>  alias  = &quot;west&quot;<br>  region = &quot;us-west-2&quot;<br>}</pre><pre>provider &quot;aws&quot; {<br>  alias  = &quot;east&quot;<br>  region = &quot;us-east-1&quot;<br>}</pre><p>You can now reference them using:</p><pre>resource &quot;aws_instance&quot; &quot;web_us_west&quot; {<br>  ami           = &quot;ami-xyz&quot;<br>  instance_type = &quot;t2.micro&quot;<br>  provider      = aws.west<br>}</pre><h3>🧱 Real-World Example: Multi-Region Setup</h3><pre>provider &quot;aws&quot; {<br>  alias  = &quot;us_east&quot;<br>  region = &quot;us-east-1&quot;<br>}</pre><pre>provider &quot;aws&quot; {<br>  alias  = &quot;us_west&quot;<br>  region = &quot;us-west-2&quot;<br>}</pre><pre>resource &quot;aws_s3_bucket&quot; &quot;east_bucket&quot; {<br>  bucket   = &quot;my-east-bucket&quot;<br>  provider = aws.us_east<br>}</pre><pre>resource &quot;aws_s3_bucket&quot; &quot;west_bucket&quot; {<br>  bucket   = &quot;my-west-bucket&quot;<br>  provider = aws.us_west<br>}</pre><p>Without aliases, you’d need to split this into different root modules or workspaces — far less efficient.</p><h3>📦 Passing Aliases to Modules</h3><p>Terraform doesn’t automatically pass aliased providers to modules. You must be explicit:</p><h3>🔹 Root module:</h3><pre>provider &quot;aws&quot; {<br>  alias  = &quot;east&quot;<br>  region = &quot;us-east-1&quot;<br>}</pre><pre>module &quot;network&quot; {<br>  source = &quot;./modules/network&quot;</pre><pre>  providers = {<br>    aws = aws.east<br>  }<br>}</pre><h3>🔹 Child module (modules/network/main.tf):</h3><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>    }<br>  }<br>}</pre><pre>provider &quot;aws&quot; {<br>  alias = &quot;east&quot;<br>}</pre><pre>resource &quot;aws_vpc&quot; &quot;main&quot; {<br>  cidr_block = &quot;10.0.0.0/16&quot;<br>  provider   = aws.east<br>}</pre><h3>✨ Optional Enhancement: configuration_aliases</h3><p>If you’re on Terraform v1.3+, you can simplify even more by using configuration_aliases in the module:</p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source = &quot;hashicorp/aws&quot;<br>      configuration_aliases = [ aws.east ]<br>    }<br>  }<br>}</pre><p>Now you don’t need to declare the provider &quot;aws&quot; block again inside the module — just use provider = aws.east directly in resources.</p><h3>✅ Best Practices</h3><p>✅ Use meaningful alias names (east, tools, prod) Improves readability. ✅ Always explicitly pass aliased providers to modules Terraform won&#39;t inherit them automatically.<br>✅ Use configuration_aliases for clean module design Reduces boilerplate and improves clarity.<br>❌ Don&#39;t use the same alias name in multiple regions/accounts Can lead to confusion and misconfiguration.</p><h3>🧠 Final Thoughts</h3><p>Provider aliases in Terraform give you <strong>fine-grained control</strong> over your infrastructure deployment — especially when juggling regions, environments, or even clouds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff726e1d3b3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use Custom AWS Credentials and Config Files in Terraform]]></title>
            <link>https://medium.com/@sampark02/how-to-use-custom-aws-credentials-and-config-files-in-terraform-38b46f2c4efa?source=rss-1f488fcaac66------2</link>
            <guid isPermaLink="false">https://medium.com/p/38b46f2c4efa</guid>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Sampark Mehrotra]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 18:07:20 GMT</pubDate>
            <atom:updated>2025-04-10T18:07:20.489Z</atom:updated>
            <content:encoded><![CDATA[<p>By default, Terraform uses your ~/.aws/credentials and ~/.aws/config files for AWS authentication. But what if:</p><ul><li>You want to isolate credentials for different environments?</li><li>You’re building CI/CD pipelines where credentials are stored in a custom path?</li><li>Or you’re just tired of switching profiles in the default AWS config?</li></ul><p>In this article, we’ll explore how to <strong>explicitly point Terraform to a custom AWS credentials and config location</strong> using the shared_credentials_files and shared_config_files options in the provider block.</p><h3>🧠 The Problem</h3><p>The default behavior works like this:</p><pre>provider &quot;aws&quot; {<br>  region  = &quot;us-east-1&quot;<br>  profile = &quot;dev&quot;<br>}</pre><p>This uses:</p><ul><li>~/.aws/credentials</li><li>~/.aws/config</li></ul><p>But this can be <strong>limiting</strong> in real-world use cases such as CI pipelines, local testing with sandbox credentials, or multiple users on shared workstations.</p><h3>✅ The Solution: Use Custom Paths</h3><p>Terraform allows you to <strong>override the default paths</strong> by setting:</p><pre>provider &quot;aws&quot; {<br>  region                    = &quot;us-east-1&quot;<br>  profile                   = &quot;dev&quot;<br>  shared_config_files       = [&quot;/Users/s/new_creds_location/config&quot;]<br>  shared_credentials_files  = [&quot;/Users/s/new_creds_location/credentials&quot;]<br>}</pre><p>This tells Terraform:</p><blockquote><em>“Don’t look in the default AWS folder. Use this custom location instead</em></blockquote><h3>📁 Sample Directory Layout</h3><p>Your custom folder might look like this:</p><pre>/Users/s/new_creds_location/<br>├── config<br>├── credentials</pre><h3>credentials file:</h3><pre>[dev]<br>aws_access_key_id = AKIADEV123456<br>aws_secret_access_key = devSecretKey</pre><h3>config file:</h3><pre>[profile dev]<br>region = us-east-1<br>output = json</pre><h3>🧪 Test Your Configuration</h3><p>Try running a simple Terraform plan:</p><pre>terraform init<br>terraform plan</pre><p>If everything is set up correctly, Terraform will authenticate using the custom files — no need to export AWS_PROFILE or rely on the default locations.</p><h3>🛠 Use Case: Multi-Environment Projects</h3><p>Let’s say your folder structure looks like:</p><pre>.<br>├── terraform-dev/<br>│   └── main.tf<br>├── terraform-prod/<br>│   └── main.tf<br>├── creds/<br>    ├── dev/<br>    │   ├── credentials<br>    │   └── config<br>    ├── prod/<br>        ├── credentials<br>        └── config</pre><p>Then in terraform-dev/main.tf:</p><pre>provider &quot;aws&quot; {<br>  region                    = &quot;us-east-1&quot;<br>  profile                   = &quot;dev&quot;<br>  shared_credentials_files  = [&quot;../creds/dev/credentials&quot;]<br>  shared_config_files       = [&quot;../creds/dev/config&quot;]<br>}</pre><p>And in terraform-prod/main.tf:</p><pre>provider &quot;aws&quot; {<br>  region                    = &quot;us-west-2&quot;<br>  profile                   = &quot;prod&quot;<br>  shared_credentials_files  = [&quot;../creds/prod/credentials&quot;]<br>  shared_config_files       = [&quot;../creds/prod/config&quot;]<br>}</pre><p>Now your environments are <strong>completely isolated</strong>.</p><h3>✅ Benefits</h3><p>🔐 Better Security Keep different credentials out of your main home directory.<br>🤹🏼 Multi-user/Multi-env Easily test/dev/prod in parallel without switching profiles.<br>🤖 CI/CD Friendly Store credentials in fixed paths or mounted volumes.<br>📦 No ENV Variables Cleaner than exporting AWS_SHARED_CREDENTIALS_FILE</p><h3>🧠 Final Thoughts</h3><p>Terraform’s shared_credentials_files and shared_config_files options give you <strong>fine-grained control over where your credentials come from</strong>, making your infrastructure code <strong>more secure</strong>, <strong>portable</strong>, and <strong>team-friendly</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38b46f2c4efa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>