无法通过 terraform 中的 ARM 模板将 API 连接到逻辑应用程序

Unable to connect the API connection to the logic App via ARM template in terraform

在我的 Terraform 中,我在 ARM 模板的帮助下创建了一个逻辑应用程序及其工作流。逻辑应用中使用的 2 个连接也是通过 ARM 模板创建的。但不知何故,即使资源是在 AZURE 中创建的。但是当我到达逻辑应用程序时,我总是必须手动更新工作流中的连接。我们怎样才能让它自动化。


//First connection

resource "azurerm_template_deployment" "exampleeventhub" {
  name                = "acctesttemplate-44"
  resource_group_name = Resourcegrpname

 template_body = <<DEPLOY
{
    "$schema": https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#,
    "contentVersion": "1.0.0.0",
    "parameters": {
        "connections_eventhubs_name": {
            "defaultValue": "eventhubs",
            "type": "String"
        }
    },
    "variables": {},
    "resources": [
        {
            "type": "Microsoft.Web/connections",
            "apiVersion": "2016-06-01",
            "name": "[parameters('connections_eventhubs_name')]",
            "location": "qwerty",
            "kind": "V1",
            "properties": {
                "displayName": "eventhubconnection",
                "statuses": [
                    {
                        "status": "Connected"
                    }
                ],
                "customParameterValues": {},
                "nonSecretParameterValues": {},
                "createdTime": "aaaaa",
                "changedTime": "bbbb",
                "api": {
                    "name": "[parameters('connections_eventhubs_name')]",
                    "displayName": "Event Hubs",
                    "description": "Connect to Azure Event Hubs to send and receive events.",
                    "iconUri": "[concat('https://connectoricons-prod.azureedge.net/releases/v1.0.1480/1.0.1480.2454/', parameters('connections_eventhubs_name'), '/icon.png')]",
                    "brandColor": "#c4d5ff",
                    "id": "[concat('/subscriptions/1111/providers/Microsoft.Web/locations/qwerty/managedApis/', parameters('connections_eventhubs_name'))]",
                    "type": "Microsoft.Web/locations/managedApis"
                },
                "testLinks": []
            }
        }
    ]
}
DEPLOY
    deployment_mode = "Incremental"
  }



//Second connection
resource "azurerm_template_deployment" "exampledatacollector" {
  name                = "acctesttemplate-45"
  resource_group_name = Resourcegrpname
 template_body = <<DEPLOY
{
    "$schema": https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#,
    "contentVersion": "1.0.0.0",
    "parameters": {
        "connections_thengadatacollector_name": {
            "defaultValue": "thengadatacollector",
            "type": "String"
        }
    },
    "variables": {},
    "resources": [
        {
            "type": "Microsoft.Web/connections",
            "apiVersion": "2016-06-01",
            "name": "[parameters('connections_thengadatacollector_name')]",
            "location": "qwerty",
            "kind": "V1",
            "properties": {
                "displayName": "azuredatacollector",
                "statuses": [
                    {
                        "status": "Connected"
                    }
                ],
                "customParameterValues": {},
                "nonSecretParameterValues": {
                    "username": "764a2b1e-431d-4e90-87b1-ea6a34dac48f"
                },
                "createdTime": "aaaa",
                "changedTime": "bbbb",
                "api": {
                    "name": "[parameters('connections_thengadatacollector_name')]",
                    "displayName": "Azure Log Analytics Data Collector",
                    "description": "Azure Log Analytics Data Collector will send data to any Azure Log Analytics workspace.",
                    "iconUri": "[concat('https://connectoricons-prod.azureedge.net/releases/v1.0.1480/1.0.1480.2454/', parameters('connections_thengadatacollector_name'), '/icon.png')]",
                    "brandColor": "#0072C6",
                    "id": "[concat('/subscriptions/1111/providers/Microsoft.Web/locations/qwerty/managedApis/', parameters('connections_thengadatacollector_name'))]",
                    "type": "Microsoft.Web/locations/managedApis"
                },
                "testLinks": []
            }
        }
    ]
}

DEPLOY
    deployment_mode = "Incremental"
  }
