GithubHelp home page GithubHelp logo

jeffhollan / logicapptemplatecreator Goto Github PK

View Code? Open in Web Editor NEW
144.0 24.0 73.0 1.02 MB

Script to convert Logic Apps into templates for deployment

License: MIT License

C# 94.52% PowerShell 5.48%

logicapptemplatecreator's Introduction

Logic App Template Creator Script

This is a simple PowerShell script module I wrote to convert Logic Apps into a template that can be included in a deployment.

How to use

  1. Clone the project, open, and build.
  2. Open PowerShell and Import the module: Import-Module C:\{pathToSolution}\LogicAppTemplateCreator\LogicAppTemplate\bin\Debug\LogicAppTemplate.dll
  3. Run the PowerShell command Get-LogicAppTemplate. You can pipe the output as needed, and recommended you pipe in a token from armclient armclient token 80d4fe69-xxxx-4dd2-a938-9250f1c8ab03 | Get-LogicAppTemplate -LogicApp MyApp -ResourceGroup Integrate2016 -SubscriptionId 80d4fe69-xxxx-4dd2-a938-9250f1c8ab03 -Verbose | Out-File C:\template.json

Example when user is connected to multitenants: Get-LogicAppTemplate -LogicApp MyApp -ResourceGroup Integrate2016 -SubscriptionId 80d4fe69-xxxx-4dd2-a938-9250f1c8ab03 -TenantName contoso.onmicrosoft.com

Example with diagnostic settings: Get-LogicAppTemplate -LogicApp MyApp -ResourceGroup Integrate2016 -SubscriptionId 80d4fe69-xxxx-4dd2-a938-9250f1c8ab03 -DiagnosticSettings

How to use (via Powershell Gallery)

  1. Open a Powershell session / console.
  2. Open PowerShell and Import the module(s):
Install-Module Az.Accounts -Force #Only if you don't if you have it or not, it is safe to run when in doubt
Import-Module Az.Accounts
Install-Module LogicAppTemplate -Force
Import-Module LogicAppTemplate
#Ensure that you are signed into an account with enough permissions
Login-AzAccount
  1. Run the PowerShell command Get-LogicAppTemplate.
$token = Get-AzAccessToken -ResourceUrl "https://management.azure.com" | Select-Object -ExpandProperty Token
Get-LogicAppTemplate -LogicApp MyApp -ResourceGroup Integrate2016 -SubscriptionId 80d4fe69-xxxx-4dd2-a938-9250f1c8ab03 -Token $token -Verbose | Out-File C:\template.json

Important Change 2019-08-09

There has been a change from previous version on parameters that where Boolean are now SwitchParameter there will be an error when you run it the first time. Error is easy fixed, in your script just remove the $true part in your command se example bellow:

 -DiagnosticSettings $true 

To:

-DiagnosticSettings

Updates Change 2020-05-06

There has been alot of small changes and contribution around extraction of connectors, Integration Account and nested templates. New is that service bus connector now comes out with inputs needed for Azure Resource Manager to create the connection string rather than providing it manually.

Specifications

Parameter Description Required
LogicApp The name of the Logic App true
ResourceGroup The name of the Resource Group true
SubscriptionId The subscription Id for the resource true
TenantName Name of the Tenant i.e. contoso.onmicrosoft.com false
Token An AAD Token to access the resources - should not include Bearer, only the token false
ClaimsDump A dump of claims piped in from armclient - should not be manually set false
DiagnosticSettings If supplied, diagnostic settings are included in the ARM template false
IncludeInitializeVariable If supplied, Initialize Variable actions will be included in the ARM template false
FixedFunctionAppName If supplied, the functionApp gets a static name false
GenerateHttpTriggerUrlOutput If supplied, generate an output variable with the http trigger url. false
StripPassword If supplied, the passwords will be stripped out of the output false
DisabledState If supplied, the LA ARM Template will be set to Disabled and won't be automatically run when deployed false
ForceManagedIdentity If supplied, Managed Identity for the Logic App will be set in the ARM template false
DisableConnectionGeneration If supplied, Connections for the Logic App will not be output in the ARM template false
DisableTagParameters If supplied, Tags are not parameterized for the Logic App will not be output in the ARM template false
IncludeEvaluatedRecurrence If supplied, EvaluatedRecurrence is added in the ARM template, this is a non documented object false
DisableFunctionNameParameters If supplied, FunctionNames are not parameterized for the Logic App will not be output in the ARM template false
SkipOauthConnectionAuthorization If supplied, Oauth Connections Authorization are not set in the ARM template false
UseServiceBusDisplayName If supplied, the ServiceBusDisplayNames is used within the parameters in the ARM template false
OnlyParameterizeConnections If supplied, the connections are generated with paramters only, no listkeys or other functions is added in the connection object false

After extraction a parameters file can be created off the LogicAppTemplate. (works on any ARM template file):

