Everytime when jenkins completes building an artifact I want it to upload an artifact to the slack channel. There are slack plugins available for jenkins pipeline that uploads file but its not always the case for everyone. What I have covered below is the alternative approach using curl
.
What you’ll need?
-
A slack channel.
-
A Slack app. Go here to create one.
-
Slack app’s OAuth Token.
-
On the same page you’ll find Scope section. In order to upload file, app will need
files:write
scope. -
Now, open your slack channel and ADD the slack app you just created.
- Open your
Jenkinsfile
and add the following function.def uploadFileToSlack() { def filePattern = "**/Release*.zip" // file that starts with Release and ends with .zip def file = findFiles(glob: "${filePattern}")[0] def botAuthToken = "xoxb-BOT_USER_AUTH_ACCESS_TOKEN" // see step #3 def channelName = "#YOUR-CHANNEL_NAME" // replace with the appropriate channel name. try { sh(script: """ curl --request POST \ --url https://slack.com/api/files.upload \ --header 'content-type: multipart/form-data' \ --form token=$botAuthToken \ --form 'channels=$channelName' \ --form 'title=${file.name}' \ --form file="@${file}" """ ) } catch (Exception e) { } }
Replace the value of
filePattern
with your desired glob pattern. - Lastly, there must be a stage in your
Jenkinsfile
where it creates an artifact. Call the above functionuploadFileToSlack()
from there.
Thats all. I hope you find this useful. Thanks!