//Logic App
resource "azurerm_template_deployment" "example" {
  name                = "acctesttemplate-46"
  resource_group_name = Resourcegrpname

 template_body = <<DEPLOY
{
    "$schema": https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#,
    "contentVersion": "1.0.0.0",
    "parameters": {
        "workflows_logicapp_name": {
            "defaultValue": "logicapp",
            "type": "String"
        },
        "connections_thengadatacollector_externalid": {
            "defaultValue": "/subscriptions/1111/resourceGroups/Resourcegrpname/providers/Microsoft.Web/connections/azureloganalyticsdatacollector",
            "type": "String"
        },
        "connections_eventhubs_externalid": {
            "defaultValue": "/subscriptions/1111/resourceGroups/Resourcegrpname/providers/Microsoft.Web/connections/eventhubs",
            "type": "String"
        }
    },
    "variables": {},
    "resources": [
        {
            "type": "Microsoft.Logic/workflows",
            "apiVersion": "2017-07-01",
            "name": "[parameters('workflows_logicapp_name')]",
            "location": "qwerty",
            "properties": {
                "state": "Enabled",
                "definition": {
                    "$schema": https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#,
                    "contentVersion": "1.0.0.0",
                    "parameters": {
                        "$connections": {
                            "defaultValue": {},
                            "type": "Object"
                        }
                    },
                    "triggers": {
                        "When_events_are_available_in_Event_Hub": {
                            "recurrence": {
                                "frequency": "Minute",
                                "interval": 3
                            },
                            "splitOn": "@triggerBody()",
                            "type": "ApiConnection",
                            "inputs": {
                                "host": {
                                    "connection": {
                                        "name": "@parameters('$connections')['eventhubs']['connectionId']"
                                    }
                                },
                                "method": "get",
                                "path": "/@{encodeURIComponent('thengaeventhub')}/events/batch/head",
                                "queries": {
                                    "contentType": "application/octet-stream",
                                    "maximumEventsCount": 50
                                }
                            }
                        }
                    },
                    "actions": {
                        "Send_Data_2": {
                            "runAfter": {},
                            "type": "ApiConnection",
                            "inputs": {
                                "body": "@base64ToString(triggerBody()?['ContentData'])",
                                "headers": {
                                    "Log-Type": "testcustimlog"
                                },
                                "host": {
                                    "connection": {
                                        "name": "@parameters('$connections')['thengadatacollector_1']['connectionId']"
                                    }
                                },
                                "method": "post",
                                "path": "/api/logs"
                            }
                        }
                    }
                },
                "parameters": {
                    "$connections": {
                        "value": {
                            "thengadatacollector_1": {
                                "connectionId": "[parameters('connections_thengadatacollector_externalid')]",
                                "connectionName": "thengadatacollector",
                                "id": "/subscriptions/1111/providers/Microsoft.Web/locations/qwerty/managedApis/thengadatacollector"
                            },
                            "eventhubs": {
                                "connectionId": "[parameters('connections_eventhubs_externalid')]",
                                "connectionName": "eventhubs",
                                "id": "/subscriptions/1111/providers/Microsoft.Web/locations/qwerty/managedApis/eventhubs"
                            }
                        }
                    }
                }
            }
        }
    ]
}
DEPLOY
    deployment_mode = "Incremental"
  }

这是预期的行为,如果您部署 ARM 模板,您的两个 API 连接都已创建,但在逻辑应用程序内部,您必须通过输入服务凭据手动更新连接。这是因为要完成 API 连接,您需要同意,但这在 ARM 模板中是不可能的。

但是如果您需要在不打开每个逻辑应用程序的情况下完成 API 连接创建,那么您可以使用 PowerShell 脚本。此脚本将检索同意 link 用于 OAuth 逻辑应用程序的连接连接器。然后它将打开同意 link 并完成授权以启用连接。

Param(
    [string] $ResourceGroupName = 'YourRG',
    [string] $ResourceLocation = 'eastus | westus | etc.',
    [string] $api = 'office365 | dropbox | dynamicscrmonline | etc.',
    [string] $ConnectionName = 'YourConnectionName',
    [string] $subscriptionId = '80d4fe69-xxxx-xxxx-a938-9250f1c8ab03',
    [bool] $createConnection =  $true
)
 #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]

参考:

Deploy Logic Apps & API Connection with ARM · in my room (bruttin.com)