Get-ParameterTemplate -TemplateFile $filenname | Out-File 'paramfile.json'

For extraction with KeyVault reference mockup links created use: (only static reference)

Get-ParameterTemplate -TemplateFile $filenname -KeyVault Static | Out-File $filennameparam

Specifications

Parameter Description Required
TemplateFile File path to the template file true
KeyVault Enum describing how to handle KeyVault possible values Static Noce, default None false
GenerateExpression Whether to generate parameters whose default value is an ARM expression. If not specified then will not generate parameters per original code false

Other supported commands:

  • Get-IntegrationAccountSchemaTemplate: extract a schema from an integration account
  • Get-IntegrationAccountMapTemplate: extract a map from an integration account
  • Get-CustomConnectorTemplate: extract a custom connector

logicapptemplatecreator's People

Contributors

alphaklp avatar bejo73 avatar bhoang avatar bhoang-ipl avatar dependabot[bot] avatar jeffhollan avatar joeyeng avatar lfalck avatar mehmetseckin avatar mlogdberg avatar rodrigogroener avatar splaxi avatar svenskfisk avatar tomkerkhove avatar wsilveiranz avatar your-azure-coach avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

logicapptemplatecreator's Issues

Clouds other than "AzureCloud" are not supported.

Anything other Azure clouds than the primary public "AzureCloud" are not supported. This is due to the hardcoding of URL https://management.azure.com in AzureResourceCollector.cs.

This makes it impossible to use this tool on other clouds. "AzureUSGovernment", "AzureStack", "AzureGermanCloud", "AzureChinaCloud", and so on. Please add a parameter that allows for switching the URL of the management API at the very least.

Get-LogicAppTemplate throws Aggregation Exception

Hi,
While trying to export the deployment template for a LogicApp, we are facing the below error:

Get-LogicAppTemplate : Aggregation Exception thrown, One or more errors occurred., first Exception message is: Object reference not set to an instance of an object., for more information read
the output file.
At line:1 char:1

  • Get-LogicAppTemplate -LogicApp TEST_EXPORT -ResourceGroup - ...
  •   + CategoryInfo          : NotSpecified: (:) [Get-LogicAppTemplate], Exception
      + FullyQualifiedErrorId : System.Exception,LogicAppTemplate.GeneratorCmdlet
    
    
    

As suggested in other similar issues, I tried adding the tenant. But even after using the Tenant, it's throwing the same error. I am guessing this has to do with the SQL server API connection used in my Logic App.

I was able to export LogicApps successfully that are using old version of SQL server API connections. But when I am using new API connection version that lets us pick the Authorization method (like Azure AD, Windows, etc.) I am facing this error.

Can you please look into this?

Thanks.

File Connector not getting any parameters

When generating the template the File Connector parameters is empty.

{
"type": "Microsoft.Web/connections",
"apiVersion": "2016-06-01",
"location": "[parameters('logicAppLocation')]",
"name": "[parameters('filesystem_name')]",
"properties": {
"api": {
"id": "[concat('/subscriptions/',subscription().subscriptionId,'/providers/Microsoft.Web/locations/',parameters('logicAppLocation'),'/managedApis/filesystem')]"
},
"displayName": "[parameters('filesystem_displayName')]"
}
}

Exception Message when adding Diagnostics Settings

to recreate:

  1. Create Logic App
  2. From Log Analytics under "Azure Resources" add your LA to be logged
  3. run export with diagnostic settings to "true"

this error shows:
Get-LogicAppTemplate : Aggregation Exception thrown, One or more errors occurred., first Exception message is: Cannot access child value on Newtonsoft.Json.Linq.JValue., for more information
read the output file.

Workaround is to
1.Create Logic App
2. From Logic App Blade, active Diagnostics settings
3. Extracting works

Blank connection when deployed?

After deploying the generated template my connection had blank values:

"$connections": {
        "value": {
            "azureblob_1": {
                "connectionId": "",
                "connectionName": "",
                "id": ""
            }
        }
    }

Here's how it was defined in the template:

"parameters": {
          "$connections": {
            "value": {
              "azureblob-1": {
                "id": "[concat('/subscriptions/',subscription().subscriptionId,'/providers/Microsoft.Web/locations/',parameters('logicAppLocation'),'/managedApis/azureblob')]",
                "connectionId": "[resourceId('Microsoft.Web/connections', parameters('azureblob-1_name'))]",
                "connectionName": "[parameters('azureblob-1_name')]"
              }
            }
          }
        }

Did I do something wrong or is this a known limitation?

resourceGroup().location is not valid in parameters file

[resourcegroup().location] is an ARM template expression which gets translated to appropriate value on deployment. While parsing the logic app template to generate the parameter file paramters with ARM Template exceptions should be skipped, as they are already automated.

SecureString values gets exposed in defaultValue after deployment

Source Logic App Definition with parameter "CRM_HTTP_AzureAD_Secret":

