Search code examples
deploymentazure-functionsazure-logic-apps

Azure logic app with different connections deployment


I'm trying to deploy a Logic App in a certain azure environment but i'm facing a problem that i don't know how to give it solution.

The problem is that when I deploy these logic apps, the connectors that references to Microsoft accounts, like Office connectors or Dynamics 365 connectors are getting the following error:

Invalid connection error

Is there any way to specify the values for these connections in the parameters.json file of the Logic App? Like, a parameter where I can specify email and password using key vaults?


Solution

  • You can create the connections like Office 365 using ARM template deployment but you will get Invalid Connection error because your connection is not authenticated yet.

    • Office 365 API follows OAuth 2.0 authentication with Authorization Code grant type flow which needs user login to fetch the code. You can refer to this MS docs which says the same.

    enter image description here

    • I have used below code to deploy the logic app which creates the connection but its not yet authenticated.
    {
        "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
        "contentVersion": "1.0.0.0",
        "parameters": {
            "logicAppName": {
                "type": "string"
            },
            "location": {
                "type": "string",
                "defaultValue": "[resourceGroup().location]"
            }
        },
        "resources": [
            {
                "type": "Microsoft.Logic/workflows",
                "apiVersion": "2016-06-01",
                "name": "[parameters('logicAppName')]",
                "location": "[parameters('location')]",
                "identity": {
                    "type": "SystemAssigned"
                },
                "properties": {
                    "state": "Enabled",
                    "definition": {
                        "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
                        "actions": {
                            "Send_an_email_(V2)": {
                                "inputs": {
                                    "body": {
                                        "Body": "<p>Hello, This is Afreen</p>",
                                        "Importance": "Normal",
                                        "Subject": "This is Test Email",
                                        "To": "{email_id}"
                                    },
                                    "host": {
                                        "connection": {
                                            "name": "@parameters('$connections')['office365']['connectionId']"
                                        }
                                    },
                                    "method": "post",
                                    "path": "/v2/Mail"
                                },
                                "runAfter": {},
                                "type": "ApiConnection"
                            }
                        },
                        "outputs": {},
                        "parameters": {
                            "$connections": {
                                "defaultValue": {},
                                "type": "Object"
                            }
                        },
                        "triggers": {
                            "manual": {
                                "inputs": {},
                                "kind": "Http",
                                "type": "Request"
                            }
                        }
                    },
                    "parameters": {
                        "$connections": {
                            "value": {
                                "office365": {
                                    "connectionId": "[resourceId('Microsoft.Web/connections', 'office365')]",
                                    "connectionName": "office365",
                                    "id": "[concat(subscription().id,'/providers/Microsoft.Web/locations/', resourceGroup().location, '/managedApis/office365')]"
                                }
                            }
                        }
                    }
                },
                "dependsOn": [
                    "[resourceId('Microsoft.Web/connections', 'office365')]"
                ]
            },
            {
            "type": "Microsoft.Web/connections",
            "apiVersion": "2016-06-01",
            "location": "[resourceGroup().location]",
            "name": "office365",
            "properties": {
                "api": {
                "id": "[concat(subscription().id,'/providers/Microsoft.Web/locations/', resourceGroup().location, '/managedApis/office365')]"
                },
                "displayName": "office365"
            }
        }
      ],
      "outputs": {}
    }
    
    • Once the logic app and the connection is created, you can validate them using the PowerShell script given in this Github link. while doing so, you will be asked to sign in for authentication. Upon successful completion, status of the connection will get changed from Error to Connected.
    Param(
        [string] $ResourceGroupName = 'YourRG',
        [string] $ResourceLocation = 'eastus | westus | etc.',
        [string] $api = 'office365 | dropbox | dynamicscrmonline | etc.',
        [string] $ConnectionName = 'YourConnectionName',
        [string] $subscriptionId = '***********',
        [bool] $createConnection =  $true | $false
    )
     #region mini window, made by Scripting Guy Blog
        Function Show-OAuthWindow {
        Add-Type -AssemblyName System.Windows.Forms
     
        $form = New-Object -TypeName System.Windows.Forms.Form -Property @{Width=600;Height=800}
        $web  = New-Object -TypeName System.Windows.Forms.WebBrowser -Property @{Width=580;Height=780;Url=($url -f ($Scope -join "%20")) }
        $DocComp  = {
                $Global:uri = $web.Url.AbsoluteUri
                if ($Global:Uri -match "error=[^&]*|code=[^&]*") {$form.Close() }
        }
        $web.ScriptErrorsSuppressed = $true
        $web.Add_DocumentCompleted($DocComp)
        $form.Controls.Add($web)
        $form.Add_Shown({$form.Activate()})
        $form.ShowDialog() | Out-Null
        }
        #endregion
    
    #login to get an access code 
    
    Login-AzureRmAccount 
    
    #select the subscription
    
    $subscription = Select-AzureRmSubscription -SubscriptionId $subscriptionId
    
    #if the connection wasn't alrady created via a deployment
    if($createConnection)
    {
        $connection = New-AzureRmResource -Properties @{"api" = @{"id" = "subscriptions/" + $subscriptionId + "/providers/Microsoft.Web/locations/" + $ResourceLocation + "/managedApis/" + $api}; "displayName" = $ConnectionName; } -ResourceName $ConnectionName -ResourceType "Microsoft.Web/connections" -ResourceGroupName $ResourceGroupName -Location $ResourceLocation -Force
    }
    #else (meaning the conneciton was created via a deployment) - get the connection
    else{
    $connection = Get-AzureRmResource -ResourceType "Microsoft.Web/connections" -ResourceGroupName $ResourceGroupName -ResourceName $ConnectionName
    }
    Write-Host "connection status: " $connection.Properties.Statuses[0]
    
    $parameters = @{
        "parameters" = ,@{
        "parameterName"= "token";
        "redirectUrl"= "https://ema1.exp.azure.com/ema/default/authredirect"
        }
    }
    
    #get the links needed for consent
    $consentResponse = Invoke-AzureRmResourceAction -Action "listConsentLinks" -ResourceId $connection.ResourceId -Parameters $parameters -Force
    
    $url = $consentResponse.Value.Link 
    
    #prompt user to login and grab the code after auth
    Show-OAuthWindow -URL $url
    
    $regex = '(code=)(.*)$'
        $code  = ($uri | Select-string -pattern $regex).Matches[0].Groups[2].Value
        Write-output "Received an accessCode: $code"
    
    if (-Not [string]::IsNullOrEmpty($code)) {
        $parameters = @{ }
        $parameters.Add("code", $code)
        # NOTE: errors ignored as this appears to error due to a null response
    
        #confirm the consent code
        Invoke-AzureRmResourceAction -Action "confirmConsentCode" -ResourceId $connection.ResourceId -Parameters $parameters -Force -ErrorAction Ignore
    }
    
    #retrieve the connection
    $connection = Get-AzureRmResource -ResourceType "Microsoft.Web/connections" -ResourceGroupName $ResourceGroupName -ResourceName $ConnectionName
    Write-Host "connection status now: " $connection.Properties.Statuses[0]
    

    enter image description here

    References-

    Unable to connect the API connection to the logic App via ARM template in terraform - Stack Overflow.

    Deploying in the Logic Apps Preview Refresh | Microsoft Learn.