We want to send information to the channel in Mattermost, but I get this error in the script.
#!/bin/bash
#start
matterSend() {
# Lowercase variable names; declare them local
local endpoint=https://mattermost.ltd/hooks/hash..
local username=$USER
# Pro tip: don't use a variable for the payload if it's effectively static
payload=$(cat <<-__EOF
payload={
"username" : "$username",
"channel" : "Genel_Log",
"text" : "#### ---\\n| Yedekeleme | Drive Gönderim | İşlem *** |\\n|:-----------|:-----------:|-----------------------------------------------:|\\n| ${2} | ${3} | ${1} :white_check_mark: |\\n"
}
__EOF
)
echo "CURL: curl -i -X POST -d $payload $endpoint"
curl -i -X POST -d "$payload" "$endpoint"
}
STRING="Starting.."
matterSend
Result:
fileName.sh: 5: local: not in a function
What is the reason?
Related
I am looking to fetch the subfolders and files inside jfrog artifactory repo and for that I am running the below script which I am running in Groovy
def test = sh(script: "curl -u uname:password -X POST -k https://artifactory.xxxx.com/artifactory/api/search/aql -d 'items.find({\"type\" : \"file\",\"\$or\":[{\"repo\" : {\"\$match\" : \"war*\"}, \"repo\" : {\"\$match\" : \"web*\"} }]}).include(\"name\",\"repo\",\"path\",\"size\").sort({\"\$desc\": [\"size\"]}).limit(10)'", returnStdout: true).trim()
echo "The list is ${test}"
But its not returning any value.
Any solution would be helpful.
Thanks
You can use api/storage get the children of a artifact path.
For example, your Artifactory has repository: maven-prerelease-local for maven, you can open
https://artifactory.xxxx.com/maven-prerelease-local in browser, it will list file and folders under it.
By adding api/storage in URL, it will return a JSON response.
def test = sh(script: """
curl -u uname:password -X GET -k \
"https://artifactory.xxxx.com/api/storage/maven-prerelease-local/com/xxx/xxx/"
""", returnStdout: true).trim()
echo "The list is ${test}"
To get detailed information about the existing subfolders under a specific directory/repository, you can use the following format of execution.
$ jfrog rt search --spec=test.aql
[Info] Searching artifacts...
[Info] Found 1 artifact.
[
{
"path": "delta-generic-local/alpha/beta",
"type": "folder",
"created": "2022-08-04T13:53:36.173Z",
"modified": "2022-08-04T13:53:36.173Z"
}
]
& the spec file includes the following content.
$ cat test.aql
{
"files":
[
{
"aql":
{
"items.find" :
{
"type":"folder",
"repo":{"$eq":"delta-generic-local"},
"path":{"$eq":"alpha"}
}
}
}
]
}
I am guessing you are in escape special character hell. Put your query in a *.aql file and then point to it. See below.
// Create the aql file and write the query to it
writeFile file: 'sizeQuery.aql', text: 'items.find({"type":"file"}).sort({"$desc":["size"]}).limit(10)'
// Pass the aql file to your curl command
sh 'curl -u uname:password -H "Content-Type: text/plain" -X POST -d #sizeQuery.aql "https://artifactory.xxxx.com/artifactory/api/search/aql"'
I am running an API call to get my node status in the cluster. the output is in the below format. i am writing a shell script to post the status of each node that is in not ready state. However i am unable to design up logic for the same.
node1 ready
node2 disconnected
node3 ready
Below is my script. Please advice on the changes.
#!/bin/bash
auth_token=$(curl -sk -d '{"username":"","password":""}' https://url/auth/login | jq -r .auth_token)
echo $auth_token
status=$(curl -X GET "https://<url>/nodes" -H "accept: application/json" -H "Authorization: Bearer $auth_token" | jq -r '.[] | .Description.Hostname + " " + .Status.State')
STATUS=($status)
alenght=${#STATUS[#]}
for (( i=0; i<${alenght}; i++));
do
# echo ${org[i]}
if [ ${org[i]} != "ready" ]
then
$dd_status = 3
$hostname = <hostname with status not ready>
curl -X POST https://api.datadoghq.com/api/v1/check_run?api_key=${DD_CLIENT_API_KEY} \
-H "Content-Type: application/json" \
-d #- << EOF
{
"check": "check_name",
"host_name": "$host_name",
"status": "$dd_status",
"tags": [
"environment:test"
]
}
EOF
else
$dd_status = 0
$hostname = <hostname with status ready >
curl -X POST https://api.datadoghq.com/api/v1/check_run?api_key=${DD_CLIENT_API_KEY} \
-H "Content-Type: application/json" \
-d #- << EOF
{
"check": "check_name",
"host_name": "$host_name",
"status": "$dd_status",
"tags": [
"environment:test"
]
}
EOF
fi
done
Try this logic
while read -r name status; do
case $status in
ready) good_code;;
*) fail_code;;
esac
done < <(code_to_generate_log)
I would like to have a simple, non-interactive way to get a list of forks of a GitHub repo.
For me personally, it has to run on at least Linux.
Using GraphQL (GiHub API v4) from a bash script, using cURL:
#!/bin/bash
# Returns a list of all forks of a github repo.
# See the output of "$0 -h" for more details.
set -e
# initial default values
access_token=""
repo_owner=$USER
repo_name=$(basename $(pwd))
res_file=res.json
function print_help() {
echo "Returns a list of all forks of a github repo."
echo
echo "Usage:"
echo " `basename $0` [OPTIONS]"
echo "Options:"
echo " -h, --help Show this help message"
echo " -o, --owner <string> Name of the GitHub user or organization of the original repo"
echo " -r, --repo <string> Name of the GitHub original repo"
echo " -t, --token <string> GitHub personal access token, required for authentication"
echo " To get one, see: https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line"
}
# read command-line args
POSITIONAL=()
while [[ $# -gt 0 ]]
do
arg="$1"
shift
case "${arg}" in
-h|--help)
shift # past argument
print_help
exit 0
;;
-o|--owner)
repo_owner="$1"
shift # past argument
;;
-r|--repo)
repo_name="$1"
shift # past argument
;;
-t|--token)
access_token="$1"
shift # past argument
;;
*) # non-/unknown option
POSITIONAL+=("${arg}") # save it in an array for later
shift # past argument
;;
esac
done
set -- "${POSITIONAL[#]}" # restore positional parameters
if [ -z "$access_token" ]
then
>&2 echo "WARNING: Access token not specified, though it is required!"
print_help
exit 1
fi
curl \
'https://api.github.com/graphql' \
-H 'Accept-Encoding: gzip, deflate, br' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-H 'Connection: keep-alive' \
-H 'Origin: altair://-' \
-H "Authorization: Bearer $access_token" \
--data-binary '{"query":"query { repository(owner: \"'$repo_owner'\", name: \"'$repo_name'\") { forks(first:100) { edges { node { nameWithOwner } } } } }","variables":{}}' \
--compressed \
> "$res_file"
cat "$res_file" \
| sed -e 's/nameWithOwner/\nXXX/g' \
| grep XXX \
| awk -e 'BEGIN { FS="\""; } { print $3; }'
You need to create an access token.
Sample invocation of the above script:
git-hub-list-forks -o hoijui -r JavaOSC -t 1234567890abcdef1234567890abcdef
NOTE: GitHub limits the maximum amount of forks to fetch to 100 at a time
if you are interested in a js based solution you try GitHub rest API:
/repos/{owner}/{repo}/forks
fetch("https://api.github.com/repos/ONLYOFFICE/CommunityServer/forks?sort=stargazers")
.then(response => response.json())
.then(res=> {
let result = res.map(e=> {
return {
url: e.html_url,
watchers: e.watchers,
starts: e.stargazers_count,
updated_at:e.updated_at
};
});
console.log(result);
// or console.table(result);
});
When i am passing value of a variable declared in jenkins Groovy script its value is not retained in for loop which is running on a remote server. Strange thing is i am able to access the same value outside the for loop.
Here is the sample code i am trying to use
#!/usr/bin/env groovy
def config
def COMMANDS_TO_CHECK='curl grep hello awk tr mkdir bc'
pipeline {
agent {
label "master"
}
stages {
stage ('Validation of commands') {
steps {
script {
sh """
#!/bin/bash
/usr/bin/sshpass -p passwrd ssh user#host << EOF
hostname
echo $COMMANDS_TO_CHECK ---> This is printed
for CURRENT_COMMAND in \$COMMANDS_TO_CHECK
do
echo ${CURRENT_COMMAND} ---> Why This is not printed?
echo \${CURRENT_COMMAND} ----> Why This is not printed?
done
hostname
EOF
exit
"""
}
}
}
}
}
Output
[workspace#3] Running shell script
+ /usr/bin/sshpass -p passwrd ssh user#host
Pseudo-terminal will not be allocated because stdin is not a terminal.
illinsduck01
curl grep hello awk tr mkdir bc
illinsduck01
+ exit
You can wrap sh in """ ... """ as below
#!/usr/bin/env groovy
def config
pipeline {
agent {
label "master"
}
stages {
stage ('Validation of commands') {
steps {
script {
sh """#!/bin/sh
/usr/bin/sshpass -p password ssh username#hostname << EOF
COMMANDS_TO_CHECK="curl grep hello awk tr mkdir bc"
hostname
echo \$COMMANDS_TO_CHECK
for CURRENT_COMMAND in \$COMMANDS_TO_CHECK
do
echo \$CURRENT_COMMAND
which \$CURRENT_COMMAND
status=\$?
if [ \${status} -eq 0 ]
then
echo \${CURRENT_COMMAND} command is OK
else
echo "Failed to find the \${CURRENT_COMMAND} command"
fi
done
hostname
EOF
exit
"""
}
}
}
}
}
I've written a bash script that sends a POST request to a server. The request contains a certificate signing request and the server signs it and returns a certificate.
When I copy and paste the CSR text in the POST's body, then the POST request is successful. But when I read the CSR from a variable, then the POST request fails. I've attached a snippet of the program below.
PROGRAM - Bash
openssl req -new -newkey rsa:2048 -nodes -out cert.csr -keyout priv.key -subj "/C=MyCountry/ST=MyState/L=MyCity/O=MyCompany/OU=MyDept/CN=MyComp"
if [ $? == 0 ]; then
csr=$(<cert.csr)
fi
response=$(curl -o - -s -w "%{http_code}\n" -X POST \
https://xxx.xxx.com/URI-END-POINT \
-H "authorization: $token" \
-H "content-type: application/json" \
-d '{
"digicert": {
"csr": "'$csr'",
"profileName": "pn123",
"signatureHash": "sh123",
"userPrincipalName": "pn123",
"validationScopeId": "vsi123"
},
"IccId": "sim123",
"MacAddress": "mac123"
}')
if [ $?==0 ]; then
status=$(echo $response | tail -c 4)
if [ "$status" == "$http_success" ]; then
echo -e "Request for certificate SUCCESS"
else
echo -e "Request for certificate FAILED with return code $status"
fi
else
echo -e "Request for certificate FAILED"
fi
OUTPUT - Bash
curl: option -----END: is unknown
curl: try 'curl --help' or 'curl --manual' for more information
In the above script, if I replace the line "csr": "'$csr'", with "csr": "----BEGIN CERTIFICATE REQUEST---- XXXXXXX ----END CERTIFICATE REQUEST----", then this will work fine.
Can you help me debug this?
Thanks!
Maybe the string in $csr is being evaluated, like if put in double quotes and the resulting string is something different than expected.
For start, try to see if $csr is same as "$csr".
To post the contents of a file, use jq to generate the JSON blob for you: this will take care of any necessary quoting automatically. The output of jq is pipe directly to curl by using the #- argument for the -d option. (A #-prefixed string indicates the name of a file curl should read from; - is the alias for standard input.)
response=$(jq -n --arg csr "$(<csr)" '{
digicert: {
csr: $csr,
profileName: "pn123",
signatureHash : "sh123",
userPrincipalName: "pn123",
validationScopeId: "vsi123"
},
IccId: "sim123",
MacAddress: "mac123"
}' |
curl -o - -s -w "%{http_code}\n" -X POST \
https://xxx.xxx.com/URI-END-POINT \
-H "authorization: $token" \
-H "content-type: application/json" \
-d #-
)