So I'm trying to pass in a string (data) into this sendSlackMessage function but it's not going into the curl command correctly. data is being passed in from my jenkinsfile.
It's working fine in the echo command though.
Can someone tell me what I'm doing wrong?
data = """{'channel': '#mychannel','username': 'jenkins-bot','icon_emoji': ':lol:','text': 'HERERERERE (<$BUILD_URL|Open>)','attachments': [['color': '#36a64f','fields': ['title': 'UPDATING INFOR','value': 'HELLOWORLD','short': 'true']]]}"""
void sendSlackMessage(String data) {
this.steps.sh(returnStdout: true, script: "echo hello world ${data} hello world again")
this.steps.sh(returnStdout: true, script: "curl -X POST -H 'Content-type: application/json' --data '${data}' https://hooks.slack.com/services/T12345671/sdfsdfsdf/sdf7sdf7gsdf")
}
Please try the below implementation
data = """{'channel': '#mychannel','username': 'jenkins-bot','icon_emoji': ':lol:','text': 'HERERERERE (<$BUILD_URL|Open>)','attachments': [['color': '#36a64f','fields': ['title': 'UPDATING INFOR','value': 'HELLOWORLD','short': 'true']]]}"""
void sendSlackMessage(String data) {
List curlCommand = []
curlCommand.add('curl -X POST -H')
curlCommand.add('\'Content-type: application/json\'')
curlCommand.add('--data')
curlCommand.add(data) // Maybe you have to see if you see to add a single quote here and escape it
curlCommand.add('https://hooks.slack.com/services/T12345671')
sh (
returnStdout: true,
script: curlCommand.join(" "),
label: "send slack message"
)
}
Related
I have a Jenkins decalarative pipeline where I am calling some URL via cURL which is returning JSON response. How to catch that JSON in a variable?
Have tried the below code but it's returning entire thing with path and command along with the response
environment {
token = bat(returnStdout: true, script: 'curl https://anypoint.mulesoft.com/accounts/login -H "Content-Type: application/json" -d "{\\"username\\" : \\"user\\",\\"password\\" : \\"pwd\\"}"').trim()
}
JSON response
C:\ProgramData\Jenkins\.jenkins\workspace\publish-api>curl https://anypoint.mulesoft.com/accounts/login -H "Content-Type: application/json" -d "{\"username\" : \"ap-1\",\"password\" : \"Ap5\"}"
{
"access_token": "axxxx-5ca2-48eb-9eb3-173c44a811",
"token_type": "bearer",
"redirectUrl": "/home/"
}
You can use the readJson method to get to your wished result. You don't necesseraly have to call it in your environment-block.
stage('Curl') {
steps {
script {
def cUrlResponse = bat(returnStdout: true, script: '#curl https://anypoint.mulesoft.com/accounts/login -H "Content-Type: application/json" -d "{\\"${env.username}\\" : \\"user\\",\\"${env.password}\\" : \\"pwd\\"}"').trim()
def responseJson = readJSON text: cUrlResponse
def accessToken = responseJson.access_token
def tokenType = responseJson.token_type
// do other stuff with the variables
}
}
}
To exclude the curl command from the output, add # in front of the script as stated in the documentation.
Writing my first function here for Groovy native lib and running into an issue. A method to get Github Labels for pull-requests. #param github_token String token with permission to access and read PR information.
getLabelsPerPullRequest.groovy: 19: expecting '}', found ':' # line 19, column 28. 'Authorization': 'token '+ github_token, ^
Here is my function
import groovy.json.JsonSlurper
def getLabelsPerPullRequest(String github_token) {
def labels
def scmHead = jenkins.scm.api.SCMHead.HeadByItem.findHead(currentBuild.rawBuild.getParent())
def repo = scmHead.getSourceRepo()
def prId = scmHead.getId()
if(github_token && github_token != null) {
// Set the call headers with Oauth token.
def headers = "{'Authorization': 'token '+ ${github_token},'Accept': 'application/vnd.github.v3+json'}"
// Construct request number URL in Github
def pr_url = "https://github.optum.com/api/v3/repos/SOP-Bot/${repo}/pulls/${prNbr}"
def json = sh(
script: "curl -X Get ${pr_url} -H ${headers}",
returnStdout: true
)
def prInfo = JsonOutput.toJson(text: json)
labels = prInfo.labels
}
return labels
}
Each header needs to be a separate -H argument. You can do something like this. I added -s to curl because you probably don't want the extra progress output but it may not actually be an issue.
def headers = [
"-H 'Authorization: token ${gitub_token}'",
"-H 'Accept: application/vnd.github.v3+json'"
]
...
def json = sh(
script: "curl -s -X GET ${headers.join(' ')} '${pr_url}'",
returnStdout: true
)
I'm trying to create a Webhook according to the documentation page:
https://www.twilio.com/docs/authy/api/webhooks
My curl call looks like this:
curl -X POST "https://api.authy.com/dashboard/json/application/webhooks" \
-d name="gridzdev_test" \
-d app_api_key="7N0..." \
-d access_key="4za..." \
-d url="https://some-random-string.ngrok.io/api/2fa/webhook" \
-d events="user_added" \
-H "X-Authy-Signature-Nonce: FiNwPdKZci4l3LEn" \
-H "X-Authy-Signature: feYEERfOSoWCB3ml5cnZFWs5xhc1sPeiWguhlJnokKQ="
Unfortunately, the response I receive is not what I expect:
{"message":"Invalid signature.","success":false,"error_code":"60000"}
The PHP code I'm using to generate signature:
public function handle() {
$url = 'https://api.authy.com/dashboard/json/application/webhooks';
$http_method = 'POST';
$params = 'id=53';
$nonce = 'FiNwPdKZci4l3LEn';
$signing_key = 'pr...';
$data = $nonce . '|' . $http_method . '|' . $url . '|' . $params;
$digest = hash_hmac('sha256', $data, $signing_key, true); // TODO tried with binary = false, but no joy
$digest_in_base64 = base64_encode($digest);
$this->info("nonce = $nonce");
$this->info("signature = $digest_in_base64");
}
I'm developing an iOS application.
Little bit confused about implementing the login module which the (Username/Password, Register and Forgot Password).
New to Couchbase. Used the Couchbase Enterprise Editon "http://192.168.1.126:8091/ui/index.html#/overview" Set up the Couchbase Lite in Xcode and I dunno what's the next step. Does anyone knows?
Data Modeling: Documents JSON
User ("Set as the EMAIL ID")
{
_id:” ",
username::" ",
password::" ",
email::" ",
type:"user"
}
User Info ("Set as the EMAIL ID")
{
_id:” ",
description:" ",
fb_URL::" ",
Twitter::" ",
Gender::" ",
Age::"[min:, max:]",
type:"user"
}
Users can be created in the Sync Gateway configuration file like so:
{
"databases": {
"app": {
"bucket": "walrus",
"users": {
"john": {"password": "pass"}
}
}
}
}
Then, authentication in the iOS app is enabled for this user:
let manager = CBLManager.sharedInstance()
let database = try! manager.databaseNamed("app")
let url = NSURL(string: "http://localhost:4984/app")!
let push = database.createPushReplication(url)
let pull = database.createPullReplication(url)
push.authenticator = CBLAuthenticator.basicAuthenticatorWithName("john", password: "pass")
pull.authenticator = CBLAuthenticator.basicAuthenticatorWithName("john", password: "pass")
push.start()
pull.start()
For user registration, you'll need to set up an App Server to register users on the Sync Gateway Admin port (4985 by default). To register a user:
$ curl -vX POST -H 'Content-Type: application/json' \
-d '{"name": "user2", "password": "pass"}' \
:4985/app/_user/
For the forgotten password functionality, the App Server should update the user record with the new password:
$ curl -vX PUT -H 'Content-Type: application/json' \
-d '{"name": "user2", "password": "newpass"}' \
:4985/app/_user/user2
I am trying to use the Dropbox API to upload a file. Here is the documentation from Dropbox:
curl -X POST https://content.dropboxapi.com/2/files/upload \
--header "Authorization: Bearer <get access token>" \
--header "Dropbox-API-Arg: {\"path\": \"/Homework/math/Matrices.txt\",\"mode\": \"add\",\"autorename\": true,\"mute\": false}" \
--header "Content-Type: application/octet-stream" \
--data-binary #local_file.txt
I have this in my Appcelerator project:
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function(e) {
//My function
};
xhr.open('POST','https://content.dropboxapi.com/2/files/upload');
xhr.setRequestHeader('Authorization', 'My Key');
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Dropbox-API-Arg', '{"path":"/my_path/file.txt","mode":{".tag":"add"}}');
But I can't figure out how to send the data-binary argument. With my current code I can create a file in my Dropbox folder, but is just an empty file.
From http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Network.HTTPClient, it looks like you just pass it into xhr.send(). You can pass a string, an object (which gets form-encoded), or a Titanium.Blob.
(Disclaimer: I've never used Appcelerator, so this is just what I surmise from reading the documentation.)
I figure out a way to do that. In my case I just need to upload a simple data structure, so I am using a JSON object:
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function(e) {
//My function
};
xhr.open('POST','https://content.dropboxapi.com/2/files/upload');
xhr.setRequestHeader('Authorization', 'My Key');
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Dropbox-API-Arg', '{"path":"/my_path/file.txt","mode":{".tag":"add"}}');
var my_json = {
"item1" : "content1"
};
xhr.send(JSON.stringify(my_json));
I still can't send a BLOB (like a picture from the phone gallery), but it works if you pass the path of the file:
var my_path = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory,'my_folder');
var newFile = Titanium.Filesystem.getFile(my_path.nativePath,'file.txt');
newFile.createFile();
newFile.write('Content of my text file');
var params = {"data-binary" : newFile};
xhr.send(params);