OctopusDeploy / Library

| Public | A repository of step templates and other community-contributed extensions to Octopus Deploy
Other
171 stars 504 forks source link

Issue with Microsoft Teams - Post a message #1392

Closed rheywood75 closed 1 year ago

rheywood75 commented 1 year ago

Step template

Microsoft Teams - Post a message

Step version

latest as of 8/28/2023

Octopus version

v2022.2 (Build 7580)

Step template parameter inputs

No response

What happened

We are getting an error message: "Error occurred executing command (on attempt 1 of 1): Exception calling "Invoke" with "0" argument(s): "A parameter cannot be found that matches parameter name 'UseBasicParsing'."

Reproduction steps

Run this script on PowerShell version 4.

More Information

Our on-prem octopus set-up is on some older Win Server 2012 R2. It is running PowerShell 4. Here is output from our server that is failing to run this script.

PS C:\Users> get-help Invoke-RestMethod

NAME Invoke-RestMethod

SYNTAX Invoke-RestMethod [-Uri] [-Method {Default | Get | Head | Post | Put | Delete | Trace | Options | Merge | Patch}] [-WebSession ] [-SessionVariable ] [-Credential

] [-UseDefaultCredentials] [-CertificateThumbprint ] [-Certificate ] [-UserAgent ] [-DisableKeepAlive] [-TimeoutSec ] [-Headers ] [-MaximumRedirection ] [-Proxy ] [-ProxyCredential ] [-ProxyUseDefaultCredentials] [-Body ] [-ContentType ] [-TransferEncoding {chunked | compress | deflate | gzip | identity}] [-InFile ] [-OutFile ] [-PassThru] [] ############################################################################# This is from another machine: PS C:\Users> $PSVersionTable.PSVersion Major Minor Build Revision ----- ----- ----- -------- 5 1 19041 3031 PS C:\Users> get-help Invoke-RestMethod NAME Invoke-RestMethod SYNOPSIS Sends an HTTP or HTTPS request to a RESTful web service. SYNTAX Invoke-RestMethod [-Uri] [-Body ] [-Certificate ] [-CertificateThumbprint ] [-ContentType ] [-Credential ] [-DisableKeepAlive] [-Headers ] [-InFile ] [-MaximumRedirection ] [-Method {Default | Get | Head | Post | Put | Delete | Trace | Options | Merge | Patch}] [-OutFile ] [-PassThru] [-Proxy ] [-ProxyCredential ] [-ProxyUseDefaultCredentials] [-SessionVariable ] [-TimeoutSec ] [-TransferEncoding {chunked | compress | deflate | gzip | identity}] [-**UseBasicParsing**] [-UseDefaultCredentials] [-UserAgent ] [-WebSession ] [] As you can see, version 4 doesn't have the UseBasicParsing parameter, but version 5 does. In the script, it doesn't use the argument UseBasicParsing if the PowerShell version is "-ge 6." Is it possible to add support for version 4 by modifying the 'if' statement condition in the script and we can avoid this issue? Sorry we don't have newer hardware and software.
twerthi commented 1 year ago

@rheywood75 Are you on our Community Slack? I've a fix, but don't have Teams to test with. Would you mind testing it for me?

rheywood75 commented 1 year ago

I don’t think I am on the Slack Community. I would be willing to test a fix. Ricky HeywoodOn Aug 29, 2023, at 7:59 AM, Shawn Sesna @.***> wrote: @rheywood75 Are you on our Community Slack? I've a fix, but don't have Teams to test with. Would you mind testing it for me?

—Reply to this email directly, view it on GitHub, or unsubscribe.You are receiving this because you were mentioned.Message ID: @.***>

twerthi commented 1 year ago

Give this version a go, if it works for you, I'll submit the PR

