Why Jenkins requires login password for sonar 6.2? - jenkins

Using pipeline code,
withSonarQubeEnv {
dir ('/mydirectory/') {
sh "'${mvnHome}/bin/mvn' org.sonarsource.scanner.maven:sonar-maven-plugin:3.2:sonar -Dsonar.projectKey=somemykey -Dsonar.projectName=somemyname"
}
Which outputs:
Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.2:sonar (default-cli) on project myproject: Not authorized. Please check the properties sonar.login and sonar.password.
If that is expected behavior then how to avoid pasting login and password? If not what is the root cause of it? Is it a problem with Sonar server configuration?

At the global level you should configure your server instance to include an analysis token from a user with Global Execute Analysis permissions. Either that, or include a project-specific user token at the analysis level.
The error message asking for login/password is a bit outmoded. You can still use login/password, but analysis token is the recommended way.

Related

How can I install a plugin using jenkinsfile?

Problem Statement
I am using Jenkins for CI/CD automation. I installed the GitHub Pull Request Builder through Jenkin's Plugin Manager.
However I cannot figure out how to do this with a Jenkins Pipeline
Attempts/Documentation
I have skimmed through this exhaustive list of pipeline steps and declarative documentation but cannot find any documentation on how to accomplish this?
Installing Plugin via Jenkinsfile
Firstly, I would question why exactly you want to do this. This is a fairly odd requirement that I have not seen in my 10 years of Jenkins & Hudson experience. With that said, anything that can be done in the Jenkins web interface, and a billion other things that cannot, can be done in either a Pipeline or in the Script Console because these two constructs have access to the entire SDK.
node {
// 'ghprb' is this plugins short name value
GITHUB_PULL_REQUEST_BUILDER = 'ghprb'
for (plugin in [GITHUB_PULL_REQUEST_BUILDER]) {
e = Hudson.instance.updateCenter.getPlugin(plugin).deploy().get().getError()
if (e != null)
println e.message
}
}
Security
Anything you see on the Jenkins GUI can be done in the script console or a pipeline via the Jenkins SDK. Jenkins has implemented a Sandbox to prevent nefarious actors from executing malicious scripts. Your requirement must use the Jenkins/Hudson SDK and therefore you have two options:
Disable the Sandbox for this pipeline
Authorize the scripts and/or methods being used
If you try and run the aforementioned script without solving these security constraints the following exception will be thrown:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method jenkins.model.Jenkins getUpdateCenter
Sandbox
To disable the Sandbox simply uncheck the "Use Groovy Sandbox" checkbox. This is the easiest solution.
Script Approval
If your administrator does not authorize you to outright disable the Sandbox for that job then you can approve the method signatures used in your script or approve the script itself.
The following message signatures would need to be approved for this script
staticMethod hudson.model.Hudson getInstance
method jenkins.model.Jenkins getUpdateCenter
method hudson.model.UpdateSite$Plugin deploy
method java.util.concurrent.Future get
method hudson.model.UpdateCenter$UpdateCenterJob getError
Additional Information
Most likely the plugin will not be available until a restart has occurred. You can automate a restart a variety of ways. You can hit the following endpoints
http://<jenkins.server>/restart
http://<jenkins.server>/safeRestart
You could invoke the jenkins-cli.jar tool. If you're feeling exceptionally risky you could even do something like Jenkins.instance.restart()
Note: don't use the SDK to restart unless you really know what you're doing

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.

Accessing a Username with Password Credential Parameter from a Jenkins Execute Groovy build step using Groovy command?

Software levels:
Jenkins 2.121.2
Credentials Plugin 2.1.18
Credentials Binding Plugin 1.16
Plain Credentials Plugin 1.4
I am working with a Freestyle project (not a pipeline) and want to use a Groovy command build step for the job's main processing.
I am trying to obtain the userid and password from a user credential so the groovy script can use them for various CLI manipulations. I spent a lot of time searching for answers, but none of the ones I've found worked. Most were not clear, many were geared toward pipelines.
I would greatly appreciate a little guidance at this point.
Here are the gory details.
I created a new parameterized Freestyle project in which I added a Credentials Parameter for a "Username and password" credential. It defaults to one of the credentials that I defined to Jenkins via the Credentials Plugin. I'm not sure this is necessary if the binding selects the credential to use explicitly.
I checked "Use secret text(s) or file(s)" in the Build Environment section, although I'm not certain that is essential for a Username/password style binding.
I added a "Username and password (separated)" binding and set USERID and PASSWORD as the respective variables.
My groovy command window has this sole line:
println("${USERID} ${PASSWORD}")
When I build the job, I get this error:
The both ways will inject the credential into Environment Variable, thus you can access them from Environment Variable in Groovy Script as following for both ways.
def env = System.getenv()
println env['auth']
println env['USERNAME']
println env['PASSSWORD']
But the injected value of the both ways are different.
1) Adding a Credential job parameter for user to choose when run job
In this way, the credentialId is injected, so you not get the username and password.
credentialId example: 1dd4755a-9396-4819-9327-86f25650c7d7
2) Using Credential Bindings
In this way, the username and password are injected, I think this is what you wanted.
def env = System.getenv()
def username = env['USERNAME']
def password = env['PASSSWORD']
def cmd = "curl -u $username:$password ...."
Add a Jenkins Build Step supply by plugin Execute Groovy script
To summarize, the techniques identified by #yong's post will only work with System Groovy Script build steps. The latest plugin and Jenkins levels will obfuscate the credential parameters, so println cannot be used to verify their content by visual inspection.

Unable to execute sonar job from jenkins 403

I am unable to do code analysis from jenkins,I am getting 403 error.The Execute Analysis permission is provided for all the sonar users,sonar administrator and project creators,but still iam getting 403.
In jenkins job i have used goal sonar:sonar
Am i missing anything in the configuration?
Error :
[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.4.0.905:sonar (default-cli) on project core: Unable to load component class org.sonar.api.config.Settings: Unable to load component class org.sonar.scanner.repository.ProjectRepositories: You're only authorized to execute a local (preview) SonarQube analysis without pushing the results to the SonarQube server. Please contact your SonarQube administrator. -> [Help 1]
Unless you've granted permissions to Anyone to perform analysis, then you will continue to have this failure because you're not providing credentials. Instead:
mvn sonar:sonar -Dsonar.login=analysis_token_here
Where the value of the login parameter is a User Token

How to configure Jenkins to report major errors to the administrator?

e.g. I have the following errors in jenkins.err.log. How can I make Jenkins email this type of errors to me?
caused by: com.microsoft.tfs.core.ws.runtime.exceptions.UnauthorizedException: Authorization failure connecting to 'http://vstsprodapp:8080/Services/v1.0/Registration.asmx' (authenticating as domain\user)
This isn't a feature that's built into Jenkins.
You could use whatever system you use for monitoring your servers, and check the logs on the Jenkins server for error messages.
There is also an idea suggested on the Jenkins wiki, which allows you to use a Groovy hook script to add a further Java logging handler to Jenkins. But again, even if you do this, you would still have to implement a custom solution to send notifications based on the log's contents.
From https://wiki.jenkins-ci.org/display/JENKINS/Logging:
Put the following Groovy script into a file called $JENKINS_HOME/init.groovy.d/extra_logging.groovy:
import java.util.logging.ConsoleHandler
import java.util.logging.LogManager
def logger = LogManager.getLogManager().getLogger("hudson.WebAppMain")
logger.addHandler (new ConsoleHandler())
This will just copy all log records generated by Jenkins and any plugins to the console.

Resources