"CRM_HTTP_AzureAD_Secret": { "type": "SecureString" }

Creates following ARM Template Parameter

"paramCRM_HTTP_AzureAD_Secret": { "type": "securestring", "defaultValue": "" }

That is used in the embedded Logic App definition:

"CRM_HTTP_AzureAD_Secret": { "type": "SecureString", "defaultValue": "[parameters('paramCRM_HTTP_AzureAD_Secret')]" }

What leads to that the secrect gets exposed in the "defaultValue" after the deployment:

"CRM_HTTP_AzureAD_Secret": { "defaultValue": "XXXXXX SECRECT VALUE XXXXXXXX", "type": "SecureString" }

So i think it would be nice to remove default value output for SecureString oder SecureObject parameters in the created template.
What do you mean?

"path" parameter empty in AzureBlob and Filesystem actions

Hi,

The latest version seems to lose the "path" input parameter value of AzureBlob and Filesystem action blocks. This is especially troublesome in cases (e.g. "List blobs in folder") where the path parameter contains a full folder or file path.

For example, the following action block
"Create_blob": { "inputs": { "body": "'Some content text'", "host": { "connection": { "name": "@parameters('$connections')['azureblob']['connectionId']" } }, "method": "post", "path": "/datasets/default/files", "queries": { "folderPath": "@{parameters('ContainerName')}", "name": "@{parameters('FileName')}", "queryParametersSingleEncoded": true } }, "runAfter": {}, "runtimeConfiguration": { "contentTransfer": { "transferMode": "Chunked" } }, "type": "ApiConnection" }
comes through in the template as
"Create_blob": { "runAfter": {}, "type": "ApiConnection", "inputs": { "body": "'Some content text'", "host": { "connection": { "name": "@parameters('$connections')['azureblob']['connectionId']" } }, "method": "post", "path": "", "queries": { "folderPath": "@{parameters('ContainerName')}", "name": "@{parameters('FileName')}", "queryParametersSingleEncoded": true } }, "runtimeConfiguration": { "contentTransfer": { "transferMode": "Chunked" } } }

I really can't follow the C# code, but in the source I noticed that AzureBlob and Filesystem API Connections have some special processing in TemplateGenerator.cs involving some Base64 handling.

Regards,
Patrik Palm

Email step w/ SMTP API connection generates smtp_port param typed as int, but default value as a string

In the parameters of the template, the following gets generated as one of the parameters when there's an Email step with an SMTP API Connection:

"smtp_port": {
  "type": "int",
  "defaultValue": "25",
  "metadata": { /*<stuff>*/ }
}

Then in the template, a Microsoft.Web/connections with a managedApis/smtp type uses this parameter.

I don't think it matters whether it is a string or an int, but the type and default value must agree with one another.

When the type doesn't agree with the value, Azure throws 400 Bad Request errors that. When --debug is provided to the Azure CLI, it can be seen that the error is the result of this type mismatch.

Hardcoded values in actions not parameterized.

When you are using connectors such a CRM(CDS) or ERP connectors in the action you still have hardcoded values to the environment name.

And I know this is can be a tricky one.