{
  "Id": "b0e7c401-013d-45eb-92d4-9dc373b898b0",
  "Name": "Microsoft Teams - Post a message Copy",
  "Description": "Posts a message to Microsoft Teams using a general webhook.",
  "ActionType": "Octopus.Script",
  "Version": 1,
  "CommunityActionTemplateId": null,
  "Packages": [],
  "Properties": {
    "Octopus.Action.Script.ScriptBody": "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12\n# Helper functions\nfunction Retry-Command {\n    [CmdletBinding()]\n    Param(\n        [Parameter(Position=0, Mandatory=$true)]\n        [scriptblock]$ScriptBlock,\n \n        [Parameter(Position=1, Mandatory=$false)]\n        [int]$Maximum = 5,\n\n        [Parameter(Position=2, Mandatory=$false)]\n        [int]$Delay = 100\n    )\n\n    Begin {\n        $count = 0\n    }\n\n    Process {\n    \t$ex=$null\n        do {\n            $count++\n            \n            try {\n                Write-Verbose \"Attempt $count of $Maximum\"\n                $ScriptBlock.Invoke()\n                return\n            } catch {\n                $ex = $_\n                Write-Warning \"Error occurred executing command (on attempt $count of $Maximum): $($ex.Exception.Message)\"\n                Start-Sleep -Milliseconds $Delay\n            }\n        } while ($count -lt $Maximum)\n\n        # Throw an error after $Maximum unsuccessful invocations. Doesn't need\n        # a condition, since the function returns upon successful invocation.\n        throw \"Execution failed (after $count attempts): $($ex.Exception.Message)\"\n    }\n}\n# End Helper functions\n[int]$timeoutSec = $null\n[int]$maximum = 1\n[int]$delay = 100\n\nif(-not [int]::TryParse($OctopusParameters['Timeout'], [ref]$timeoutSec)) { $timeoutSec = 60 }\n\n\nIf ($OctopusParameters[\"TeamsPostMessage.RetryPosting\"] -eq $True) {\n\tif(-not [int]::TryParse($OctopusParameters['RetryCount'], [ref]$maximum)) { $maximum = 1 }\n\tif(-not [int]::TryParse($OctopusParameters['RetryDelay'], [ref]$delay)) { $delay = 100 }\n\t\n    Write-Verbose \"Setting maximum retries to $maximum using a $delay ms delay\"\n}\n\n$payload = @{\n    title = $OctopusParameters['Title']\n    text = $OctopusParameters['Body'];\n    themeColor = $OctopusParameters['Color'];\n}\n\nRetry-Command -Maximum $maximum -Delay $delay -ScriptBlock {\n\t# Declare variable for parameters\n    $invokeParameters = @{}\n    $invokeParameters.Add(\"Method\", \"POST\")\n    $invokeParameters.Add(\"Uri\", $OctopusParameters['HookUrl'])\n    $invokeParameters.Add(\"Body\", ($payload | ConvertTo-Json -Depth 4))\n    $invokeParameters.Add(\"ContentType\", \"application/json; charset=utf-8\")\n    $invokeParameters.Add(\"TimeoutSec\", $timeoutSec)\n    \n    # Check for UseBasicParsing\n    if ((Get-Command Invoke-RestMethod).Parameters.ContainsKey(\"UseBasicParsing\"))\n    {\n    \t# Add the basic parsing argument\n        $invokeParameters.Add(\"UseBasicParsing\", $true)\n    }\n<#    \n    # Check version of PowerShell\n    if ($PSVersionTable.PSVersion.Major -eq 5)\n    {\n\t\t$Response = Invoke-RestMethod -Method POST -Uri $OctopusParameters['HookUrl'] -Body ($payload | ConvertTo-Json -Depth 4) -ContentType 'application/json; charset=utf-8' -TimeoutSec $timeoutSec -UseBasicParsing\n    }\n    else\n    {\n    \t$Response = Invoke-RestMethod -Method POST -Uri $OctopusParameters['HookUrl'] -Body ($payload | ConvertTo-Json -Depth 4) -ContentType 'application/json; charset=utf-8' -TimeoutSec $timeoutSec \n    }\n#>\n\n\t$Response = Invoke-RestMethod @invokeParameters\n    Write-Verbose \"Response: $Response\"\n}",
    "Octopus.Action.Script.Syntax": "PowerShell",
    "Octopus.Action.Script.ScriptSource": "Inline"
  },
  "Parameters": [
    {
      "Id": "f569de11-b7e1-499d-b35a-2de3fbae096b",
      "Name": "HookUrl",
      "Label": "Webhook Url",
      "HelpText": "The specific URL provided by Microsoft Teams when adding an _Incoming WebHook_ connector to a team channel. Copy and paste the full Webhook URL from Microsoft Teams here.",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "1da2f9c3-f3d7-4754-916e-da82c7a46ce9",
      "Name": "Title",
      "Label": "Message title",
      "HelpText": "The title of the message that will be posted to your Microsoft Teams channel.",
      "DefaultValue": "#{Octopus.Project.Name} #{Octopus.Release.Number} deployed to #{Octopus.Environment.Name}#{if Octopus.Deployment.Tenant.Id} for #{Octopus.Deployment.Tenant.Name}#{/if}",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "4eac4ad1-e591-41d2-8d31-f4248b6de394",
      "Name": "Body",
      "Label": "Message body",
      "HelpText": "The message body of post being added to your Microsoft Teams channel.",
      "DefaultValue": "For more information, please see [deployment details](#{if Octopus.Web.ServerUri}#{Octopus.Web.ServerUri}#{else}#{Octopus.Web.BaseUrl}#{/if}#{Octopus.Web.DeploymentLink})!",
      "DisplaySettings": {
        "Octopus.ControlType": "MultiLineText"
      }
    },
    {
      "Id": "62fbf3d9-ddb8-4a68-b201-197585a322c8",
      "Name": "Color",
      "Label": "Color",
      "HelpText": "The color to use for the border on the side of the message.",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "a0d98950-ed52-418e-96fe-28a98bfa6c8c",
      "Name": "Timeout",
      "Label": "Timeout in seconds",
      "HelpText": "The maximum timout in seconds for each request.",
      "DefaultValue": "60",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "c1213b2b-daee-41e3-a9fd-54f3d7668492",
      "Name": "TeamsPostMessage.RetryPosting",
      "Label": "Retry posting message",
      "HelpText": "Should retries be made? If this option is enabled, the step will attempt to retry the posting of message to teams up to the set retry count. Default: `False`.",
      "DefaultValue": "False",
      "DisplaySettings": {
        "Octopus.ControlType": "Checkbox"
      }
    },
    {
      "Id": "61311001-8c76-46dd-8e55-3c4d6ce67d38",
      "Name": "TeamsPostMessage.RetryCount",
      "Label": "Retry Count",
      "HelpText": "The maximum number of times to retry the post before allowing failure. Default 1",
      "DefaultValue": "1",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "8ec8c2f4-5dcc-404f-b630-bda469b259b4",
      "Name": "TeamsPostMessage.RetryDelay",
      "Label": "Retry delay in milliseconds",
      "HelpText": "The amount of time in milliseconds to wait between retries. Default 100",
      "DefaultValue": "100",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    }
  ],
  "StepPackageId": "Octopus.Script",
  "$Meta": {
    "ExportedAt": "2023-08-31T14:37:24.937Z",
    "OctopusVersion": "2023.2.13239",
    "Type": "ActionTemplate"
  },
  "LastModifiedBy": "Your GitHub Username",
  "Category": "other"
}
rheywood75 commented 1 year ago

@twerthi that worked! :)

twerthi commented 1 year ago

Excellent! Thank you for testing, I've submitted the PR to fix it in the template, stay tuned :)

twerthi commented 1 year ago

@rheywood75 New version available.