Can't build customise Slack notifications - sh

After much research, I discovered this .sh script, which allows me to send a very simple personalized notification to a Slack channel (I failed to send it to a particular member).
The problem, which I am facing, is that of formatting the message of the notification. The tags offered on the Slack site to format the notification do not work correctly (that I do not know how to use them!).
The notification must be built "from scratch" at the end of each execution of the Rundeck job.
Rundeck's "On Failure" and "On Success" notifications are not suitable for users.
This the sh script :
#!/bin/bash
​#Usage: slackpost <channel> <message>
slackhost="https://hooks.slack.com/services"
token="XXXXXXXXXX/XXXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXX"
slack_username="Someone-who-loves-you"
slack_icon="smile"​
channel=$1
if [[ $channel == "" ]]
then
echo "No channel specified"
exit 1
fi
text="$2"
if [[ $text == "" ]]
then
echo "No text specified"
exit 1
fi
escapedText=$(echo $text | sed 's/"/\"/g' | sed "s/'/\'/g" )
json="{\"channel\": \"#$channel\", \"username\":\"${slack_username}\", \"icon_emoji\":\":${slack_icon}:\", \"text\": \"$escapedText\"}"
curl -s -d "payload=$json" "$slackhost/$token"
The variable $text is filled with the content of a .txt file (myFileText):
myFileText content is as follows:
text="",
{
blocks=[
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Hello world! <#UNVD64N02> :tada: \n\n - a \n-b"
}
}
]
}
{
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Hello, Assistant to the Regional Manager John Doe! *Martin Scott* wants to know where you'd like to take the Paper Company investors to dinner tonight.\n\n *Please select a restaurant:*"
}
}
]
}
The .sh script is run as follows:
sh slack_post.sh "channel-receiving-the-notification" "$(< myFileText)"
As result I have :
invalid_payload
Any idea could be helpful.

Related

How to get the top-n files sorted by cognitive complexity in a project using REST API?

