<?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 Amjad Nagori on Medium]]></title>
        <description><![CDATA[Stories by Amjad Nagori on Medium]]></description>
        <link>https://medium.com/@amjad30nagori?source=rss-f0ae3122303f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pWXHe2eHPZBAFhMco79JBg.jpeg</url>
            <title>Stories by Amjad Nagori on Medium</title>
            <link>https://medium.com/@amjad30nagori?source=rss-f0ae3122303f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:08:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amjad30nagori/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[Loops in Terraform: Key to Clean and Efficient Code]]></title>
            <link>https://medium.com/@amjad30nagori/loops-in-terraform-key-to-clean-and-efficient-code-1fd96541b54c?source=rss-f0ae3122303f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fd96541b54c</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Amjad Nagori]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 22:19:18 GMT</pubDate>
            <atom:updated>2023-11-01T22:19:18.774Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D2hXdoZX42W5tD3X11ETIQ.gif" /></figure><p>In this article, we are going to explore the power of loops in Terraform. If you already have experience with any other programming language, then you should already be familiar with the benefits of loops and how they help us write clean and efficient code. Like other programming languages, Terraform also offers a variety of looping mechanis that we can choose based on our requirements.</p><h3>Type of Loops in Terraform</h3><ul><li><strong>count</strong></li><li><strong>for_each</strong></li></ul><p>Let’s discuss each of them in detail.</p><h4><strong>count Loop</strong></h4><p>As the name suggests, the count loop in Terraform iterates based on the specified count. You can define how many similar resources you would like to deploy, and with the “count” loop, you can deploy them using a single resource block. In short, the count loop allows you to avoid repeating the same code for similar resources. Let’s see how it helps us iterate through repeated code and make it more clean and efficient.</p><p>Imagine you need to create 3 or more Azure Storage Accounts with similar configurations. Without looping, you would end up with something like the code below, right?</p><pre>resource &quot;azurerm_storage_account&quot; &quot;storageaccount1&quot; {<br>  name                     = &quot;loopstorageacc001&quot;<br>  resource_group_name      = azurerm_resource_group.rg.name<br>  location                 = azurerm_resource_group.rg.location<br>  account_tier             = &quot;Standard&quot;<br>  account_replication_type = &quot;GRS&quot;<br>}<br><br>resource &quot;azurerm_storage_account&quot; &quot;storageaccount2&quot; {<br>  name                     = &quot;loopstorageacc002&quot;<br>  resource_group_name      = azurerm_resource_group.rg.name<br>  location                 = azurerm_resource_group.rg.location<br>  account_tier             = &quot;Standard&quot;<br>  account_replication_type = &quot;GRS&quot;<br>}<br><br>resource &quot;azurerm_storage_account&quot; &quot;storageaccount3&quot; {<br>  name                     = &quot;loopstorageacc003&quot;<br>  resource_group_name      = azurerm_resource_group.rg.name<br>  location                 = azurerm_resource_group.rg.location<br>  account_tier             = &quot;Standard&quot;<br>  account_replication_type = &quot;GRS&quot;<br>}</pre><p>Does this approach look good to you? I’m sure it doesn’t.</p><blockquote>Consider this: What if you wanted to change the “account_replication_type” to “LRS” for all of them? In that case, you would once again have to make changes in all 3 blocks. And what if you had a requirement for 50 blocks? It’s certainly not a efficient way to handle it.</blockquote><blockquote>Of course, if Terraform didn’t provide loops, it wouldn’t be as successful as it is today.</blockquote><p>So, now let’s see how the count loop helps us in this type of scenario.</p><p>Can you imagine that the following code is the replacement for the one above? Even if you want to create 50 storage accounts, you can simply change the count from 3 to 50, and <strong><em>BOOM</em></strong>, there will be 50 Azure Storage Accounts with just one Resource block. That is the power of looping.</p><pre>resource &quot;azurerm_storage_account&quot; &quot;storageaccounts&quot; {<br>  count                    = 3<br>  name                     = &quot;loopstorageacc00${count.index + 1}&quot;<br>  resource_group_name      = azurerm_resource_group.rg.name<br>  location                 = azurerm_resource_group.rg.location<br>  account_tier             = &quot;Standard&quot;<br>  account_replication_type = &quot;GRS&quot;<br>}</pre><p>Now, let me explain how it works and the underlying logic.</p><p>If you’ve noticed, there were two changes we made to the Resource Block to utilize the count loop. First, we added the <strong>count </strong>argument, and second, we appended the storage account name with <strong>${count.index + 1}.</strong></p><p>The <strong>count</strong> argument is used to inform Terraform about how many times this resource block should iterate. In a real-world scenario, we typically use a variable to define the count, and the value of this variable is either passed at the time of execution or taken as input from the user.</p><p>The <strong>${count.index + 1}</strong> part might seem a bit tricky. In this block, <strong>count.index</strong> represents the current index, which generally starts from 0 and increases up to the value provided in the count argument. So in our case, it would be 0, 1, 2. However, the desired index is 1, 2, 3. That’s why we added <strong>+ 1</strong> during each iteration to achieve the desired sequence of 1, 2, 3 instead.</p><p>This would be the result of the above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SgcRUhLndGu7zNx_tCw1ww.png" /><figcaption>Terraform Apply of the count loop code.</figcaption></figure><blockquote>You can also use name = &quot;loopstorageacc${format(&quot;%03d&quot;, count.index + 1)}&quot; to generate three-digit counts like 001, 002, 003. By adding +1, it becomes 001, 002, 003, which results in the desired storage account names.</blockquote><p>This is how the count loop works, and you can even use the count loop with module and data blocks too.</p><p>The only tricky part with the count loop is the reference and output. For example, if you want to create a container in the storage account, it can be challenging to refer to it directly, and the same applies to retrieving the output.</p><p>Typically, we reference the resource or define the output block as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*VKrpN6uHv-N5QGBCwTmudA.png" /></figure><p>However, if the resource block is within a loop, it becomes challenging for outputs or references to identify which specific storage account we are referring to and attempting to reference them may result in the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQ2eqXKmRpnI_OwCLFMevA.png" /></figure><p>So, you will need to define something like the following to create accurate references:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*exDKe_fvsNj_FA935SIgaA.png" /></figure><blockquote>Additionally, you can explore other logics, like using a for loop, to reference or retrieve the output, which we will discuss later on.</blockquote><p>Do you know why we got storage account 2 when referring to 1 in the output?</p><blockquote>Don’t tell me you don’t know! <em>😲</em> Well, okay, because the count loop starts iterating from 0. So when we say 1, it actually corresponds to resource number 2 (remember that <strong>count.index + 1 </strong>login above)</blockquote><p>I hope you now have a better understanding of the count loop. If you still have questions or if there’s anything you’d like to discuss, feel free to post your comments.</p><p>Now, let’s talk about one of my favorites, the <strong>for_each</strong> loop.</p><h4>for_each Loop</h4><p>The for_each loop is one of the best looping mechanisms in Terraform. It greatly aids in simplifying complex, repetitive code by iterating based on the map or list variables. <em>Oh, you&#39;re not familiar with map yet? Let me explain that first.</em></p><blockquote><strong>What is Map?</strong></blockquote><blockquote>A map is a variable type in Terraform that allows you to define a collection of key-value pairs, as shown below:</blockquote><pre>variable &quot;map_variable&quot; {<br>  type = map(string)<br>  default = {<br>    key1 = &quot;value1&quot;<br>    key2 = &quot;value2&quot;<br>    key3 = &quot;value3&quot;<br>  }<br>}</pre><p>So, with the combination of a for_each loop and a map, we can iterate based on the number of key-value pairs present in the map variable. This allows us to not only iterate but also utilize both the key and value in every iteration, which can be passed as argument values. <em>Didn’t understand? That’s why I prefer to explain things practically rather than theoretically </em>😉.</p><p>Let’s take a look at the scenario below and see how the for_each loop can help resolve the complexity.</p><p>Suppose we need to create an Azure Virtual Network with 3 Subnets. How would you do it, as shown below, right?</p><blockquote>I know that there’s another approach where you can reference the subnets inside the Virtual Network resource block itself. I’m not going to use it, because My Article My Wish <em>😁</em> Kidding! Actually that would make this example more complex. If you want to see how for_each can be used in that scenario, you can refer to my Dynamic Blocks article <a href="https://medium.com/@amjad30nagori/what-is-dynamic-block-in-terraform-a-step-by-step-guide-b56b706edd47">here</a>.</blockquote><pre>resource &quot;azurerm_resource_group&quot; &quot;network&quot; {<br>  name = &quot;network&quot;<br>  location = &quot;westeurope&quot;<br>}<br><br>resource &quot;azurerm_virtual_network&quot; &quot;vnet&quot; {<br>  name                = &quot;vnet1&quot;<br>  address_space       = [&quot;10.0.0.0/16&quot;]<br>  location            = azurerm_resource_group.network.location<br>  resource_group_name = azurerm_resource_group.network.name<br>}<br><br>resource &quot;azurerm_subnet&quot; &quot;subnet1&quot; {<br>  name                 = &quot;subnet1&quot;<br>  resource_group_name  = azurerm_resource_group.network.name<br>  virtual_network_name = azurerm_virtual_network.vnet.name<br>  address_prefixes     = [&quot;10.0.1.0/24&quot;]<br>}<br><br>resource &quot;azurerm_subnet&quot; &quot;subnet2&quot; {<br>  name                 = &quot;subnet2&quot;<br>  resource_group_name  = azurerm_resource_group.network.name<br>  virtual_network_name = azurerm_virtual_network.vnet.name<br>  address_prefixes     = [&quot;10.0.2.0/24&quot;]<br>}<br><br>resource &quot;azurerm_subnet&quot; &quot;subnet3&quot; {<br>  name                 = &quot;subnet3&quot;<br>  resource_group_name  = azurerm_resource_group.network.name<br>  virtual_network_name = azurerm_virtual_network.vnet.name<br>  address_prefixes     = [&quot;10.0.3.0/24&quot;]<br>}</pre><p>Now, let’s consider the count loop. Do you think it will work here? <em>Seriously, do you think it will work here? It&#39;s very disappointing</em> 😟😅. Trust me, it will not because you can refer to count.index in the subnet name, but what about the address_prefixes? You can&#39;t create two subnets with the same address_prefixes.</p><p>See how the for_each loop effectively resolves the problem here.</p><pre>variable &quot;subnets&quot; {<br>  type = map(any)<br>  default = {<br>    subnet1 = [&quot;10.0.1.0/24&quot;]<br>    subnet2 = [&quot;10.0.2.0/24&quot;]<br>    subnet3 = [&quot;10.0.3.0/24&quot;]<br>  }<br>}<br><br>resource &quot;azurerm_resource_group&quot; &quot;network&quot; {<br>  name     = &quot;network&quot;<br>  location = &quot;westeurope&quot;<br>}<br><br>resource &quot;azurerm_virtual_network&quot; &quot;vnet&quot; {<br>  name                = &quot;vnet1&quot;<br>  address_space       = [&quot;10.0.0.0/16&quot;]<br>  location            = azurerm_resource_group.network.location<br>  resource_group_name = azurerm_resource_group.network.name<br>}<br><br>resource &quot;azurerm_subnet&quot; &quot;subnets&quot; {<br>  for_each             = var.subnets<br>  name                 = each.key<br>  resource_group_name  = azurerm_resource_group.network.name<br>  virtual_network_name = azurerm_virtual_network.vnet.name<br>  address_prefixes     = each.value<br>}</pre><p>Wow, it looks fascinating, doesn’t it? I told you for_each is one of my favorites 😉</p><p>Let me explain. If you have noticed, we have made a couple of changes in the code:</p><ol><li>First, we introduced a map variable called subnets and assigned default values, with keys representing the subnet name and values representing the address_prefixes list of each subnet.</li><li>Second, we added a new argument called for_each in the block, which is then passed with the subnets map variable. This essentially tells Terraform to iterate based on the number of key-value pairs presents in this map variable.</li><li>Third, we passed each.key in the name argument. This means that with each iteration, it takes the key from the map variable and uses it as the name of the subnet. So, in the first iteration, it would be &#39;subnet1,&#39; then &#39;subnet2,&#39; and finally &#39;subnet3.&#39;</li><li>Similarly, we passed each.value in the address_prefixes. This means that, like each.key, with each iteration, it takes the value from the map variable and uses it as the address_prefixes of the subnet.</li></ol><p>This would be the result of the above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HH3bloNc04xPShStpLAANw.png" /><figcaption>Terraform Apply of the for_each loop code.</figcaption></figure><p>This is how the for_each loop works in Terraform, and you can easily add more subnets by simply adding them to the map variable as new key-value pair without making any changes in the code. I hope it clears all of your doubts or at least provides you with an understanding of the underlying logic.</p><p>I know most of you now have the following question here. <em>Oh, you don’t? Well, I’ll still answer it.</em>😅</p><p>“So, we agree that for_each worked very well with the subnet creation as we had to pass only 2 mandatory arguments. What if we have to pass more than 2? How are we going to use the for_each loop in that case?&quot;</p><p>Let’s take an example of the abvoe subnet block itself and add an optional service_endpoints argument to define associated service endpoints for each subnet.</p><p>First, we will need to make changes to the map variable to define the values of additional arguments in the following format:</p><pre>variable &quot;subnets&quot; {<br>  type = map(any)<br>  default = {<br>    subnet1 = {<br>      address_prefixes  = [&quot;10.0.1.0/24&quot;]<br>      service_endpoints = [&quot;Microsoft.KeyVault&quot;]<br>    }<br>    subnet2 = {<br>      address_prefixes  = [&quot;10.0.2.0/24&quot;]<br>      service_endpoints = [&quot;Microsoft.Sql&quot;]<br>    }<br>    subnet3 = {<br>      address_prefixes  = [&quot;10.0.3.0/24&quot;]<br>      service_endpoints = [&quot;Microsoft.Storage&quot;]<br>    }<br>  }<br>}</pre><p>Secondly, make the changes in the subnet resource block to pass the values in arguments as shown below:</p><pre>resource &quot;azurerm_subnet&quot; &quot;subnets&quot; {<br>  for_each             = var.subnets<br>  name                 = each.key<br>  resource_group_name  = azurerm_resource_group.network.name<br>  virtual_network_name = azurerm_virtual_network.vnet.name<br>  address_prefixes     = each.value[&quot;address_prefixes&quot;]<br>  service_endpoints    = each.value[&quot;service_endpoints&quot;]<br>}</pre><p>See, how simple it is 😉. So, no matter how many arguments you have, you can easily pass them in this way using the for_each loop. The result of the code changes would be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*Zkx2_hY0TEyaP3Xly94IdA.png" /><figcaption>Terrafrom Plan of multi-argument for_each loop.</figcaption></figure><p>Phew, I wasn’t expecting that explaining Terraform’s looping mechanisms would take this long. We even have one more looping mechanism left the for loop. It works in a slightly different way and is mostly used for data transformation. That’s why not included in this article, but it will be surely the topic of my next one.</p><p>Oh, did you guys notice that I missed the example of something I mentioned in the for_each loop description? No? Then you&#39;re not paying attention ☹️. Let me tell you, I mentioned that the for_each loop works with list variables too. Let&#39;s see how?</p><pre>variable &quot;rgs&quot; {<br>  type    = list(any)<br>  default = [&quot;rg1&quot;, &quot;rg2&quot;, &quot;rg3&quot;]<br>}<br><br>resource &quot;azurerm_resource_group&quot; &quot;rg&quot; {<br>  for_each = var.rgs<br>  name     = each.value<br>  location = &quot;westeurope&quot;<br>}</pre><p>With lists, we are going to pass only each.value. It looks simple isn’t it? Let&#39;s execute the code and see if it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vHcs3DJUps8RCU8VUfYoQ.png" /></figure><p>Wait, but I said it works with list 😐. So, why did it fail and say that for_each is not suitable for list type? Yes, it does work, but you have to take special care of the for_each argument when using a list, as shown below:</p><pre>variable &quot;rgs&quot; {<br>  type    = list(any)<br>  default = [&quot;rg1&quot;, &quot;rg2&quot;, &quot;rg3&quot;]<br>}<br><br>resource &quot;azurerm_resource_group&quot; &quot;rg&quot; {<br>  for_each = toset(var.rgs)<br>  name     = each.value<br>  location = &quot;westeurope&quot;<br>}</pre><p>You will need to convert the list into a set first, which can be done using the toset() function.</p><p>But why here and not in a map type? Because for_each works with unique identifiers, and in a map variable, keys are always unique. However, in a list, it&#39;s not guaranteed, and you can have similar values defined more than once. So by using the toset() function, we are essentially ensuring that this list doesn&#39;t contain similar values, and all values are unique identifiers, which satisfies the for_each requirement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kIvAVfxOf5faMscwL1Nkqw.png" /><figcaption>Terrafrom Plan output of for_each with list.</figcaption></figure><p>I hope that with this article, you’ve gained a good understanding of looping mechanisms in Terraform. If you still have any questions or find any mistakes in this article, please feel free to leave a comment or reach out to me on <a href="https://www.linkedin.com/in/amjadnagori">LinkedIn</a> 😉.</p><p>Happy Terraforming! <em>Wait, is ‘Terraforming’ even a word, or am I being quirky here? </em>😂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fd96541b54c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Dynamic Blocks in Terraform: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@amjad30nagori/what-is-dynamic-block-in-terraform-a-step-by-step-guide-b56b706edd47?source=rss-f0ae3122303f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b56b706edd47</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Amjad Nagori]]></dc:creator>
            <pubDate>Sat, 21 Oct 2023 22:51:31 GMT</pubDate>
            <atom:updated>2026-01-05T12:09:35.054Z</atom:updated>
            <content:encoded><![CDATA[<p>The Dynamic Block in Terraform is one of the most useful options for making your code dynamic. Previously, we could use dynamic conditions like ‘for_each’ and ‘if’ conditions at the resource block level. However, with the dynamic block, we can also apply the same logic to resource sub-blocks or nested blocks, such as ‘Identity’ in an Azure SQL Server resource block</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*tQus39jpr58QvnaIHnmzSA.png" /><figcaption>Example of Resource Block and Nested Block</figcaption></figure><p>The dynamic block is very useful in a couple of scenarios for creating error-free, dynamic code that can iterate based on the variable values you are passing, such as:</p><h4><strong><em>Scenario 1:</em></strong></h4><p>Let’s assume there is a scenario where you want to enable the system-managed identity for a resource, such as Azure SQL Server, only if the variable ‘managed_identity_enable’ is set to true. Otherwise, it should not enable the managed identity. Let’s see how you can achieve this.</p><p>First, let’s understand the resource block for Azure SQL Server:</p><p>This is the basic Terraform resource block for creating an Azure SQL Server.</p><pre>resource &quot;azurerm_resource_group&quot; &quot;sqlrg&quot; {<br>  name     = &quot;sql-rg&quot;<br>  location = &quot;westeurope&quot;<br>}<br><br>resource &quot;azurerm_mssql_server&quot; &quot;sqlserver&quot; {<br>  name                         = &quot;sqlserver5474&quot;<br>  resource_group_name          = azurerm_resource_group.sqlrg.name<br>  location                     = azurerm_resource_group.sqlrg.location<br>  version                      = &quot;12.0&quot;<br>  administrator_login          = &quot;missadministrator&quot;<br>  administrator_login_password = &quot;thisIsKat11&quot;<br>}</pre><p>Now, let’s say we need to enable the managed identity. In that case, we will add the ‘Identity’ nested block as shown below:</p><pre>resource &quot;azurerm_resource_group&quot; &quot;sqlrg&quot; {<br>  name     = &quot;sql-rg&quot;<br>  location = &quot;westeurope&quot;<br>}<br><br>resource &quot;azurerm_mssql_server&quot; &quot;sqlserver&quot; {<br>  name                         = &quot;sqlserver5474&quot;<br>  resource_group_name          = azurerm_resource_group.sqlrg.name<br>  location                     = azurerm_resource_group.sqlrg.location<br>  version                      = &quot;12.0&quot;<br>  administrator_login          = &quot;missadministrator&quot;<br>  administrator_login_password = &quot;thisIsKat11&quot;<br><br>  identity {<br>    type = &quot;SystemAssigned&quot;<br>  }<br><br>}</pre><p>Now, I would like to make this ‘Identity’ block dynamic based on my requirements, enabling it only when the variable ‘managed_identity_enable’ is set to true. Let’s see how we can achieve this using a Dynamic Block.</p><p>First, let’s declare a variable named ‘managed_identity_enable’ with the type ‘boolean’.</p><pre>variable &quot;managed_identity_enable&quot; {<br>  type = bool<br>  description = &quot;Set to true for creating a managed identity in the Azure SQL Server. Default is false.&quot;<br>}</pre><p>Let’s configure the Dynamic block for ‘Identity’:</p><pre>resource &quot;azurerm_mssql_server&quot; &quot;sqlserver&quot; {<br>  name                         = &quot;sqlserver5474&quot;<br>  resource_group_name          = azurerm_resource_group.sqlrg.name<br>  location                     = azurerm_resource_group.sqlrg.location<br>  version                      = &quot;12.0&quot;<br>  administrator_login          = &quot;missadministrator&quot;<br>  administrator_login_password = &quot;thisIsKat11&quot;<br><br>  dynamic &quot;identity&quot; {<br>    for_each = var.managed_identity_enable == true ? [1] : [ ]<br>    content {<br>      type = &quot;SystemAssigned&quot;<br>    }<br>  }<br>}</pre><p>Now, let me explain the logic of using the dynamic block:</p><ol><li>First you need to replace the <strong>“identity”</strong> with <strong>dynamic “identity” </strong>to let Terraform knows that this will be used dynamically.</li><li>Next, configure the conditional expression. Let me break down the one we’ve used.:</li></ol><pre>for_each = var.managed_identity_enable == true ? [1] : [ ]</pre><p>This conditional expression is a combination of ‘<strong>for_each’ </strong>loop with ‘<strong>if’ </strong>condition.</p><p><strong>if_condition </strong>— “var.managed_identity_enable == true ? [1] : [ ]”</p><blockquote><strong>‘?’</strong> operator signifies that the condition is true, and it returns ‘for_each = [1]’ (a single element).</blockquote><blockquote><strong>‘:’ </strong>operator represents the else case, which means the condition is false, and it returns ‘for_each = []’ (an empty list).</blockquote><p><strong>‘for_each’</strong> — Then, it executes the dynamic block for each element in the list. If ‘for_each’ is set to [1], it will execute the dynamic block; if it’s an empty list, it will skip the block.</p><p><strong>Now, Let’s see dynamic block in action:</strong></p><p>If var.managed_identity_enable is <strong>false</strong>, then-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aAsNjKkqxSjaeZKTTPmZHA.png" /><figcaption>managed_identity_enable == false</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VUXE1iFy1IuVQ63vCbEozw.png" /></figure><p>If var.managed_identity_enable is <strong>true </strong>(we didn’t make any other changes in the code), then-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QssidGO5KiqkJOjwnLW5Q.png" /><figcaption>managed_identity_enable == true</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GMDUxuDYWm0urzxX740WjA.png" /></figure><p>In the example above, you could see how the nested block dynamically works based on the value of the ‘managed_identity_enable’ variable without requiring any other changes in the code.</p><h4>Scenario 2:</h4><p>Another scenario, and one of my favorites, there are some Azure Resource Blocks in Terraform that have nested blocks that can be defined multiple times, such as the ‘subnet’ nested block in the ‘Virtual Network’ resource block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*SQepXMc5ssgKqCcIFF9ccQ.png" /><figcaption>Example of Repetitive Nested Blocks</figcaption></figure><p>In this type of scenario, we can use Dynamic blocks with a <strong>‘for_each’</strong> loop to extract the values for Nested Blocks from a variable of ‘map’ type, thus avoiding the need for repetitive and complex code.</p><p>Let’s explore how to use Dynamic blocks in this scenario:</p><p>First, declare a variable named ‘network_subnets’ with the type ‘map’ and a default value for the subnet (we are assigning a default value here just to keep it simple; in an actual scenario, you would typically use a terraform.tfvars file or pass the values through a pipeline.)</p><pre>variable &quot;network_subnets&quot; {<br>  description = &quot;Map of subscriptions.&quot;<br>  type        = map(string)<br>  default = {<br>    subnet1 = &quot;10.0.1.0/24&quot;<br>    subnet2 = &quot;10.0.2.0/24&quot;<br>    subnet3 = &quot;10.0.3.0/24&quot;<br>  }<br>}</pre><p>Now, let’s define the logic for the Dynamic block in the Virtual Network resource block.</p><pre>variable &quot;network_subnets&quot; {<br>  description = &quot;Map of subscriptions.&quot;<br>  type        = map(string)<br>  default = {<br>    subnet1 = &quot;10.0.1.0/24&quot;<br>    subnet2 = &quot;10.0.2.0/24&quot;<br>    subnet3 = &quot;10.0.3.0/24&quot;<br>  }<br>}<br><br>resource &quot;azurerm_resource_group&quot; &quot;vnetrg&quot; {<br>  name     = &quot;vnet-rg&quot;<br>  location = &quot;westeurope&quot;<br>}<br><br>resource &quot;azurerm_virtual_network&quot; &quot;vnet&quot; {<br>  name                = &quot;example-network&quot;<br>  location            = azurerm_resource_group.vnetrg.location<br>  resource_group_name = azurerm_resource_group.vnetrg.name<br>  address_space       = [&quot;10.0.0.0/16&quot;]<br><br>  dynamic &quot;subnet&quot; {<br>    for_each = var.network_subnets<br>    content {<br>      name           = subnet.key<br>      address_prefix = subnet.value<br>    }<br>  }<br>}</pre><p>This code will create a new Virtual Network with 3 subnets defined in the ‘network_subnets’ variable.</p><p>Let me explain the logic of using the dynamic block in this scenario:</p><ol><li>In this Dynamic Block, only the ‘for_each’ condition is used, and we are passing a map variable with key-value pairs.</li><li>Since we can define subnet nested blocks multiple times within the Virtual Network block, the ‘for_each’ loop here accomplishes the same based on the values provided in ‘network_subnets.’</li><li>It takes the first value, for example, ‘subnet1 = “10.0.1.0/24,” and passes it through the content block, where we specify that the Subnet name should be the Key and the Address Prefix should be the value from the map variable. It does the same for the second, third, and subsequent values, using them as Subnet names and Address Prefixes.</li></ol><blockquote>If you have experience working with ‘for_each’ loops, you’ll notice a slight difference here. Typically, when using a ‘for_each’ loop, we assign values as <strong>‘each.key’ </strong>and <strong>‘each.value.’</strong> However, in the dynamic block, we need to replace <strong>‘each’</strong> with the <strong>name of the block</strong>, which, in this case, is <strong>‘subnet.’</strong></blockquote><p>Let’s see this in action:</p><p>Using the example provided, it will create three subnets: ‘subnet1,’ ‘subnet2,’ and ‘subnet3.’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*HLJxb95FqJa7LxiovtdUMg.png" /></figure><p>Now, let’s add a couple more values to the ‘network_subnets’ variable without making any other changes to the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*IVeo4ThugRwv3Cv5WnMXwA.png" /></figure><p>Let’s see the impact of this change now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*a9x97IPpAePpb0IarB1UMw.png" /></figure><p>Now, it will dynamically create the 5 subnets defined in the ‘network_subnets’ variable.</p><p><strong>Scenario 3</strong></p><p>Continuing from Scenario 2, let’s assume you need to pass security group values as well in the subnet nested block. However, in the variable, you can only define key-value pairs. How can you pass three or more values using a Dynamic block in the nested block? Something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ALURcSTJiJLmGYqM5kkZxg.png" /></figure><p>Then, let’s see how you can pass these values through a map and dynamic block</p><p>Firstly, now the network_subnets variable will not be the map of string but map of map of string (I know it sounds weird but this is what it is :D), like below.</p><p>First, note that the ‘network_subnets’ variable will no longer be a map of strings but a map of maps of strings (I know it sounds weird but this is what it is :D), let’s have a look:</p><pre>variable &quot;network_subnets&quot; {<br>  description = &quot;Map of subscriptions.&quot;<br>  type        = map(map(string))<br>  default = {<br>    subnet1 = {<br>      address_prefix = &quot;10.0.1.0/24&quot;<br>      security_group = &quot;/subscriptions/xxxxx/resourceGroups/vnetrg/providers/Microsoft.Network/networkSecurityGroups/subnet1-nsg&quot;<br>    }<br>    subnet2 = {<br>      address_prefix = &quot;10.0.2.0/24&quot;<br>      security_group = &quot;/subscriptions/xxxxx/resourceGroups/vnetrg/providers/Microsoft.Network/networkSecurityGroups/subnet2-nsg&quot;<br>    }<br>    subnet3 = {<br>      address_prefix = &quot;10.0.3.0/24&quot;<br>      security_group = &quot;/subscriptions/xxxxx/resourceGroups/vnetrg/providers/Microsoft.Network/networkSecurityGroups/subnet3-nsg&quot;<br>    }<br>  }<br>}</pre><p>Let’s see how it will work with Dynamic block now.</p><pre>variable &quot;network_subnets&quot; {<br>  description = &quot;Map of subscriptions.&quot;<br>  type        = map(map(string))<br>  default = {<br>    subnet1 = {<br>      address_prefix = &quot;10.0.1.0/24&quot;<br>      security_group = &quot;/subscriptions/xxxxx/resourceGroups/vnetrg/providers/Microsoft.Network/networkSecurityGroups/subnet1-nsg&quot;<br>    }<br>    subnet2 = {<br>      address_prefix = &quot;10.0.2.0/24&quot;<br>      security_group = &quot;/subscriptions/xxxxx/resourceGroups/vnetrg/providers/Microsoft.Network/networkSecurityGroups/subnet2-nsg&quot;<br>    }<br>    subnet3 = {<br>      address_prefix = &quot;10.0.3.0/24&quot;<br>      security_group = &quot;/subscriptions/xxxxx/resourceGroups/vnetrg/providers/Microsoft.Network/networkSecurityGroups/subnet3-nsg&quot;<br>    }<br>  }<br>}<br><br>resource &quot;azurerm_resource_group&quot; &quot;vnetrg&quot; {<br>  name     = &quot;vnet-rg&quot;<br>  location = &quot;westeurope&quot;<br>}<br><br>resource &quot;azurerm_virtual_network&quot; &quot;vnet&quot; {<br>  name                = &quot;example-network&quot;<br>  location            = azurerm_resource_group.vnetrg.location<br>  resource_group_name = azurerm_resource_group.vnetrg.name<br>  address_space       = [&quot;10.0.0.0/16&quot;]<br><br>  dynamic &quot;subnet&quot; {<br>    for_each = var.network_subnets<br>    content {<br>      name           = subnet.key<br>      address_prefix = subnet.value[&quot;address_prefix&quot;]<br>      security_group = subnet.value[&quot;security_group&quot;]<br>    }<br>  }<br><br>}<br></pre><p>The dynamic block will be the same as in Scenario 2, with the only difference being the way values are passed. In this approach, you can specify the keys for the subnet’s value block in the ‘network_subnets’ variable, such as ‘address_prefix’ and ‘security_group.’</p><p>The output will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ALURcSTJiJLmGYqM5kkZxg.png" /></figure><p><strong>That’s all</strong> about the Dynamic block and its various use cases.</p><p>Hope it clears all of your doubts and now you understand the Dynamic block and it’s logic better.</p><p>I hope this has clarified any doubts you may have had, and now you have a better understanding of the Dynamic block and its logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b56b706edd47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Free Website Hosting & SSL Certificate with Azure Static Web App]]></title>
            <link>https://medium.com/@amjad30nagori/free-website-hosting-ssl-certificate-with-azure-static-web-app-f26df8f39c51?source=rss-f0ae3122303f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f26df8f39c51</guid>
            <category><![CDATA[azure-web-app]]></category>
            <category><![CDATA[free-website-hosting]]></category>
            <category><![CDATA[microsoft-azure]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-static-web-app]]></category>
            <dc:creator><![CDATA[Amjad Nagori]]></dc:creator>
            <pubDate>Tue, 10 Jan 2023 13:21:42 GMT</pubDate>
            <atom:updated>2023-01-10T13:45:21.049Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Host your static website in Azure without paying a single penny, it will even provide you with a free managed SSL certificate and on top of that you can integrate your GitHub repository directly with Azure Static Web App using GitHub Action to get CI/CD benefits in just a couple of clicks. What else do you want? ;)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*385igwdROcDYuRxJ-_yEdQ.jpeg" /></figure><p><strong>Top benefits of Azure Static Web App apart from being free:</strong></p><ol><li>Free managed SSL Certificate which will auto-renew; you don’t need to worry about the expiry date.</li><li>Free bandwidth overage.</li><li>Supports 2 custom domains.</li><li>You can configure up to 3 staging environments.</li><li>Integrate with Managed Azure Function.</li></ol><p><strong>How to deploy a website to Azure Static Web App?</strong></p><p>Let’s assume your code is on your local machine so first, we will have to push the code to GitHub Repository. If it’s already in GitHub then skip Step 1 to Step 9.</p><p><strong>Push your code to GitHub Repository</strong></p><p><strong>Step 1:</strong> Go to <a href="https://github.com/">https://github.com</a> and <strong>Sign-in</strong> if you already have an account or <strong>Sign-up</strong> to create one if you don’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t502pKCn0rtakgSpk90IKA.png" /></figure><p><strong>Step 2:</strong> Once you signed in, create a new Repository by clicking on New or you can also use an existing one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qAr4W4lh0hFRiJGjXdkqQQ.png" /></figure><p><strong>Step 3:</strong> Provide <strong>Repository name </strong>and<strong> Description</strong>, select <strong>Private </strong>to keep your code internally and enable <strong>Add a README file</strong> to initialize the repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSMX-9ndQFvEZ_Jd1nQKSw.png" /></figure><p><strong>Step 4:</strong> Scroll down and click on <strong>Create repository.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxHg4t6ubhkHixaocrP4VA.png" /></figure><p><strong>Step 5:</strong> Now, let’s copy the Clone URL by clicking on <strong>Code</strong> and the <strong>Copy icon</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TCvohdZTseCVL5y8vCoyaQ.png" /></figure><p><strong>Step 6:</strong> Now download theGit tool in your local machine by following this <a href="https://git-scm.com/downloads">URL</a>.</p><p><strong>Step 7:</strong> Now open <strong>Command Prompt</strong> (if you have Windows) or <strong>CLI </strong>(in Mac and Linux) on your local machine and go to your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*90F7afAZhgtMnwCaT_89HQ.png" /></figure><p><strong>Step 8:</strong> Run the below commands to push your code from local machine to GitHub Repository.</p><pre>git init<br><br>git remote add origin &lt;URL Copied in Step 5&gt;<br><br>git pull origin main<br><br>git branch -M main<br><br>git add .<br><br>git commit -m &quot;Initial Push&quot;<br><br>git push origin main</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XGG2QoGDmJoQLJU4R3fqWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*LYK9yCzLeRYYpUNvQa1vYg.png" /></figure><p><strong>Step 9:</strong> Once all the commands are executed successfully, you should be able to see your code in GitHub Repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-3h673X--qFYv1H5hMeXA.png" /></figure><p><strong>Deploy and configure Azure Static Web App</strong></p><p><strong>Step 10:</strong> Login into Azure Portal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*QF3bezwdMZAU5J4B.png" /></figure><p><strong>Step 11:</strong> Search for <strong>Static Web App</strong> and click on <strong>Create</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*Y5jfuxmA32b_NbDhGItePA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*u_N5T3SAT0247wd3JRvwXg.png" /></figure><p><strong>Step 12:</strong> Select <strong>Subscription</strong>, <strong>Resource Group</strong> and provide <strong>Name </strong>for your Static Web App resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3wrH3iEw-UPIJCoVxnD2QA.png" /></figure><p><strong>Step 13:</strong> Scroll down and choose the <strong>Plan type</strong> to <strong>Free</strong>, <strong>location </strong>and <strong>Source </strong>to <strong>GitHub</strong>; Click on <strong>Sign in with GitHub</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y6WDLeMHHXzLpQI_GuHJFQ.png" /></figure><p><strong><em>Plan Comparison:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*-Ykr6j5QlluNoQHZycsA7g.png" /></figure><p><strong>Step 14:</strong> Login with your GitHub credentials and click on <strong>Authorize Azure-App-Service-Static-Web-Apps.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*PO9HgZ9DuAZuCTwaaGMYKA.png" /></figure><p><strong>Step 15:</strong> Select <strong>Organization</strong>, <strong>Repository </strong>and <strong>Branch </strong>of your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ete0mhWedG6lPUMvP8kgsw.png" /></figure><p><strong>Step 16:</strong> Select the<strong> Build Presets</strong> based on your <strong>framework</strong>, if it’s just HTML then select <strong>Custom </strong>with default options; Click on <strong>Review + create</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*osQv1VUXjBeqsOlUTAwLpw.png" /></figure><p><strong>Step 17:</strong> Click on <strong>Create</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*YWUsvbucyTEtbV76FfexuA.png" /></figure><p><strong>Step 18:</strong> As soon as your Static Web App is created, it will automatically trigger the deployment with GitHub Action Workflow (which you can see in your GitHub portal).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zA6RO59C-B60Y0aJG-dZlQ.png" /></figure><p>Your website will be ready as soon as this workflow is completed.</p><p><strong>Step 19: </strong>Now you can access your website by using default URL of Static Web App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZIhkcm0EjL2ha3Q7NJe1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCk6dkVbfx_xcEJ5vKBMGw.png" /></figure><p><strong>Configure Custom Domains for your website</strong></p><blockquote>If you are planning to configure apex or root domain as your Custom Domain like <a href="https://cloudgodown.com/">https://cloudgodown.com</a> (without any subdomain) then move your domain to Azure Public DNS first as most of the domain provider doesn’t support Alias records which will be required for that.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*yZBDfJnYrP_ID_wLmFpzPw.png" /><figcaption><a href="https://learn.microsoft.com/en-us/azure/static-web-apps/custom-domain">https://learn.microsoft.com/en-us/azure/static-web-apps/custom-domain</a></figcaption></figure><p><strong>Step 20:</strong> Open your <strong>Static Web App</strong> in Azure Portal and click on <strong>Custom Domains</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42GwHL5tRL0Qb1QTYV9Ikw.png" /></figure><p><strong>Step 21:</strong> Click on <strong>Add </strong>and choose your DNS provider option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*GDiGWHoebTfxrBxPQpDqDQ.png" /></figure><p><strong>Step 22:</strong> Provide your <strong>Domain name</strong> and click on <strong>Next</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*nyHmsvT6Uk1B_A7XRJv34w.png" /></figure><blockquote>My Domain Provider is Godaddy which doesn’t support alias record and that’s why I am using Custom Domain with a subdomain like https://<strong>www.</strong>cloudgodown.com</blockquote><p><strong>Step 23:</strong> Select <strong>CNAME </strong>in <strong>Hostname record type</strong>; Copy <strong>Value</strong> and click on <strong>Add</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*KT0qAZAohTruFA6CelxBtw.png" /></figure><p><strong>Step 24:</strong> Now create a <strong>CNAME record </strong>with the same <strong>Host</strong> and <strong>Value</strong> in your Domain Provider.</p><p><em>For me, Domain Provider is Godaddy so it looks like this-</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8pK4gRcZYAOqwjmpvyRMA.png" /></figure><p><strong>Step 25:</strong> Wait till the status of your domain is changed to <strong>Validated </strong>(it might take a few mins).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QtOAWBuXepA7QuFG4ld2Tg.png" /></figure><p><strong>Your website is ready now with a free SSL Certificate.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TARb4sZePuzPpLwysgpKsA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f26df8f39c51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Start and Stop Azure VM without Azure Access]]></title>
            <link>https://medium.com/@amjad30nagori/start-stop-azure-vm-without-azure-access-1d37e96c1b71?source=rss-f0ae3122303f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d37e96c1b71</guid>
            <category><![CDATA[automation-account]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-vm]]></category>
            <category><![CDATA[azure-virtual-machines]]></category>
            <category><![CDATA[azure-automation]]></category>
            <dc:creator><![CDATA[Amjad Nagori]]></dc:creator>
            <pubDate>Thu, 05 Jan 2023 14:28:45 GMT</pubDate>
            <atom:updated>2023-01-06T10:04:12.181Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>This article will help you set up the workflow to provide access to Start and Stop Azure Virtual Machine without giving Azure Access.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l2v9j4xuYvtMcJq5u_rQUA.jpeg" /></figure><p><strong><em>Have you ever come across a situation where someone needs to Start and Stop the Azure Virtual Machine but you don’t want to create their Azure Account</em></strong><em>?</em><strong><em> If yes, then you are at the right place. Follow the below steps to get it done.</em></strong></p><p>To set up this mechanism we are going to use Azure Automation Account (A hidden gem in Azure) with PowerShell workflow.</p><p><strong>Deploy and configure Azure Automation Account.</strong></p><p><strong>Step 1:</strong> Login into Azure Portal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2r3SQJx-Lnhsk7PrzrHlXg.png" /></figure><p><strong>Step 2:</strong> Search for <strong>Automation Accounts</strong> and click on <strong>Create</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*IJbJ9922AUzygQbkMYNNTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*JeAgl5WE4Y_c4vexDLdGzA.png" /></figure><p><strong>Step 3:</strong> Keep all the settings default and click on <strong>Review and Create</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UsouWa8pe5715HyvJFzTfQ.png" /></figure><p><em>Note: You can change Managed Identity from System to User assigned in the Advanced tab if required.</em></p><p><strong>Step 4:</strong> Once Automation Account has been created, you will have to assign the required permission either on the Subscription level or Resource Group or individual VM (which you want to stop/start) to the managed identity of the Automation account.</p><blockquote><strong><em>This step is very critical in terms of security and you will have to be very careful while assigning the permission because this automation doesn’t require any authentication and it may lead to providing stop/start permission to the VMs which might not be in scope.</em></strong></blockquote><p>For now, let’s assume we want to stop/start only 1 VM called <strong>“azvm1”</strong> through this automation.</p><p><strong>Step 5:</strong> Open Virtual machine <strong>“azvm1”</strong> in portal.</p><p>Go to A<strong>ccess control (IAM), </strong>click on <strong>Add, </strong>and select <strong>Add role assignment.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvRzJ84TJYwiVGlJBaET7g.png" /></figure><p><strong>Step 6:</strong> Search and select <strong>Virtual Machine Contributor</strong> role and click on <strong>Next</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-P7sfGyLyljTyJepQKGFHQ.png" /></figure><p><strong>Step 7:</strong> Select <strong>Managed Identity</strong> and click on <strong>+Select members</strong>.</p><p>Select <strong>Automation Account</strong> from <strong>Managed identity </strong>drop-down and click on your Automation Account so it can move to <strong>Selected members </strong>section.</p><p>Click on <strong>Select </strong>and then <strong>Next</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DzutSE3FKMMe2vpepMUJVA.png" /></figure><p>Azure Automation Account is ready for the action now.</p><p><strong>Create Runbook with PowerShell Workflow.</strong></p><p><strong>Step 1:</strong> Go to our <strong>Azure Automation Account, </strong>select <strong>Runbooks </strong>and click on <strong>Create a runbook</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1AlL84-6sNeHnwUXYqy4-w.png" /></figure><p><strong>Step 2:</strong> Select Runbook type to <strong>PowerShell Workflow</strong> and click on <strong>Create</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1z-00XYx5aZKV3CcgYCrvA.png" /></figure><p><strong>Step 3:</strong> Once runbook is created then copy below code into it and click on <strong>Save</strong> &amp; <strong>Publish.</strong></p><pre>workflow vm-stop-start<br>{<br>    param<br>    (<br>        [object]$WebhookData<br>    )<br>    inlinescript {<br>        Connect-AzAccount -Identity<br><br>        $WebhookBody =  $using:WebhookData.RequestBody<br>        $webhookBodyObject = $WebhookBody | ConvertFrom-JSON<br><br>        $vm = $webhookBodyObject.vm<br>        $stopOrStart = $webhookBodyObject.stopOrStart<br><br><br>        if ($stoporstart -eq &quot;S&quot;)<br>        {<br>            Get-AzVM -Name $vm | Start-AzVM<br>        }<br>        elseif ($stoporstart -eq &quot;X&quot;)<br>        {<br>            Get-AzVM -Name $vm | Stop-AzVM -Force<br>        }<br>        else<br>        {<br>            Write-Warning &quot;Invalid Argument: $stoporstart&quot;<br>        }<br><br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHwI_p2Go_q6Uhnc5Uop9w.png" /></figure><p><em>Note: Make sure Runbook and Workflow name is the same.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YzaLaxqOnnI3Z1YzRjRmrw.png" /></figure><p><strong>Step 4:</strong> Now go to <strong>Webhooks</strong> and click on <strong>Add Webhook</strong> in Runbook side tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*AAbMgXzgcSCUkvBU7JIGCg.png" /></figure><p><strong>Step 5:</strong> Click on <strong>Create new webhook</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-zQdZDLFy9QRBU0CsVQygQ.png" /></figure><p><strong>Step 6: </strong>Provide webhook <strong>Name</strong>, select <strong>Yes</strong> for <strong>Enabled</strong> and choose an <strong>Expiry</strong> date for your webhook URL.</p><p><em>Copy URL and paste it somewhere as you will not be able to see this URL again and we are going to use in our main script.</em></p><blockquote><strong><em>This URL should be stored/shared securely as it can authenticate and execute the Runbook from anywhere.</em></strong></blockquote><p>Click on <strong>OK</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0Kx5FJrIkbmkTBBLaEPvQ.png" /></figure><p><strong>Step 7:</strong> Click on <strong>Parameters and run settings</strong> and click on <strong>OK </strong>with default settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*alOsyN6K3vb0Ccd4XW-LKQ.png" /></figure><p><strong>Step 8:</strong> Click on <strong>Create.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KamT6IvhrU1vkY3AFDBCng.png" /></figure><p>Now we are ready with Azure Automation Account configuration and can use the Webhook URL as an API to stop or start the VM with tools of your choice like PowerShell, Postman, Curl, etc.</p><blockquote><strong><em>All of the above steps are one-time task and we can share below steps to whom you want to provide access to Stop or Start the VM without providing them access to Azure.</em></strong></blockquote><p><strong>PowerShell Script to trigger the Runbook via Webhook URL.</strong></p><p><strong>Step 1:</strong> Open PowerShell ISE and copy below code into it.</p><pre># Runbook Webhoor URL (Replace this URL with your Runbook Webhook)<br><br>$uri = &quot;https://xxxxxxxxxxxxxxxxxxx.webhook.eus2.azure-automation.net/webhooks?token=xxxxxxxxxxxxxxxxxxx&quot;<br><br># Provide your inputs<br><br>$vm=Read-Host &quot;Virtual Machine Name &quot;<br>$stopOrStart = Read-Host &quot;[S] Start [X] Stop &quot;<br><br># Trigger Webhook<br><br>if ($stoporstart -eq &quot;S&quot;)<br>{<br>    $params = @{&quot;vm&quot;=$vm;&quot;stopOrStart&quot;=$stopOrStart}<br>    $body = ConvertTo-Json -InputObject $params<br>    $webresp = Invoke-WebRequest -Method Post -Uri $uri -Body $body -Verbose -UseBasicParsing<br>    Write-Host &quot;VM $vm will be started if exist in Subscription and Automation Account have required rights.&quot;<br>}<br>elseif ($stoporstart -eq &quot;X&quot;)<br>{<br>    $params = @{&quot;vm&quot;=$vm;&quot;stopOrStart&quot;=$stopOrStart}<br>    $body = ConvertTo-Json -InputObject $params<br>    $webresp = Invoke-WebRequest -Method Post -Uri $uri -Body $body -Verbose -UseBasicParsing<br>    Write-Host &quot;VM $vm will be stopped if exist in Subscription and Automation Account have required rights.&quot;<br>}<br>else<br>{<br>    Write-Warning &quot;Invalid Argument: $stoporstart&quot;<br>}</pre><p><strong>Step 2:</strong> Replace <strong>“$uri” </strong>variable value with your Webhook URL which you got in Step 6 of previous section.</p><p><strong>Step 3:</strong> Execute the script by clicking on Green <strong>Play</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCQ-7aXqU0clgsAySn0_WA.png" /></figure><p><strong>Step 4:</strong> It will ask you to provide VM name and the action you want to take.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*gdBZFlTntuoUJqkWJk7NEA.png" /></figure><p><strong><em>S</em></strong><em> to Start the VM and </em><strong><em>X</em></strong><em> to Stop</em></p><p><strong>Step 5:</strong> Hit <strong>Enter </strong>after providing name and action and it will trigger the Azure Automation Account runbook and will Stop or Start the Virtual Machine.</p><p>That’s all what we have to do ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d37e96c1b71" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>