How to configure new BitBucket webhook for Jenkins - jenkins

Since BitBucket 5.4 it's not necessary anymore to install some plugin to enable webhooks to jenkins (push to bitbucket -> trigger jenkins build).
I'm now trying to configure this on our BitBucket 5.9.1.
I've clicked create webhook on my repo:
Name: test-webhook
URL: https://ourjenkins/
secret: MyToken
In my jenkins job I've configured: Trigger builds remotely (e.g., from scripts) and also added the same token: MyToken.
When I test the setup I got a 403:
Authentication required
<!--
You are authenticated as: anonymous
Groups that you are in:
Permission you need to have (but didn't): hudson.model.Hudson.Read
... which is implied by: hudson.security.Permission.GenericRead
... which is implied by: hudson.model.Hudson.Administer
-->
What am I missing to authenticate? I hoped the token would be used to authenticate but it seems not to work.

Go to Jenkins --> Manage Jenkins --> Configure Global Security
Select Project-based Matrix Authorization Strategy under Authorization
Set permission for Anonymous User to Read / Write Jenkins Jobs. Check for overall Read should work in your case. You can also try other options.

Related

Pass User-Scoped Credentials in Downstream Job in Jenkins is giving error

I am trying to pass user-scoped credentials to a downstream job in Jenkins in the declerative pipeline in order to be used from the downstream job for AWS Authentication. I have checked the option "Run as User who triggered the buid" in jenkins settings. When I trigger the Job it is working but when I try to trigger it from another job the it is giving me an error like "Error: " and after that is giving the credentials ID. Which means that the credentials are pass to the job but fore some reason the cannot be used.
I use the credentials like this: environment { creds = credentials("${AWSCredentials}") } in a stage of the declerative pipeline and it is failing right there. My goal is to make all the job to run with each user's personalized credentials and not to use Global credentials to Access and Modify AWS Resources through those jobs.

Why is a Jenkins script job failing to use proper AWS credentials?

I have a simple jenkins job that just runs aws ssm send-command and it fails with:
"An error occurred (AccessDeniedException) when calling the SendCommand operation: User: arn:aws:sts::1234567890:assumed-role/jenkins-live/i-1234567890abc is not authorized to perform: ssm:SendCommand on resource: arn:aws:ssm:us-east-1:1234567890:document/my-document-name"
However, the IAM permissions are correct. To prove it, I directly SSH onto that instance and run the exact same ssm command, and it works. I verify it's using the instance role by running aws sts get-caller-identity and it returns arn:aws:sts::1234567890:assumed-role/jenkins-live/i-1234567890abc which is the same user mentioned in the error message.
So indeed, this assumed role can run the command.
I even modified the jenkins job to run aws sts get-caller-identity first, and it outputs the same user json.
Does jenkins do some caching that I am unaware of? Why would I get that AccessDeniedException if that jenkins-live user can run the command otherwise?
First, install the AWS Credentials and AWS Steps plugins and register your AWS key and secret access key in Jenkins credential store. Then, the next steps depends if you're using a freestyle or a declarative/scripted pipeline.
If you're using a freestyle pipeline: On "Build Environment", click on "Use secret text(s) or file(s)" and follow the next steps. After that, you're gonna have your credentials as variables in your pipeline;
If you're using a declarative/scripted pipeline: Enclose your aws calls with a withAWS block, something like this:
withAWS(region: 'us-east-1', credentials: 'my-pretty-credentials') {
// let's explode something
}
Best regards.

Jenkins CSRF: how to use the Build Token Root Plugin to call the crumbIssuer ? (anonymous access)

Jenkins version: 2.121.1 .
Global security: LDAP + Matrix-based security . No access rights for Anonymous.
Since anonymous access is disabled, my script cannot get access to 'http://jenkins_host/crumbIssuer/api/json'. in order to get the CSRF token.
In https://issues.jenkins-ci.org/browse/JENKINS-45811, it is mentioned that the Build Token Root Plugin allows to workaround the access restriction for anonymous.
What I'm not sure is how to properly use this plugin in order to execute the crumbIssuer API? Because the plugin URL has a form such as 'buildByToken/build?job=RevolutionTest&token=TacoTuesday' , and it isn't clear to me how to execute '/crumbIssuer/api/json' with buildByToken.. (would I need to create a build job?)
Thanks!

How do I pass SSH keys from Jenkins Pipeline to Jenkins build jobs?

I'm working on a set of jobs to tag a bunch of related Git repos with the same tag. At the moment, the flow is decomposed into three types of jobs: an overall Jenkins scripted Pipeline, a job that does a build and drops a tag if the build succeeds, and a job triggered by the tagging job that does the final release build. My intention is to allow users to run either the overall pipeline or one of the jobs beneath it depending on if they need to re-run a step in the process or do an entire release.
One of my requirements is that this all needs to happen with the invoking user's credentials, which are then passed to Git so the updates (maven pom changes, etc.) are logged into the commit history as their user. I was successful in this by combining User-scoped credentials with the Authorize Project plugin (so the job can access the user-scoped credentials), the Build User Vars to set user.name and user.email in Git, and the SSH Agent plugin to supply the keys to Git so the commit and tag can be pushed as the correct user.
What I'm trying to do now is collect the user's SSH key with a credentials parameter to the scripted pipeline job and then pass that credentials parameter to the downstream tagging job (which also takes a credentials parameter). Unfortunately, when I do that the downstream job fails because the SSH Agent in the downstream job can't retrieve the credentials based on the value that the credentials parameter in the pipeline passes on to the credentials parameter in the tagging job.
The error I'm getting is:
FATAL:
java.io.IOException: [ssh-agent] Could not find specified credentials
at com.cloudbees.jenkins.plugins.sshagent.SSHAgentBuildWrapper.preCheckout(SSHAgentBuildWrapper.java:209)
at jenkins.scm.SCMCheckoutStrategy.preCheckout(SCMCheckoutStrategy.java:76)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:490)
at hudson.model.Run.execute(Run.java:1737)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:421)
FATAL: [ssh-agent] Could not find specified credentials
java.io.IOException: [ssh-agent] Could not find specified credentials
at com.cloudbees.jenkins.plugins.sshagent.SSHAgentBuildWrapper.preCheckout(SSHAgentBuildWrapper.java:209)
at jenkins.scm.SCMCheckoutStrategy.preCheckout(SCMCheckoutStrategy.java:76)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:490)
at hudson.model.Run.execute(Run.java:1737)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:421)
Right now, my Job DSL for the pipeline job looks like this:
parameters {
stringParam('sitePrefix',Projects.siteAbbr,"Three-character site code")
activeChoiceParam('modules'){
choiceType('MULTI_SELECT')
groovyScript{
script("[${projectsAsGroovyString}]")
}
description("Modules to build")
}
credentialsParam('gitUser'){
type('com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey')
required()
description('Personal SSH Key for tagging and releasing')
}
stringParam('gitBranch','develop','Branch to tag')
stringParam('releaseVersion',null,'Version you want to release')
stringParam('developmentVersion',null,'Snapshot version to set after release. If unset, generates a new patch snapshot based on the release version')
}
and my actual pipeline code contains code like this:
def tag_params = [
[$class:'com.cloudbees.plugins.credentials.CredentialsParameterValue',name: 'gitUser',value:params.gitUser],
// credentials(name:'gitUser',value:params.gitUser),
string(name:'gitBranch',value:params.gitBranch),
string(name:'releaseVersion',value:params.releaseVersion),
string(name:'developmentVersion',value:params.developmentVersion),
booleanParam(name:'buildRelease',value:false),
]
stage('Tag bom'){
// Run tag job
build job: "bom_tag_release", parameters: tag_params
// Run release build
build job: "bom_tag_build", parameters: build_params
}
The downstream job is just using another credentials parameter to receive the credentials, not the Credentials Binding plugin because that only seems to handle secret files not the SSH keys that SSH Agent needs. Is passing a credential id from a pipeline to a job even possible or should I be looking at another approach?
Thanks!