How to get the top 500 files in a project sorted by cognitive complexity (using the REST API)? The intent is to export the metric for use with another tool.
On a current SonarQube (8.2, though this would work with earlier versions as well, according to documentation), and presuming your instance is on localhost:9000 and the project's name is project1, this bash script curls SonarQube for top 500 files and their cognitive complexity values, sorted by cognitive complexity, then pretty prints it with jq, and displays it in less:
#!/bin/bash
curl \
"localhost:9000"\
"/api/measures/component_tree?"\
"component=project1&"\
"strategy=leaves&"\
"metricKeys=cognitive_complexity&"\
"s=metric&"\
"metricSort=cognitive_complexity&"\
"asc=false&"\
"ps=500" \
| jq "[.components[] | {path: .path, cognitive_complexity: .measures[0].value}]" \
| less
Above script produces output as such:
[
{
"path": "desktop/src/main/java/bisq/desktop/main/offer/MutableOfferViewModel.java",
"cognitive_complexity": "319"
}
{
"path": "desktop/src/main/java/bisq/desktop/main/offer/offerbook/OfferBookView.java",
"cognitive_complexity": "304"
}
{
"path": "p2p/src/main/java/bisq/network/p2p/network/Connection.java",
"cognitive_complexity": "228"
}
{
"path": "desktop/src/main/java/bisq/desktop/main/support/dispute/DisputeView.java",
"cognitive_complexity": "225"
}
{
"path": "desktop/src/main/java/bisq/desktop/util/GUIUtil.java",
"cognitive_complexity": "192"
}
...

How to escape $ in Visual Studio Code snippet creation

It seems when using PHP variables like $_SERVER the code snippet ignores the $. For example
{
// Example:
"IP Address Test": {
"scope": "php",
"prefix": "iptest",
"body": [
"// Debugging",
"if($_SERVER[\"REMOTE_ADDR\"]=='${1:ipaddress}'){",
"\t//run only my ip",
"\t$0",
"}"
],
"description": "Test only from IP address"
}
}
outputs :
// Debugging
if(_SERVER["REMOTE_ADDR"]=='xxx.xxx.xxx.xxx'){
//run only my ip
}
You can't use \ you have to use double $ ..
eg.
// Debugging
if($$_SERVER["REMOTE_ADDR"]=='xxx.xxx.xxx.xxx'){
//run only my ip
}

How to configure the APNS.Certificate in the arm template

I am using the following azuredeploy.json file for setting up the notification hub on the Azure cloud.
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"Gcm.GoogleApiKey": {
"type": "string",
"metadata": {
"description": "Google Cloud Messaging API Key"
},
"defaultValue": "AIzaSyAyp9MernKgMS3wFNM3yNWByiP-TaGrqEg"
},
"APNS.Certificate": {
"type": "string",
"metadata": {
"description": "A certificate (in base 64 format) provided by Apple on the iOS Provisioning Portal"
},
"defaultValue": ""
},
"APNS.certificateKey": {
"type": "string",
"metadata": {
"description": "The Certificate Key provided by the iOS Provisioning Portal when registering the application"
},
"defaultValue": "ce469bf21dfa7b9d595d4999bfaca8a94ea47e46"
},
"APNS.endpoint": {
"type": "string",
"metadata": {
"description": "The APNS endpoint to which our service connects. This is one of two values: gateway.sandbox.push.apple.com for the sandbox endpoint or gateway.push.apple.com, for the production endpoint. Any other value is invalid."
},
"allowedValues": [
"gateway.sandbox.push.apple.com",
"gateway.push.apple.com"
],
"defaultValue": "gateway.push.apple.com"
}
},
"variables": {
"hubVersion": "[providers('Microsoft.NotificationHubs', 'namespaces').apiVersions[0]]",
"notificationHubNamespace": "[concat('hubv2', uniqueString(resourceGroup().id))]",
"notificationHubName": "notificationhub"
},
"resources": [
{
"name": "[variables('NotificationHubNamespace')]",
"location": "[resourceGroup().location]",
"type": "Microsoft.NotificationHubs/namespaces",
"apiVersion": "[variables('hubVersion')]",
"comments": "Notification hub namespace",
"properties": {
"namespaceType": "NotificationHub"
},
"resources": [
{
"name": "[concat(variables('NotificationHubNamespace'),'/',variables('NotificationHubName'))]",
"location": "[resourceGroup().location]",
"type": "Microsoft.NotificationHubs/namespaces/notificationHubs",
"apiVersion": "[variables('hubVersion')]",
"properties": {
"GcmCredential": {
"properties": {
"googleApiKey": "[parameters('Gcm.GoogleApiKey')]",
"gcmEndpoint": "https://android.googleapis.com/gcm/send"
}
}
},
"dependsOn": [
"[variables('NotificationHubNamespace')]"
]
}
]
}
],
"outputs": {
}
}
Now I tried to set up the apple push notification service also using the following snippet:
"apnsCredential": {
"properties": {
"apnsCertificate": "[parameters('APNS.Certificate')]",
"certificateKey": "[parameters('APNS.certificateKey')]",
"endpoint": " gateway.sandbox.push.apple.com or gateway.push.apple.com",
}
}
With the above changes, I executed the Deploy-AzureResourceGroup.ps1 using powershell command prompt and on executing it I am getting an error with message 'Bad Request'
Can anyone help me to fix this issue.
Add the proper APNS.Certificate and APNS.certificateKey.
It is failing on trying to verify your details, hence the bad request.
You need a base 64 formatted APNS.Certificate.
APNS.Certificate:
This is the Apple Push Notification certificate in base 64 string-format.
You can use PowerShell to convert the certificate like this (then copie the key from the output file ‘MyPushCert.txt’ and use it.):
$fileContentBytes = get-content ‘Apple_Certificate.p12’ -Encoding Byte
[System.Convert]::ToBase64String($fileContentBytes) | Out-File ‘MyPushCert.txt’
APNS.certificateKey:
This is the password you specified when you exported the certificate.(The password you created on Apple at the time of creating the cert.)
It's impossible to know exactly what caused this without knowing more about your environment/setup. According to this post, one possible issue could be how strong your password is:
After a few hours of pulling my hair out and not getting anything
beyond “Bad Request”, I finally thought to use a password stronger
than “pass#word1”. I’ll be darned, it worked. Not only that, but
provisioning with Azure Resource Manager is asynchronous, so your
scripts finish a heck of a lot sooner than they used to because VMs
provision in parallel.
The post recommends going through Troubleshooting common Azure deployment errors with Azure Resource Manager.
I'm not sure you should be dynamically setting the apiVersion for your templates. They vary depending on what you are deploying.
See Best Practices:
Avoid using a parameter or variable for the API version for a resource type. Resource properties and values can vary by version number. IntelliSense in a code editor cannot determine the correct schema when the API version is set to a parameter or variable. Instead, hard-code the API version in the template.
The correct apiVersion for notification hubs appears to be 2015-04-01: https://github.com/Azure/azure-resource-manager-schemas/blob/master/schemas/2015-04-01/Microsoft.NotificationHubs.json
I had to use PowerShell to resolve this problem.
Partially the idea was taken from here: https://learn.microsoft.com/en-us/azure/notification-hubs/notification-hubs-deploy-and-manage-powershell
Below is the script, which tested locally and is working.
Microsoft.Azure.NotificationHubs -Version 1.0.9 used.
We adopted it for VSTS Release as one of the PowerShell tasks/steps after Notification Hub has been created with ARM template.
Login-AzureRmAccount
Select-AzureRmSubscription -SubscriptionName my-subscription-here
Write-Host "Begin process..."
try
{
# Make sure to reference the latest version of Microsoft.Azure.NotificationHubs.dll
Write-Host "Adding the [Microsoft.Azure.NotificationHubs.dll] assembly to the script...";
$scriptPath = Split-Path (Get-Variable MyInvocation -Scope 0).Value.MyCommand.Path;
$packagesFolder = $scriptPath + "\packs";
Write-Host $packagesFolder;
$assembly = Get-ChildItem $packagesFolder -Include "Microsoft.Azure.NotificationHubs.dll" -Recurse;
write-Host $assembly.FullName;
Add-Type -Path $assembly.FullName;
Write-Host "The [Microsoft.Azure.NotificationHubs.dll] assembly has been successfully added to the script.";
# Create requered variables
$HubNamespace = "hub-namespace";
$HubName = "hub-name";
$ResourceGroup = "resource-group";
$GcmApiKey = "api key here";
# Possible values: gateway.push.apple.com, gateway.sandbox.push.apple.com
$ApnsEndpoint = "gateway.push.apple.com";
# A certificate (in base 64 format) provided by Apple on the iOS Provisioning Portal
$ApnsCertificate = "base 64 certificate here";
$ApnsCertificateKey = "certificate key/password here";
$GcmCredential = New-Object -TypeName Microsoft.Azure.NotificationHubs.GcmCredential -ArgumentList $GcmApiKey;
$ApnsCredential = New-Object -TypeName Microsoft.Azure.NotificationHubs.ApnsCredential;
$ApnsCredential.Endpoint = $ApnsEndpoint;
$ApnsCredential.ApnsCertificate = $ApnsCertificate;
$ApnsCredential.CertificateKey = $ApnsCertificateKey;
# Query the namespace
$FoundNamespaces = Get-AzureRmNotificationHubsNamespace -Namespace $HubNamespace -ResourceGroup $ResourceGroup
# Check if the namespace already exists
if ($FoundNamespaces -and $FoundNamespaces.Length -eq 1)
{
$CurrentNamespace = $FoundNamespaces[0];
Write-Host "The namespace [$HubNamespace] in the [$($CurrentNamespace.Location)] region was found.";
$HubListKeys = Get-AzureRmNotificationHubListKeys -Namespace $HubNamespace -ResourceGroup $ResourceGroup -NotificationHub $HubName -AuthorizationRule DefaultFullSharedAccessSignature;
# Check to see if the Notification Hub exists
if ($HubListKeys)
{
# Create the NamespaceManager object used to update the notification hub
Write-Host "Creating a NamespaceManager object for the [$HubNamespace] namespace...";
$NamespaceManager = [Microsoft.Azure.NotificationHubs.NamespaceManager]::CreateFromConnectionString($HubListKeys.PrimaryConnectionString);
Write-Host "NamespaceManager object for the [$HubNamespace] namespace has been successfully created.";
# Update notification hub with new details
Write-Host "The [$Path] notification hub already exists in the [$HubNamespace] namespace." ;
$NHDescription = $NamespaceManager.GetNotificationHub($HubName);
$NHDescription.GcmCredential = $GcmCredential;
$NHDescription.ApnsCredential = $ApnsCredential;
$NHDescription = $NamespaceManager.UpdateNotificationHub($NHDescription);
Write-Host "The [$HubName] notification hub was updated";
}
else
{
Write-Host "The [$HubName] notification hub does not exist."
}
}
else
{
Write-Host "The [$HubNamespace] namespace does not exist."
}
}
catch [System.Exception]
{
Write-Error($_.Exception.Message)
}
Hope that helps someone.