"Lists_items_present_in_table": { "runAfter": {}, "type": "ApiConnection", "inputs": { "host": { "connection": { "name": "@parameters('$connections')['dynamicsax']['connectionId']" } }, "method": "get", "path": "/datasets/@{encodeURIComponent(encodeURIComponent('xxxxx.cloudax.dynamics.com'))}/tables/@{encodeURIComponent(encodeURIComponent('CustomerGroups'))}/items" }
I could see two resolutions to this, one is to resolve this "xxxxx.cloudax.dynamics.com" to an ARM template parameter. Or resolve this to a logic app parameter.

The upside of the ARM template parameter is that when you look at it in the designer experience everything works. If you change this to a logic app parameter it won't work at design time, but will work at runtime.

Logic App parameter
"path":ย "/datasets/@{encodeURIComponent(encodeURIComponent(parameters('Organization')))}/tables/@{encodeURIComponent(encodeURIComponent('CustomerGroups'))}/items",

ARM parameter
"path":ย "[concat('/datasets/@{encodeURIComponent(encodeURIComponent(''',parameters('Organization')ย ,'''))}/tables/@{encodeURIComponent(encodeURIComponent(''CustomerGroups''))}/items')]"

Command not recognized in Powershell Core

Hello,

I'm trying to use Get-LogicAppTemplate and Get-ParameterTemplate with PowerShell Core, but I get every time this error: Get-LogicAppTemplate: The term 'Get-LogicAppTemplate' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Configuration:

  • Azure Cloud Shell with PowerShell:

Capture dโ€™รฉcran 2020-04-09 ร  11 14 55

  • MacOS 10.15.3 with PowerShell Core 7.0.0:

Capture dโ€™รฉcran 2020-04-09 ร  11 20 05

However, commands are properly working on my dual boot Windows environment.

Is LogicAppTemplate module not working on PowerShell Core?

Regards,

Grรฉgoire

Hardcoded values for organization for CDS connectors of type dynamicscrmonline

We are facing issue with exporting template of Logic app which contains older dynamicscrmonline typed connectors.
We have action as shown in below:

"Create_error_log": {
    "inputs": {
        "body": {
            <Some Parameters>
        },
        "host": {
            "connection": {
                "name": "@parameters('$connections')['dynamicscrmonline']['connectionId']"
            }
        },
        "method": "post",
        "path": "/datasets/@{encodeURIComponent(encodeURIComponent('orgxxxxxxx.crm4'))}/tables/@{encodeURIComponent(encodeURIComponent('accounts'))}/items"
    },
    "runAfter": {
        "Scope": [
            "Failed",
            "Skipped",
            "TimedOut"
        ]
    },
    "type": "ApiConnection"
}

When we export template from this using Get-LogicAppTemplate cmdlet, it is exported as is and no parameters are exported.
We want to make CE organization ("orgxxxxxxx.crm4") to be replaced with parameter.
Please let me know if any more information is required.

Clarify README

The README.md contains:

For extraction with KeyVault reference liks created use:

Can you clarify what the liks part means?

Function id is not generating properly

Hi guys,

Found a new issue on parsing the function action. Seems like when the function app is been parsed the order of the regex fixes causes the template to became invalid, as it generates this:

"function": { "id": "[concat('/subscriptions/',subscription().subscriptionId,'/resourceGroups/', resourceGroup().name,'/providers/Microsoft.Web/sites/', **parameters('', parameters('ActivityCallIDGenerator-FunctionName'),'-FunctionApp'**),'/functions/', parameters('ActivityCallIDGenerator-FunctionName'),'')]" }

Instead of this:

"function": { "id": "[concat('/subscriptions/',subscription().subscriptionId,'/resourceGroups/', resourceGroup().name,'/providers/Microsoft.Web/sites/', **parameters('ActivityCallIDGenerator-FunctionApp'),**'/functions/', parameters('ActivityCallIDGenerator-FunctionName'),'')]" }

This is caused by the following lines in TemplateGenerator.cs:

curr = curr.Replace(matches.Groups["functionApp"].Value, "', parameters('" + AddTemplateParameter(action.Name + "-FunctionApp", "string", matches.Groups["functionApp"].Value) + "'),'"); curr = curr.Replace(matches.Groups["functionName"].Value, "', parameters('" + AddTemplateParameter(action.Name + "-FunctionName", "string", matches.Groups["functionName"].Value) + "'),'");

As they are in the wrong order.

I'm submitting a pull request to fix that issue.

Also, noticed that there is no Unit Tests for Function samples. I tried to create one but I am struggling at the moment on creating a good sample file (can't seem to extract the template from the right place). If one of you guys add a sample file with function ID there, I can write the unit tests this don't break at a later stage.

Cheers, Wagner.

Error in getting the LogicApp Template

Hello - Iam trying to download the logicapp template. I followed the exact steps that are provided in the description. I get the below error when i try to download

cmd> Get-LogicAppTemplate

cmdlet Get-LogicAppTemplate at command pipeline position 1
Supply values for the following parameters:
(Type !? for Help.)
LogicApp: XXXXXXXXXXXXXXx-XXXXXXXXXx
ResourceGroup: RG-Dev-xxx
SubscriptionId: eexxxxxxxx-1xxxxx-4xxx-bc24-eb6xxxxxcfa
Get-LogicAppTemplate : Aggregation Exception thrown, One or more errors occurred., first Exception message is: Value
cannot be null.
Parameter name: s, for more information read the output file.
At line:1 char:1

  • Get-LogicAppTemplate
  •   + CategoryInfo          : NotSpecified: (:) [Get-LogicAppTemplate], Exception
      + FullyQualifiedErrorId : System.Exception,LogicAppTemplate.GeneratorCmdlet
    
    

Any Inputs would be really helpful.

Managed identity properties are not generated properly

Its seems that when working with managed identities the ARM template is not generated properly.
When comparing the code from Azure portal and the generated code from the tool there is no authentication property created for the ARM. See below error when deploying.

Any idea what I'm doing wrong. when running the logic app from azure portal, there is no problem.

[error]WorkflowManagedIdentityConfigurationInvalid: The workflow connection parameter 'azuredatafactory' is not valid. The API connection 'azuredatafactory' is configured to support managed identity but the connection parameter is either missing 'authentication' property in connection properties or authentication type is not 'ManagedServiceIdentity'

Document usage instructions with azure-cli (instead of armclient)

Its possible (and in fact fairly simple) to use this module with Azure CLI instead of armclient:

Assuming you're already signed in with the Azure CLI (az login):

Get-LogicAppTemplate -Token (az account get-access-token | ConvertFrom-Json).accessToken -LogicApp ... <other parameters>

Documenting this in this issue for posterity, and also with the idea it could be added to the README as well.

Error when calling Get-LogicAppTemplate

Get the following error:

Get-LogicAppTemplate : Aggregation Exception thrown, One or more errors occurred., first Exception message is: Cannot access child value on Newtonsoft.Json.Linq.JValue., for more information read the out
At line:1 char:1

  • Get-LogicAppTemplate -LogicApp LogicAppName ...
  •   + CategoryInfo          : NotSpecified: (:) [Get-LogicAppTemplate], Exception
      + FullyQualifiedErrorId : System.Exception,LogicAppTemplate.GeneratorCmdlet
    

Wrong servicebus-related parameter names

In LogicAppTemplateCreator/LogicAppTemplate/TemplateGenerator.cs, there's section of code:

                    else if (concatedId.EndsWith("/servicebus')]"))
                    {
                        var namespace_param = AddTemplateParameter($"servicebus_namespace_name", "string", "REPLACE__servicebus_namespace");
                        var sb_resource_group_param = AddTemplateParameter($"servicebus_resourceGroupName", "string", "REPLACE__servicebus_rg");
                        var servicebus_auth_name_param = AddTemplateParameter($"servicebus_accessKey_name", "string", "RootManageSharedAccessKey");

                        connectionParameters.Add(parameter.Name, $"[listkeys(resourceId(parameters('servicebus_rg'),'Microsoft.ServiceBus/namespaces/authorizationRules', parameters('servicebus_namespace_name'), parameters('servicebus_auth_name')), '2017-04-01').primaryConnectionString]");

                    }

The above code creates 3 parameters: "servicebus_namespace_name", "servicebus_resourceGroupName" and "servicebus_accessKey_name".

But the next line uses parameters with the same purposes but different spellings "servicebus_rg" and "servicebus_auth_name:

                        connectionParameters.Add(parameter.Name, $"[listkeys(resourceId(parameters('servicebus_rg'),'Microsoft.ServiceBus/namespaces/authorizationRules', parameters('servicebus_namespace_name'), parameters('servicebus_auth_name')), '2017-04-01').primaryConnectionString]");

The template that's generated looks like:

"servicebus_namespace_name": {
  "type": "string",
  "defaultValue": "REPLACE__servicebus_namespace"
},
"servicebus_resourceGroupName": {
  "type": "string",
  "defaultValue": "REPLACE__servicebus_rg"
},
"servicebus_accessKey_name": {
  "type": "string",
  "defaultValue": "RootManageSharedAccessKey"
},

and:

    "displayName": "[parameters('servicebus-2_displayName')]",
    "parameterValues": {
      "connectionString": "[listkeys(resourceId(parameters('servicebus_rg'),'Microsoft.ServiceBus/namespaces/authorizationRules', parameters('servicebus_namespace_name'), parameters('servicebus_auth_name')), '2017-04-01').primaryConnectionString]"
    }

legalEntity from D365 F&O trigger should be parameterized

Hi!

When extracting a logic app triggered by the D365 Fin&Ops connector, there's a parameter called LegalEntity. This is not parameterized upon extraction:


          "triggers": {
            "When_a_Business_Event_occurs": {
              "type": "ApiConnectionWebhook",
              "inputs": {
                "body": {
                  "NotificationUrl": "@{listCallbackUrl()}"
                },
                "host": {
                  "connection": {
                    "name": "@parameters('$connections')['dynamicsax']['connectionId']"
                  }
                },
                "path": "my_path_is_here",
                "queries": {
                  "businesseventcategory": "Alerts",
                  "legalEntity": "<THIS_PARAMETER>"
                }
              }
            }

What I refer to is the property marked with "<THIS_PARAMETER>".

This also applies to the "List all items in table"-actions and such, where Odata filter is applied using a pre-defined parameter. It would be extremely useful to be able to parameterize these, since it would make it possible to dynamically set filters during deploy.

Cheers!

Template file is empty after running Get-LogicTemplate

Hello,
I am trying to learn how the template extraction works.

I create a logic app using the template - https://github.com/Azure/azure-quickstart-templates/tree/master/101-logic-app-create

Then i ran the following command
armclient token $SubscriptionId | Get-LogicAppTemplate -LogicApp $LogicApps -ResourceGroup $ResourceGroup -SubscriptionId $SubscriptionId -TenantName $TenantName -Verbose | Out-File logic-app-template.json

However I see an empty file in the directory

Swagger function action not supported

If function app has an api definition and logic app function uses it, there is a NullReferenceException in TemplateGenerator.cs:
((JObject)definition["actions"][action.Name]["inputs"]["function"]).Value("id")

There is no 'function' property in the action definition if using swagger definition in the function.

Common Data Service actions keep hardcoded environment

When exporting a Logic App with a CDS action, the action keeps its "path" property hardcoded:

     "path": "/v2/datasets/@{encodeURIComponent(encodeURIComponent('orgdXXXXXX.crm4'))}/tables/@{encodeURIComponent(encodeURIComponent('cdm_table'))}/items/@{encodeURIComponent(encodeURIComponent(triggerBody()?['empNumber']))}"

This is very hard to de-hardcode especially is a workflow expression is used - we need to add an apostrophe ARM parameter and concatenate to the formula.

Null FTP parameters

Hi!

These FTP parameters are generated with null values which causes the ARM template deploy to fail:

ftp_closeConnectionAfterRequestCompletion (default is false)
ftp_password (should be empty string or dummy value?)

Best regards,
Ludvig Falck

httpTriggerUrl gets wrong URL upon extraction

I've noticed an anomaly in the extraction of the httpTriggerUrl object when using a HTTP trigger.

This is what we deploy:


  "outputs": {
    "httpTriggerUrl": {
      "type": "string",
      "value": "[listCallbackURL(concat(resourceId(resourceGroup().name,'Microsoft.Logic/workflows/', parameters('logicAppName')), '/triggers/request'), '2016-06-01').value]"
    }
  }

If I extract it again after deploy, this is what I get:

  "outputs": {
    "httpTriggerUrl": {
      "type": "string",
      "value": "[listCallbackURL(concat(resourceId(resourceGroup().name,'Microsoft.Logic/workflows/', parameters('logicAppName')), '/triggers/manual'), '2016-06-01').value]"
    }
  }

Please notice the change of '/triggers/request' to '/triggers/manual'.
The workaround so far is to manually replace the 'manual' route with 'request', before commit.

ActiveDirectoryOAuth authentication '-Authority' parameter - No default value

TemplateGenerator.cs creates '-Authority' parameter with no default value like this example:

"Get_FullLoad_Data-Authority": {
  "type": "string",
  "defaultValue": ""
},

When I query ARM:

(Search-AzGraph -Include DisplayName -Query 'where type =~ "Microsoft.Logic/workflows" | where name =~ "logic-azureactivedirectory-fullload-01"|where resourceGroup =~ "rg-hrfuncapp-dev"').properties.definition.actions.Try_Scope.actions.Get_FullLoad_Data.inputs.authentication

I don't see "authority" in the results:

type : ActiveDirectoryOAuth
tenant : @variables('Secret')?['Tenant']
clientId : @variables('Secret')?['ClientId']
audience : @variables('Secret')?['ApiUrl']
secret : @variables('Secret')?['ClientSecret']

The above results (with no "authority") seems to match Microsoft documentation https://docs.microsoft.com/en-us/azure/logic-apps/logic-apps-custom-api-authentication which has the following example that also has no "authority" value:

{
"tenant": "",
"audience": "",
"clientId": "",
"secret": "",
"type": "ActiveDirectoryOAuth"
}

Could TemplateGenerator.cs please not add the "-Authority" template parameter if "authority" is not returned by ARM. I ask this because it creates a template parameter with no default value which then breaks Get-ParameterTemplate.

Custom Connector

1. The issue

I have Logic App and LogicApp Custom connector on Azure and they are working as expected; without any problem, the same goes with CI/CD behind, but when running the module Get-LogicAppTemplate I got the following error:
image

2. The analysis

I tried to find where the problem was and it seems that it occurs on LogicApp Custom Connector, which is connected with LogicApp with API connection. As a reminder; the part that will be shown below is working perfectly and the connection is working as expected in Azure. If I deleted the below part of the code from Custom Connector the problem disappear and I can use the "Get-LogicAppTemplate" module without any issue
image

Relative paths cannot be used in Get-ParameterTemplate

Relative paths aren't being resolved relative to the current working directory. In this case, this was an admin PS session, which starts in C:\WINDOWS\system32

PS C:\src\sandbox> Get-ParameterTemplate -TemplateFile ./template.json | Out-File ./template.params.json
Get-ParameterTemplate : Could not find file 'C:\WINDOWS\system32\template.json'.
At line:1 char:1
+ Get-ParameterTemplate -TemplateFile ./template.json | Out-File ./temp ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-ParameterTemplate], FileNotFoundException
    + FullyQualifiedErrorId : System.IO.FileNotFoundException,LogicAppTemplate.ParamGenerator

Action names with apostrophe not exported correctly

Create an action with an apostrophe in the name: "Get Worker's Number".

Export

When re-importing, getting error:

New-AzResourceGroupDeployment : 15:55:26 - Error: Code=InvalidTemplate; Message=Deployment template language
expression evaluation failed: 'Unable to parse language expression 'parameters('Get_Worker's_Number')':

SQL V2 connectors not parameterized

I am using a SQL Server "Execute Stored Procedure V2" connector in my logic app and the extraction does not create parameters for the "path" value in this logic app connector. It does properly parameterize the sql connection, but the V2 connectors also have a "hardcoded" path value that contains the name of the sql server, like this:

"host": {
"connection": {
"name": "@parameters('$connections')['sql_1']['connectionId']"
}
},
"method": "post",
"path": "/v2/datasets/@{encodeURIComponent(encodeURIComponent('my_DEV_SQL_Server.database.windows.net'))},@{encodeURIComponent(encodeURIComponent('my_database_name'))}/procedures/@{encodeURIComponent(encodeURIComponent('[SAGE].[usp_my_stored_proc_name'))}"
}

In the snippet above... the value for "my_DEV_SQL_Server" is what I need to have parameterized during the logic app extraction.

Custom Connector Implementation

Hey guys, especially Mattias, I see that the custom connector template was not really done. Do you mind if I take a crack at that?

The input is not a valid Base-64 string as it contains a non-base 64 character...

I have 2 logic apps in the same resource group, that I send through the LogicAppTemplateCreator. One generates the template just fine, the other generates this error and generates a blank template:

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal
character among the padding characters.

Any idea what is wrong?

AccessControl settings not exported

The issue

When running the extractor the property AccessControl is not exported.

The effect

This means that any changes or updates to IP-restrictions, or Authentication must be added manually and added to the generated file.

Any manual "fiddeling" with an ARM template after generation will always present the risk that the manual step is forgotten.

Tip

Use resources.azure.com to view the full ARM-template of any deployed resource.

Get-LogicAppTemplate : Aggregation Exception thrown, One or more errors occurred., first Exception message is: Object reference not set to an instance of an object.

Hi,

I have created my own script to pull a list of logic apps from my subscription/rg and spit out the templates for each. I am running into the following error when I get to the Get-LogicAppTemplate call:

Get-LogicAppTemplate : Aggregation Exception thrown, One or more errors occurred., first Exception message is: Object reference not set to an instance of an
object., for more information read the output file.
At C:\Users\corey\source\repos\LogicAppUtils\ImportLogicAppsFromRG-UsingLogicAppTemplateCreator-cdp.ps1:18 char:2

  • Get-LogicAppTemplate -LogicApp $logicAppNamePrefix -ResourceGroup ...
    
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [Get-LogicAppTemplate], Exception
    • FullyQualifiedErrorId : System.Exception,LogicAppTemplate.GeneratorCmdlet

Here is my script. Also, I have made sure that I am logged in and the subscription is available.

Import-Module C:\PathToCode\LogicAppTemplateCreator\LogicAppTemplate\bin\Debug\LogicAppTemplate.dll!

$logicAppNamePrefixes = @("logic-app-name")
foreach ($logicAppNamePrefix in $logicAppNamePrefixes) {
$logicAppTemplateOutFilePath = "C:\PathToTemplateFile" + $logicAppNamePrefix + ".json"
$logicAppParamsOutFilePath = "C:\PathToTemplateFile" + $logicAppNamePrefix + ".parameters.json"

Write-Host $logicAppTemplateOutFilePath
Write-Host $logicAppParamsOutFilePath
Write-Host $logicAppNamePrefix

Get-LogicAppTemplate -LogicApp $logicAppNamePrefix -ResourceGroup "rg" -SubscriptionId "subId" -Verbose | Out-File $logicAppTemplateOutFilePath
#Get-ParameterTemplate -TemplateFile $logicAppTemplateOutFilePath | Out-File $logicAppParamsOutFilePath

}

Thanks for any help!

Corey

Boolean parameters are not handled successfully

Hi,
When a FTP connection is used by the Logic App for example, there are multiple parameters for this connection that are of type Boolean (i.e isSSL for example).
The value generated in the template for those parameters is not ok: it should be set to false or true and not False or True (the F and T must be in lower case) to be handled correctly in the JSON.

Generated names for KeyVault values generates errors

The very useful feature generates key names for the keyvault. Those generated names contains the _ (underscore) sign and that is not allowed in KeyVault. It would be better to add a - (minus) sign instead.

parameter -DisableState

suggestion
remove parameter -DisableState from Get-LogicAppTemplate

extract the WorkflowProperties object "state" and add a parameter with default value = "Enabled"
This way we can control it in an easier way.

This will be helpful if we need to deploy a logicApp that we want to deploy but start up later.

Generation for custom connector generates hard coded value

I tried to fix this in the code, but I lack the skillz.
When creating a template with a custom connector. The ARM template contains a value for the connector. This value would benefit from being parameterized. Example:

"id": "[concat('/subscriptions/',subscription().subscriptionId,'/resourceGroups/',parameters('MyValue-CustomConnector-ResourceGroup'),'/providers/Microsoft.Web/customApis/MyValue-CustomConnector-SOAPPassthru-DEV')]"

would be great if it looked like this:

"id": "[concat('/subscriptions/',subscription().subscriptionId,'/resourceGroups/',parameters('MyValue-CustomConnector-ResourceGroup'),'/providers/Microsoft.Web/customApis/', parameters('MyValue-CustomConnector-Connectorname)]",

Same hard-coded string added as multiple parameters

This is not necessarily a bug but it would still be good to have it as an option.

Assuming we have two HTTP Get actions, both with the same hard-coded URL. When exporting the template, it will generate two parameters:

"HTTP-URI": {
  "type": "string",
  "defaultValue": "https://www.bing.com/search?q=shopping"
},
"HTTP_get_again-URI": {
  "type": "string",
  "defaultValue": "https://www.bing.com/search?q=shopping"
},

Sometimes you may want to have just one parameter for each unique string. So maybe adding an additional option for preventing duplicates when generating parameters is the way to go.

Get-LogicAppTemplate - Aggregation Exception

I'm trying to import my template from my Logic App and I get the following exception:

Get-LogicAppTemplate : Aggregation Exception thrown, One or more errors occurred., first Exception
message is: Object reference not set to an instance of an object., for more information read the
output file.
At line:1 char:1

  • Get-LogicAppTemplate -LogicApp logic-app-key-vault-test -ResourceGrou ...
  • CategoryInfo : NotSpecified: (:) [Get-LogicAppTemplate], Exception
  • FullyQualifiedErrorId : System.Exception,LogicAppTemplate.GeneratorCmdlet

I have double checked everything, Subscription Id is correct. Resource names are also correct. I would almost think that this happens because I have two active Subscriptions with the same name, because the same command works in another tenant with the same resource.

Client Credentials paramters not added to EventGrid connector

When extracting Logic Apps with trigger for eventgrid the parameters for clientcredentials connectivity has disappered.
now:

{
      "type": "Microsoft.Web/connections",
      "apiVersion": "2016-06-01",
      "location": "[parameters('logicAppLocation')]",
      "name": "[parameters('azureeventgrid_name')]",
      "properties": {
        "api": {
          "id": "[concat('/subscriptions/',subscription().subscriptionId,'/providers/Microsoft.Web/locations/',parameters('logicAppLocation'),'/managedApis/azureeventgrid')]"
        },
        "displayName": "[parameters('azureeventgrid_displayName')]"
      }
    }

And this is how it was:

{
      "type": "Microsoft.Web/connections",
      "apiVersion": "2016-06-01",
      "location": "[parameters('logicAppLocation')]",
      "name": "[parameters('azureeventgrid_name')]",
      "properties": {
        "api": {
          "id": "[concat('/subscriptions/',subscription().subscriptionId,'/providers/Microsoft.Web/locations/',parameters('logicAppLocation'),'/managedApis/azureeventgrid')]"
        },
        "displayName": "[parameters('azureeventgrid_displayName')]",
        "parameterValues": {
          "token:clientId": "[parameters('azureeventgrid_token:clientId')]",
          "token:clientSecret": "[parameters('azureeventgrid_token:clientSecret')]",
          "token:TenantId": "[parameters('azureeventgrid_token:TenantId')]",
          "token:resourceUri": "[parameters('azureeventgrid_token:resourceUri')]",
          "token:grantType": "[parameters('azureeventgrid_token:grantType')]"
        }
      }
    }

Including `[resourceGroup().location]` as a valid value for location parameter doesn't do anything.

If the resource group's location is not one of the explicit values listed, deployment of the logic app will still fail. The [resourceGroup().location] value in the validValues list has no effect:

2019-09-16T17:24:05.1587254Z DEBUG: msrest.http_logger : {"error":{"code":"InvalidTemplate","message":"Deployment template validation failed: 'The 
2019-09-16T17:24:05.1587465Z provided value 'usgovarizona' for the template parameter 'logicAppLocation' at line '1' and column '334' is not valid. 
2019-09-16T17:24:05.1587714Z The parameter value is not part of the allowed value(s): '[resourceGroup().location],eastasia,southeastasia,centralus,e
2019-09-16T17:24:05.1587952Z astus,eastus2,westus,northcentralus,southcentralus,northeurope,westeurope,japanwest,japaneast,brazilsouth,australiaeast
2019-09-16T17:24:05.1588162Z ,australiasoutheast,westcentralus,westus2'.'.","additionalInfo":[{"type":"TemplateViolation","info":{"lineNumber":1,"po
2019-09-16T17:24:05.1588366Z sitionNumber":334,"snippet":""}}]}}

Error AggregateException

Hi,
When I use the PowerShell cmdlets, I got a AggregateException in the ProcessRecord method.
There is an innerException of type ArgumentTypeException with the message 'String cannot be of zero length. Parameter name oldValue.

I have this error with one of my Logic App. This is one Logic App with a recurrence as a trigger and multiple File System connectors and an OnPremise Data Gateway connection. Maybe this can help ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.