How to configure jenkins slack plugin?

I tried to configure jenkins slack plugin to send a notification to slack channel. But it doesn't work. I followed below instruction:
1. Get a Slack account: https://slack.com/
2. Configure the Jenkins integration: https://my.slack.com/services/new/jenkins-ci
3. Install this plugin on your Jenkins server.
4. Configure it in your Jenkins job (and optionally as global configuration) and add it as a Post-build action.
After I install jenkins on slack app there is a instruction about how to configure jenkins. But the configuration fields mentioned on the instruction is a little different than my jenkins configuration.
Below is the configuration screenshot from the instruction:
the configuration for my jenkins server looks like below:
how can I fill in the Base URL in my configuration? I have tried to fill in my jenkins url but it doesn't work. The test connection failed.
I get below error in jenkins system log:
Slack post may have failed. Response: <html><head><meta http-equiv='refresh' content='1;url=/login?from=%2FOPRc9G4zB2JX289VOnTvfeey'/><script>window.location.replace('/login?from=%2FOPRc9G4zB2JX289VOnTvfeey');</script></head><body style='background-color:white; color:white;'>
Authentication required
<!--
You are authenticated as: anonymous
Groups that you are in:
Permission you need to have (but didn't): hudson.model.Hudson.Read
... which is implied by: hudson.security.Permission.GenericRead
... which is implied by: hudson.model.Hudson.Administer
-->
I have tried to leave base url empty but still doesn't work
After a lot of testing, I figured out the problem. The issue relates to the configuration panel for slack. When I change the slack configuration and hit the test button, it doesn't take the current configuration, instead, it takes the previously saved configuration. I have to save the configuration first then test the connection.
Base URL doesn't need to be filled. Try from Specific Project. Only supply Team SubDomain in Global setting.
You have to provide these info separately for every project:
Team Domain/Sub-Domain
Integration Token(Taken from the Browse Apps > Jenkins CI)
Channel Name
For each Project that you would like receive notifications for, choose Configure from the project's menu in Jenkins.
You'll also need to add Slack Notifications to the Post-build Actions for this project.
Provide the Channel name, Team Subdomain and Integration Token there.
Test the connection.
you can directly run a POST build shell script per project basis or per slack channel
#!/bin/bash
curl -X POST --data-urlencode 'payload={"text": "'"$SLACK_MSG"'"}' $SLACK_WEB_HOOK_URL
where $SLACK_WEB_HOOK_URL and $SLACK_MSG can be exported as env variables or hardcode it for each project
Hay,
you have to add you integration Token to your Jenkins(I would recommend to add a Credential ID but its not necessary), that should sole your Problem. Keep in mind that your Jenkins just can send Messages to channels, the Account which generated the token has access to.
As said previously, you dont have to add a Team-Domain and your Subdomain has to be the following part of your Slack link:
www.EXAMPLE.slack.com
Hopefully i was able to help

Resources