Installing Slack Plugin to Sensu NON-enterprise edition

I have Sensu running and followed the instructions the best I could to install the Slack plugin. I'm attempting to just do a "hello-world" to get started, but the documentation seems lacking to me.
I followed the "getting started" with checks:
https://sensuapp.org/docs/0.20/getting-started-with-checks
and everything seems to be in the correct place on the server.
I am attempting to install the following community plugin, but they have a catch-all instruction for all community plugins. There is a json file in the plugin instructions, but doesn't say where to put it...
https://github.com/sensu-plugins/sensu-plugins-slack
Here is what my check_cron.json looks like ( I tried 2 methods, 1 from another source other than Sensu):
{
"checks": {
"cron_checks": {
"handlers": ["default", "slack"],
"command": "/etc/sensu/plugins/check-procs.rb -p cron -C 1 ",
"interval": 60, "subscribers": ["webservers"]
},
"cron": {
"handlers": ["default", "slack"],
"command": "/etc/sensu/plugins/check-procs.rb -p cron",
"subscribers": [
"production",
"webservers",
],
"interval": 60
}
}
}
I have restarted my server after making the changes. I'm assuming that this cron will hit every minute and call the slack notification plugin, but don't know what I'm missing, or where to put the .json doc from the Slack plugin "documentation"
https://github.com/sensu-plugins/sensu-plugins-slack
Any help getting me to the right direction?
You need a handler on the Sensu Server that will fire the request to Slack. Have you created that? If yes, please post it's content.
So I just solved this. benishkey did provide the solution in the link, however, just in case anyone comes across this and the link is broken, I thought I would add the solution.
-github user eugene-chow:
The Slack handler's config need to be named differently. Try the JSON below. I renamed the Slack config for each environment, and then pointed the handler to the respective config with -j config_name
{
"handlers": {
"slack-staging": {
"type": "pipe",
"command": "/usr/local/bin/handler-slack.rb -j slack-staging",
"severites": ["critical", "unknown"]
}
},
"slack-staging": {
"webhook_url": "https://hooks.slack.com/services/...",
"template" : ""
}
}
{
"handlers": {
"slack-production": {
"type": "pipe",
"command": "/usr/local/bin/handler-slack.rb -j slack-production",
"severites": ["critical", "unknown"]
}
},
"slack-production": {
"webhook_url": "https://hooks.slack.com/services/...",
"template" : ""
}
}
I dropped the handler-slack.rb file in with my checks and referenced it from there because it wasn't in my /usr/local/bin/ folder
I was facing the same issue, so the answer is already given but maybe help someone in the future,
First, install sensu slack plugin
/opt/sensu/embedded/bin/gem install sensu-plugins-slack
Then, Create a handler config file
vim /etc/sensu/conf.d/slack-handler.json
handler-slack.rb https://github.com/sensu-plugins/sensu-plugins-slack/blob/master/bin/handler-slack.rb
{
"handlers": {
"slack": {
"type": "pipe",
"command": "/opt/sensu/embedded/bin/handler-slack.rb",
"severites": ["critical", "unknown"]
}
},
"slack": {
"webhook_url": "https://your_webhook.com/abc",
"template" : ""
}
}
I found the answer in the "issues" section in Git
https://github.com/sensu-plugins/sensu-plugins-slack/issues/7

