<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Azure on Journey through Cloud &amp; Code</title><link>https://gurupasupathy.com/tags/azure/</link><description>Recent content in Azure on Journey through Cloud &amp; Code</description><generator>Hugo</generator><language>en-us</language><lastBuildDate>Mon, 10 Jun 2024 00:00:00 +0000</lastBuildDate><atom:link href="https://gurupasupathy.com/tags/azure/index.xml" rel="self" type="application/rss+xml"/><item><title>Extracting Swagger definition for Azure Logic App and importing to Azure APIM</title><link>https://gurupasupathy.com/post/2024-06-10_extracting-logic-app-swagger-def-and-import-to-apim/</link><pubDate>Mon, 10 Jun 2024 00:00:00 +0000</pubDate><guid>https://gurupasupathy.com/post/2024-06-10_extracting-logic-app-swagger-def-and-import-to-apim/</guid><description>&lt;p&gt;&lt;img loading="lazy" src="https://gurupasupathy.com/img/1__Yqhxr__0j4lVw8U9QtA6mKQ.jpeg"&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Use case&lt;/strong&gt; — I want to import a Logic App as an API within my APIM instance.&lt;/p&gt;
&lt;p&gt;There is no direct way to get the swagger file of a logic app using CLI (at least, I could not figure out). So, detailing the steps to extract the swagger definition of a logic app. I use the generated swagger file to import a Logic App as an API within APIM using Azure CLI&lt;/p&gt;</description><content:encoded><![CDATA[<p><img loading="lazy" src="/img/1__Yqhxr__0j4lVw8U9QtA6mKQ.jpeg"></p>
<p><strong>Use case</strong> — I want to import a Logic App as an API within my APIM instance.</p>
<p>There is no direct way to get the swagger file of a logic app using CLI (at least, I could not figure out). So, detailing the steps to extract the swagger definition of a logic app. I use the generated swagger file to import a Logic App as an API within APIM using Azure CLI</p>
<ol>
<li><strong>Provide the service principal contributor role to the logic app</strong></li>
</ol>
<ul>
<li><em>Get the resource id of the logic app —</em></li>
</ul>
<p>$logicAppResourceId = (az logic workflow show &ndash;resource-group &ldquo;{resourcegroup-name}&rdquo; &ndash;name &ldquo;{logicAppName}&rdquo; &ndash;query id &ndash;output tsv)</p>
<ul>
<li><em>Provide contributor role for the service principal —</em></li>
</ul>
<p>az role assignment create --assignee {sp-id} - role Contributor &ndash;scope $logicAppResourceId</p>
<p><strong>2. Get the swagger file from the Logic App</strong></p>
<ul>
<li><em>generate a JW token</em> from <a href="https://login.microsoftonline.com/%7BtenantId%7D/oauth2/token"><em>https://login.microsoftonline.com/{tenantId}/oauth2/token</em></a> for the service principle with resource as “<em><a href="https://management.core.windows.net/">https://management.core.windows.net/</a></em>”</li>
</ul>
<p>$tenantId = &ldquo;11111111-1111-1111-1111-111111111111&rdquo;<br>
$clientId = &ldquo;00000000-0000-0000-0000-000000000000&rdquo;<br>
$clientSecret = &ldquo;your-client-secret&rdquo;<br>
$resource = &ldquo;<a href="https://management.core.azure.com/%22">https://management.core.azure.com/&quot;</a></p>
<p>$body = @{<br>
grant_type    = &ldquo;client_credentials&rdquo;<br>
client_id     = $clientId<br>
client_secret = $clientSecret<br>
resource      = $resource<br>
}</p>
<p>$response = Invoke-RestMethod -Method Post -Uri &ldquo;<a href="https://login.microsoftonline.com/$tenantId/oauth2/token%22">https://login.microsoftonline.com/$tenantId/oauth2/token&quot;</a> -ContentType &ldquo;application/x-www-form-urlencoded&rdquo; -Body $body</p>
<p>$accessToken = $response.access_token<br>
$accessToken</p>
<ul>
<li><em>construct the swagger URL for the logic app —</em></li>
</ul>
<p>$swaggerUrl = &ldquo;<a href="https://management.azure.com">https://management.azure.com</a>&rdquo; + (az logic workflow show &ndash;resource-group &ldquo;{resourcegroup-name}&rdquo; &ndash;name &ldquo;{logicapp-name}&rdquo; &ndash;query id &ndash;output tsv) + &ldquo;/listSwagger?api-version=2016–06–01&rdquo;</p>
<ul>
<li><em>Issue a POST request to $swaggerUrl to get the swagger definition of the LogicApp using Postman (or any other option you prefer)</em></li>
</ul>
<p><strong>3. Import into APIM</strong></p>
<ul>
<li>Run the below command to import the above swagger file to APIM</li>
</ul>
<p>az apim api import &ndash;resource-group &ldquo;{resourcegroup-name}&rdquo; &ndash;service-name &ldquo;{apim-instance-name}&rdquo; &ndash;path &ldquo;/v1&rdquo; &ndash;api-id myapi &ndash;specification-path &ldquo;.\logicapp.backend.swagger.json&rdquo; &ndash;specification-format Swagger</p>
<p><strong>4. Remove the contributor role for the service principal</strong></p>
<p>az role assignment delete &ndash;assignee 00000000–0000–0000–0000–000000000000 &ndash;role &ldquo;Contributor&rdquo; &ndash;scope $logicAppResourceId</p>
]]></content:encoded></item><item><title>Calling a Logic App from APIM</title><link>https://gurupasupathy.com/post/2024-05-22_calling-a-logic-app-from-apim/</link><pubDate>Wed, 22 May 2024 00:00:00 +0000</pubDate><guid>https://gurupasupathy.com/post/2024-05-22_calling-a-logic-app-from-apim/</guid><description>&lt;p&gt;&lt;img loading="lazy" src="https://gurupasupathy.com/img/1__Gepa1jETj8F7cwF8xpVXJg.jpeg"&gt;&lt;/p&gt;
&lt;p&gt;There are couple of ways to integrate an APIM with Logic App. The most common use case as far as I know is exposing the Logic App as an API on the APIM. The other scenario is calling a Logic App from APIM.&lt;/p&gt;
&lt;p&gt;I will provide the APIM policy snippet to call a Logic App. If you are using Managed Identity to authenticate to Logic App (will cover in a separate article), you can skip sending the bearer token.&lt;/p&gt;</description><content:encoded><![CDATA[<p><img loading="lazy" src="/img/1__Gepa1jETj8F7cwF8xpVXJg.jpeg"></p>
<p>There are couple of ways to integrate an APIM with Logic App. The most common use case as far as I know is exposing the Logic App as an API on the APIM. The other scenario is calling a Logic App from APIM.</p>
<p>I will provide the APIM policy snippet to call a Logic App. If you are using Managed Identity to authenticate to Logic App (will cover in a separate article), you can skip sending the bearer token.</p>
<p><strong>Few steps to be done in the Logic App</strong></p>
<ol>
<li>
<p>enable Authentication at the Logic App end</p>
</li>
<li>
<p>the Logic App URL should not contain the SAS token</p>
</li>
<li>
<p>make sure that the Logic App has the below in trigger section. Basically, this is the ensure that the Logic App expects the Bearer token and “IncludeAuthorizationHeadersInOutputs” ensures that the Auth token is available for further processing within the Logic App</p>
<p>&ldquo;triggers&rdquo;: {<br>
&ldquo;manual&rdquo;: {<br>
&ldquo;conditions&rdquo;: [<br>
{<br>
&ldquo;expression&rdquo;: &ldquo;@startsWith(triggerOutputs()?[&lsquo;headers&rsquo;]?[&lsquo;Authorization&rsquo;], &lsquo;Bearer&rsquo;)&rdquo;<br>
}<br>
],<br>
&ldquo;inputs&rdquo;: {<br>
&ldquo;schema&rdquo;: {}<br>
},<br>
&ldquo;kind&rdquo;: &ldquo;Http&rdquo;,<br>
&ldquo;operationOptions&rdquo;: &ldquo;IncludeAuthorizationHeadersInOutputs&rdquo;,<br>
&ldquo;type&rdquo;: &ldquo;Request&rdquo;<br>
}<br>
}</p>
</li>
</ol>
<p><strong>APIM Policy to call the Logic App</strong></p>
<p>We issue a call to the Logic App from with the <send-request>. The response from the Logic App is captured in <em>response-variable-name=”responsela”.</em></p>
<p>&lt;policies&gt;<br>
&lt;inbound&gt;<br>
<base /></p>
<pre><code>    &lt;send-request mode\=&quot;new&quot; response-variable-name\=&quot;responsela&quot; timeout\=&quot;20&quot; ignore-error\=&quot;false&quot;\&gt;  
        &lt;set-url\&gt;https://xxxxxxx.com:443/workflows/xxxxxxxxxxxx/triggers/manual/paths/invoke?api-version=2016-10-01&lt;/set-url\&gt;  
        &lt;set-method\&gt;POST&lt;/set-method\&gt;  
        &lt;set-header name\=&quot;Content-Type&quot; exists-action\=&quot;override&quot;\&gt;  
            &lt;value\&gt;application/json&lt;/value\&gt;  
        &lt;/set-header\&gt;  
        &lt;set-header name\=&quot;Authorization&quot; exists-action\=&quot;override&quot;\&gt;  
            &lt;value\&gt;Bearer \*\*\*\*&lt;/value\&gt;  
        &lt;/set-header\&gt;  
    &lt;/send-request\&gt;  

    &lt;return-response\&gt;  
        &lt;set-status code\=&quot;200&quot; reason\=&quot;OK&quot; /&gt;  
        &lt;set-body\&gt;@(((IResponse)context.Variables\[&quot;responsela&quot;\]).Body.As&lt;JObject\&gt;(preserveContent: true).ToString())&lt;/set-body\&gt;  
    &lt;/return-response\&gt;  

&lt;/inbound\&gt;  
&lt;outbound\&gt;  
    &lt;base /&gt;  
&lt;/outbound\&gt;  
&lt;on-error\&gt;  
    &lt;base /&gt;  
&lt;/on-error\&gt;  
&lt;backend\&gt;  
    &lt;base /&gt;  
&lt;/backend\&gt;  
</code></pre>
<p>&lt;/policies&gt;</p>
<p>All the tags are quite self-explanatory and there a loads of documentation available about them. <return-response> is very useful policy, it suspends further policy pipeline execution and returns to the caller.</p>
<p>Hope this helps.</p>
<p>Cheers!</p>
]]></content:encoded></item><item><title>How to get rid of a rouge instance in Azure App Service Plan</title><link>https://gurupasupathy.com/post/2021-04-22_rid-of-a-rouge-instance-in-azure-app-service-plan/</link><pubDate>Thu, 22 Apr 2021 00:00:00 +0000</pubDate><guid>https://gurupasupathy.com/post/2021-04-22_rid-of-a-rouge-instance-in-azure-app-service-plan/</guid><description>&lt;p&gt;&lt;img loading="lazy" src="https://gurupasupathy.com/img/1__Lm11e6NyfH1lBZhwYgObTw.jpeg"&gt;&lt;/p&gt;
&lt;p&gt;If you have been using Azure App Services for a while to host your API, there is a small chance that you would have encountered the issue with a faulty instance. Your API just doesn’t respond or keeps crashing in a particular instance. And, if your ARR Affinity was enabled, your problems will just be exacerbated. Some users will always be routed to the faulty instance.&lt;/p&gt;
&lt;p&gt;AFAIK, there are no straight forward way to release an instance that is allotted to you by Azure for the given App Service Plan. Adding more instances and removing instances (scale out / in) will not guarantee that the rogue instance will be released. I will share the approach I took to get rid of the rogue instance. Note that, the approach below needs your app service to be out of rotation and should not be serving incoming requests.&lt;/p&gt;</description><content:encoded><![CDATA[<p><img loading="lazy" src="/img/1__Lm11e6NyfH1lBZhwYgObTw.jpeg"></p>
<p>If you have been using Azure App Services for a while to host your API, there is a small chance that you would have encountered the issue with a faulty instance. Your API just doesn’t respond or keeps crashing in a particular instance. And, if your ARR Affinity was enabled, your problems will just be exacerbated. Some users will always be routed to the faulty instance.</p>
<p>AFAIK, there are no straight forward way to release an instance that is allotted to you by Azure for the given App Service Plan. Adding more instances and removing instances (scale out / in) will not guarantee that the rogue instance will be released. I will share the approach I took to get rid of the rogue instance. Note that, the approach below needs your app service to be out of rotation and should not be serving incoming requests.</p>
<p>Assume that you suspect that a given instance in your App Service Plan has issues and is crashing frequently and you wish to remove this instance. As of today, there is no way to select an instance and remove it via the Azure Portal (<em>yes, you can stop an instance from Process Explorer, but it would still not get rid of the instance</em>). One way to achieve this would be to use vertical scaling (up/down). When you scale up/down Azure allocates necessary hardware based on the target pricing tier you have chosen. The infrastructure differs significantly across tiers and moving across tiers will almost always guarantee different infrastructure allocation. We will use this to get rid of the rogue instance.</p>
<p>Start by scaling down to a lesser tier (<em>moving laterally within the same tier may not help</em>) For instance, if you are operating on a Premium tier, move to Standard. This action will make Azure allocate new instances in the lesser tier that you have chosen. Now, after scaling down, scale up again to your target pricing tier. When you do this, you are going to be allocated fresh (at least not the old rogue) instances. This is how I got rid of one of the instances that was bothering me.</p>
<p>Hope this helps.</p>
]]></content:encoded></item><item><title>Using Azure function proxies for mocking API</title><link>https://gurupasupathy.com/post/2020-06-14_using-azure-function-proxies-for-mocking/</link><pubDate>Sun, 14 Jun 2020 00:00:00 +0000</pubDate><guid>https://gurupasupathy.com/post/2020-06-14_using-azure-function-proxies-for-mocking/</guid><description>&lt;p&gt;&lt;img loading="lazy" src="../post/img/1__0dxAdZ9Lr__lZh7pA1UvbhA.png"&gt;
&lt;img loading="lazy" src="img/1__K8rbssn1nWY4vAurhAH3QQ.jpeg"&gt;&lt;/p&gt;
&lt;p&gt;There are many options available when it comes to mocking API response, like, &lt;a href="https://www.npmjs.com/package/json-server"&gt;JSON server&lt;/a&gt; or even having a response JSON file added to your solutions, to cite a few. In this article we will see how Azure function proxies can be used to mock API responses.&lt;/p&gt;
&lt;p&gt;Azure function provides an elegant option to mock API response using proxies. Using a Azure function proxy, you can provide a mock endpoint which can be used by your team to continue their work till your actual API is ready for integration.&lt;/p&gt;</description><content:encoded><![CDATA[<p><img loading="lazy" src="../post/img/1__0dxAdZ9Lr__lZh7pA1UvbhA.png">
<img loading="lazy" src="img/1__K8rbssn1nWY4vAurhAH3QQ.jpeg"></p>
<p>There are many options available when it comes to mocking API response, like, <a href="https://www.npmjs.com/package/json-server">JSON server</a> or even having a response JSON file added to your solutions, to cite a few. In this article we will see how Azure function proxies can be used to mock API responses.</p>
<p>Azure function provides an elegant option to mock API response using proxies. Using a Azure function proxy, you can provide a mock endpoint which can be used by your team to continue their work till your actual API is ready for integration.</p>
<p>Let us go ahead, create a simple proxy and see how the mock response is served.</p>
<p>We will be creating a proxy end point which will service a GET call, say, getCustomer. Our getCustomer API method is expected to provide a response in the below format. So, till getCustomer is up and ready for consumption, our proxy can be used to get the below JSON as mock response.</p>
<p><img loading="lazy" src="/img/1__VxL01HJuza__7HKo6y3T8Vw.png"></p>
<p>Below are the steps for create a Function proxy.</p>
<p><strong>Step 1:</strong> We will create an Azure function app which will host the proxy. (If there is already a general purpose / maintenance Function App present we can use that.)</p>
<p><img loading="lazy" src="/img/1__CdC5l5Ay818N906wBgbugw.png">
<img loading="lazy" src="/img/1__R8T9gR2hwvG7u38I8e9ZWA.png"></p>
<p><strong>Step 2:</strong> Now that we have created the function app to host our proxy, let us create our proxy. Choose the “Proxies” item in the Azure function blade as shown below. Click on “Add” to create a new proxy. We will call this MockCustomerAPI</p>
<p><img loading="lazy" src="/img/1__K6PLoLzwHZssslewruuToQ.png"></p>
<p>And we will provide a route <em>/api/getcustomer</em>. In the HTTP Method section, we select “GET”. Please note that we can choose to mock other HTTP methods like POST as well.</p>
<p><strong>Step 3:</strong> This is the step where we will provide the response we want the proxy to send us back. We will override the response as shown below by expanding the “Response override” link and paste our mock response in the space provide in Body section.</p>
<p><img loading="lazy" src="/img/1__BgsQW0N7msbWbSpjkiIdNg.png"></p>
<p>We can provide the status code and status message as per our use case and click on “Create”. Once the proxy gets created successfully we will be provided with a link to access the proxy as shown below</p>
<p><img loading="lazy" src="/img/1__k7__6TGvg__h2H9nN1KHpO7Q.png"></p>
<p><strong>Step 4:</strong> Now that we are done with creating the proxy, let us test. To test our proxy, copy the generated proxy URL and open in the browser. We will see the response as below</p>
<p><img loading="lazy" src="/img/1__omuFybwa4TdrArkz3r7Gxg.png"></p>
<p>Thus, we have created a proxy for the getCustomer API which can be used by the UX team or other API teams to integrate during the early development cycles when our API is not ready yet. Please do note that mocks are not just for GET method, you could do other HTTP methods as well</p>
<p>Some of the advantages of this approach are</p>
<ol>
<li>Mock API responses unblocks the collaborating team like UX team as they can work against the mock endpoint till the actual API is ready</li>
<li>Testing is easier and thorough if your API relies on a partner API. Creating a mock endpoint gives you the flexibility to change the response and test your code for all possible, allowed parameter values from the partner API</li>
<li>If there is a dependency on partner API which is not available in your lower environments, you can resort to creating a proxy in lower environment.</li>
<li>As it is hosted in a common URL, same contract will be used across all crews consistently. Any change done to the contract will be immediately visible to all the consuming developers.</li>
<li>Eliminates the need of having a separate JSON response file or JSON server on local dev box and thus ensure you are developing against the latest contract</li>
</ol>
<p><em>Before we conclude, a note about</em> <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS"><em>CORS</em></a><em>:</em> If you are hitting the proxy from your front-end web application, please ensure you tweak the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">CORS</a> setting for the mock function app accordingly as show below</p>
<p><img loading="lazy" src="/img/1__vxBs4ndIeg9zEF4r7__BX8w.png"></p>
<p><strong>Conclusion</strong></p>
<p>There are many useful feature of Azure function Proxies like redirection and route template parameters. You can read more about Azure Function proxies in official <a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-proxies">Microsoft documentation</a>.</p>
]]></content:encoded></item><item><title>Scheduling vertical scaling using Microsoft Azure Automation Accounts</title><link>https://gurupasupathy.com/post/2020-04-25_scheduling-vertical-scaling/</link><pubDate>Sat, 25 Apr 2020 00:00:00 +0000</pubDate><guid>https://gurupasupathy.com/post/2020-04-25_scheduling-vertical-scaling/</guid><description>&lt;p&gt;&lt;img loading="lazy" src="https://gurupasupathy.com/img/1__6HRU03UvgOt__5ih3ssEDXw.jpeg"&gt;&lt;/p&gt;
&lt;p&gt;Scaling cloud resources dynamically is a fascinating topic. Microsoft Azure provide quite a few ways to dynamically scale resources. This article focuses on creating a scheduled &lt;em&gt;vertical scaling&lt;/em&gt; (scaled up/down) of App Services. The approach outlined here can be used for other Azure resource like SQL Databases, Redis Cache or in fact pretty much most of the Azure resources that support scaling. Just to clarify right at the outset, we are talking about vertical scaling (between pricing tiers) and not horizontal scaling (scale in/out) wherein we deal with the number of instances at our disposal.&lt;/p&gt;</description><content:encoded><![CDATA[<p><img loading="lazy" src="/img/1__6HRU03UvgOt__5ih3ssEDXw.jpeg"></p>
<p>Scaling cloud resources dynamically is a fascinating topic. Microsoft Azure provide quite a few ways to dynamically scale resources. This article focuses on creating a scheduled <em>vertical scaling</em> (scaled up/down) of App Services. The approach outlined here can be used for other Azure resource like SQL Databases, Redis Cache or in fact pretty much most of the Azure resources that support scaling. Just to clarify right at the outset, we are talking about vertical scaling (between pricing tiers) and not horizontal scaling (scale in/out) wherein we deal with the number of instances at our disposal.</p>
<p>It is a common knowledge that Azure provides out-of-the-box options to <strong><em>scale out/ scale in</em></strong> based on the scaling rules for App Service plan but there is no way to scale up / scale down as per some schedule.</p>
<p>For instance, there is no direct way to say that between 10 AM and 12 Noon, let my App Service plan run on P2V2 and come back to P1V2 there after or have my SQL Server move up to P6 for a few hours before coming back to S2. In other words, no option to <strong><em>scale up/scale down</em></strong> based on schedule</p>
<blockquote>
<p>Note on Serverless Azure SQL Database :- We have Serverless Azure SQL Databases with two key capabilities which make them attractive in terms of cost. 1. The option to auto scale up / down between the minimum and maximum threshold 2. Auto-pause — wherein the SQL Server is stopped after a predefined period of inactivity till some activity is detected again. You don’t get charged for the period of inactivity. The downside is that it will take some time of the SQL Server to warm up and be available for the next use after the period of inactivity. Serverless is best suited for test / dev environments where you have tolerance to the brief period of connection unavailability during the warm-up. There could also be slight performance degradation for sometime as the cache memory are gradually reclaimed. Serverless is not for your use case if these limitations are not acceptable. Furthermore, there are cases when although your usage will be limited for an interval you cannot afford to shut down the server using auto pause. Without auto pause you will be charged for the minimum number of vCores and minimum memory configured. For more details, refer to Microsoft documentation on <a href="https://docs.microsoft.com/en-us/azure/azure-sql/database/serverless-tier-overview">Azure Serverless SQL Database</a></p>
</blockquote>
<blockquote>
<p>So, if your case is such that you will want to use DTU based provisioning and still want scaling based on a schedule as you have predictable utilisation, you can use the approach outlined in this article. One example that comes to my mind is bumping up your DTU for a few hours when you are doing a performance test or scaling down during a seasonal / weekend low utilisation to save costs.</p>
</blockquote>
<p>Alright, now that we have context set, let us move on to see how we can achieve this scheduled vertical scaling for Azure resource in the following section</p>
<p>To start with, create an automation account. Details on how to create automation account can be found <a href="https://docs.microsoft.com/en-us/azure/automation/automation-create-standalone-account">here</a>. Azure Automation allows us to invoke runbooks as per a schedule. We will leverage this capability for our purpose. Please remember to select the option to create a RunAs account while creating the Automation account as shown below. This is the principle under with the runbooks can execute.</p>
<p><img loading="lazy" src="/img/1__XoHZ7Nof1sdJkKRcwhXCaA.png"></p>
<p>After the automation account is created, create two Runbooks which will be invoked by a scheduler to perform the scaling operation automatically without our intervention. These runbooks will contain PowerShell scripts to perform the scaling operation based on your need. (one for Scale up and another for Scale down) The fact that we use PowerShell to perform the scaling gives us the option to scale pretty much all resource for which you can get hold of PowerShell scripts to scale; and the best source for PowerShell reference is <a href="https://docs.microsoft.com/en-us/powershell/scripting/overview?view=powershell-7">Microsoft’s official documentation</a>.</p>
<p>Now that you have the automation account and the runbooks that you need, create a schedule and link these runbooks as per your need. (<em>I won’t go into details on creating a schedule as it is very well documented and simple. Refer to Microsoft’s documentation on how to create a</em> <a href="https://docs.microsoft.com/en-us/azure/automation/shared-resources/schedules"><em>Schedule</em></a> )</p>
<p>So, for instance, the below schedule will automatically call the “ScaleDown” runbook at 5:10 AM on 7th Feb</p>
<p><img loading="lazy" src="/img/0__qk76rY21a2xOWrxz.jpg"></p>
<p>The below PowerShell script can be used to scale up / down an App Service Plan</p>
<p>Write-Output &ldquo;API Scale&rdquo;</p>
<p>$connectionName = &ldquo;AzureRunAsConnection&rdquo;<br>
try {<br>
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName</p>
<p>Add-AzureRmAccount -ServicePrincipal -TenantId $servicePrincipalConnection.TenantId -ApplicationId $servicePrincipalConnection.ApplicationId -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint</p>
<p>Set-AzureRmAppServicePlan -ResourceGroupName &ldquo;&laquo;<strong>yourresourcegroup</strong>&rdquo; -Name &ldquo;&laquo;<strong>yourappserviceplanname</strong>&rdquo;  -Tier PremiumV2 -NumberofWorkers 2 -WorkerSize &ldquo;Medium&rdquo;}</p>
<p>catch {<br>
if (!$servicePrincipalConnection){<br>
$ErrorMessage = &ldquo;Connection $connectionName not found.&rdquo;<br>
throw $ErrorMessage } else{<br>
Write-Error -Message $_.Exception<br>
throw $_.Exception<br>
}}</p>
<blockquote>
<p>In case you receive an error as below, go and update the PowerShell modules in your automation account. That should fix the issue</p>
</blockquote>
<blockquote>
<p><strong>The term ‘Set-AzureRmAppServicePlan’ is not recognized as the name of a cmdlet, function, script file, or operable program.</strong></p>
</blockquote>
<p>Below, I have provided a sample PowerShell to scale a SQL database; it scales to database to P1 tier. This script uses a credential to perform the DB scaling as opposed to the AzureRunAsAccount in the previous PowerShell.</p>
<p>To create a new credential, navigate to your automation account and select the “Credentials” option in the “Shared Resources” section. Refer to the below screen shot showing the credential creation</p>
<p><img loading="lazy" src="/img/1__tvODqy4v1CAZN__sbLLDL7g.png"></p>
<p>param([parameter(Mandatory=$true)] [PSCredential] $Credential )</p>
<p># Name of the Azure SQL Database server<br>
[string] $SqlServerName = &ldquo;<strong>yourserver</strong>.database.windows.net&rdquo;</p>
<p>$Servercredential = New-Object System.Management.Automation.PSCredential($Credential.UserName, (($Credential).GetNetworkCredential().Password | ConvertTo-SecureString -asPlainText -Force))</p>
<p>$CTX = New-AzureSqlDatabaseServerContext -ServerName $SqlServerName -Credential $ServerCredential</p>
<p>[string] $DatabaseName = &ldquo;<strong>yourdb</strong>&rdquo;<br>
[string] $Edition = &ldquo;Premium&rdquo;<br>
[string] $PerfLevel = &ldquo;P1&rdquo;<br>
$Db = Get-AzureSqlDatabase  $CTX –DatabaseName $DatabaseName</p>
<p>Write-Output &ldquo;Database Scale state &quot; - $Db.ServiceObjectiveAssignementStateDescription</p>
<p>if($Db.ServiceObjectiveName -ne $PerfLevel -and $Db.ServiceObjectiveAssignementStateDescription -ne &ldquo;Pending&rdquo;){<br>
$ServiceObjective = Get-AzureSqlDatabaseServiceObjective $CTX -ServiceObjectiveName $PerfLevel</p>
<p># Set the new edition/performance level<br>
#None, Business, Web, Premium, Basic, Standard&rdquo;</p>
<p>Write-Output &ldquo;Trigger the scale operation&rdquo;<br>
Set-AzureSqlDatabase $CTX –Database $Db –ServiceObjective $ServiceObjective –Edition $Edition -Force</p>
<p>Write-Output &ldquo;Completed vertical scale&rdquo;<br>
}else{<br>
Write-Output &ldquo;The DB is already in the target pricing tier Or DB is currenlty being scale up / down&rdquo;}</p>
<p>This same approach can be applied for other Azure resources also. Go on and try it out!</p>
<p>Happy Scaling!</p>
]]></content:encoded></item></channel></rss>