wget command line - define format and encoding

trying to download all categories from an ecommerce website using rest and wget (curl either) I cannot make a readable file. the following line is the one that Im executing:
...>wget https://api.mercadolibre.com/sites/MLB/categories/all --no-check-certificate
I receive information like this->
½Û’Û8².ü*_[6q Hö]>t{\=¶ÇëðÇŽˆ¢ªè–ÄÜmïXûÖôeÇŽ¹˜˜»û®^ìHU €()‰dåŠ1]ì®,$&
I expected something like:
, {
"id": "MLA1743",
"name": "Autos, Motos y Otros"
}, {
"id": "MLA1384",
"name": "Bebés"
}, {
"id": "MLA1039",
"name": "Cámaras y Accesorios"
}, {
"id": "MLA1051",
"name": "Celulares y Teléfonos"
}, {
"id": "MLA1798",
"name": "Coleccionables y Hobbies"
}
sorry if its a newbie question but i cannot find a proper tutorial. brgds
The content is gzip-encoded. You can figure this out by looking at the Content-Encoding header the servers sends with the response. You can access the data like this:
wget -o- https://api.mercadolibre.com/sites/MLB/categories/all | zcat
Or just save it to a file first:
wget -o all.gz https://api.mercadolibre.com/sites/MLB/categories/all
gunzip all.gz