Creating a job with credentials in jenkins only in command lines - jenkins

I am only allowed to work with the command line terminal on Ubuntu.
I need to create a job in Jenkins with security credentials.
I already installed Jenkins in my machine, but the access is open. If I set-up security credentials on Jenkins, how can I specify these on the command line?

Follow these steps:
Generate a public ssh-key in the user you want to work with from the command line:
ssh-keygen
Just press enter whenever yo are asked to enter some value.
Copy the content of the file ~/.ssh/id_rsa.pub.
Go to your jenkins home screen in a browser and login with a user with full access, Then click on the right on Users and then on the user you are currently logged with. Then click on settings (or configuration??).
In the field SSH public keys paste the content of the id_rsa.pub file. Save the changes.
And that's all! Now you are able to work with jenkins from the command line.
From the command line
The following is the configuration file of my jenkins main user (with all the privileges). Pay attention to the setting <authorizedKeys>. You should paste there the public ssh key. I haven't made that, but surely if you add the necessary lines to your config file it works. The file is in /path_to_jenkins/users/user_name/config.xml
<?xml version='1.0' encoding='UTF-8'?>
<user>
<fullName>admin</fullName>
<description></description>
<properties>
<jenkins.security.ApiTokenProperty>
<apiToken>pP08W9tzs2jlCrVCY9I2o6y2RNu3Huw85Y2f99/Uif7dia1W7piGpzsrpstln/jw</apiToken>
</jenkins.security.ApiTokenProperty>
<com.cloudbees.plugins.credentials.UserCredentialsProvider_-UserCredentialsProperty plugin="credentials#1.4">
<credentials/>
</com.cloudbees.plugins.credentials.UserCredentialsProvider_-UserCredentialsProperty>
<hudson.tasks.Mailer_-UserProperty plugin="mailer#1.4">
<emailAddress>admin#mail.com</emailAddress>
</hudson.tasks.Mailer_-UserProperty>
<hudson.model.MyViewsProperty>
<primaryViewName></primaryViewName>
<views>
<hudson.model.AllView>
<owner class="hudson.model.MyViewsProperty" reference="../../.."/>
<name>Alle</name>
<filterExecutors>false</filterExecutors>
<filterQueue>false</filterQueue>
<properties class="hudson.model.View$PropertyList"/>
</hudson.model.AllView>
</views>
</hudson.model.MyViewsProperty>
<hudson.security.HudsonPrivateSecurityRealm_-Details>
<passwordHash>1DF2ykjkkkjkkQXW</passwordHash>
</hudson.security.HudsonPrivateSecurityRealm_-Details>
<org.jenkinsci.main.modules.cli.auth.ssh.UserPropertyImpl>
<authorizedKeys>ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA4P1b/5RpibQgDZpKPD7lTQLjtyMrIQH43ns62PO72koL9zJe6qrAYcTIDNOUvSYNYyKfrgt6Z5zB8MvvENQLWezDKTWNXINhZml0PxOlc9ZaHbQX6UqyFbTS6o+ZEGs+K92Yi/XwK5hTmN5Igsw5BQYEs5cOsd5H2PoEZdhK1X0XAEBX/+p6aNy585+/scgZj0jSIvcX+pnzsCJLKmeYadlLnbrvebf9u6pu8MI9RuAY5dvPfpSL4WynWwS1QvY4z535TqPaaAlM3qXqH0pcOlxgW1iUkJqti3JnnxpBNXLmXalmq+4/d7mUrRBx+HKbh5ZpNZad9vaelAjAsNg+uw== user#machine_name</authorizedKeys>
</org.jenkinsci.main.modules.cli.auth.ssh.UserPropertyImpl>
<hudson.search.UserSearchProperty>
<insensitiveSearch>false</insensitiveSearch>
</hudson.search.UserSearchProperty>
</properties>
</user>

I just changed the starting prompt location to the folder in which the jar file is located. For example, if your jar file's location and name is:
C:\Users\Tod\file.jar
you can do two commands:
cd C:\Users\Tod
java -jar file.jar

Related

Jenkins Windows Slave setup using Winsw not working

Using this info https://hayato-iriumi.net/2019/05/23/how-to-install-jenkins-slave-as-windows-service/ we are setting up the Jenkins Slave on Windows server. Jenkins agent start from command line. but when we start from Windows service, its giving below error message? How to resolve this error message?
Service cannot be started. System.IO.InvalidDataException: Attribute <className> is missing in configuration XML
at winsw.Util.XmlHelper.SingleAttribute[TAttributeType](XmlElement node, String attributeName)
at winsw.Extensions.WinSWExtensionDescriptor.FromXml(XmlElement node)
at winsw.Extensions.WinSWExtensionManager.LoadExtension(String id)
at winsw.Extensions.WinSWExtensionManager.LoadExtensions()
at winsw.WrapperService.OnStart(String[] args)
at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)
xml file we have
<service>
<id>JenkinsSlave</id>
<name>Jenkins agent</name>
<description>This service runs an agent for Jenkins automation server.</description>
<executable>c:\java\jdk-11\bin\java.exe</executable>
<arguments>-Xrs -jar "c:\jenkins\slave.jar" -jnlpUrl https://jenkinsmaster/jenkins/computer/slave01/slave-agent.jnlp -secret a4b5b4ddfd34a016cd3a8eb94cbe8f908613e33a66db5fa6f5f43a080aea3116 -workDir=c:\jenkins</arguments>
<workingdirectory>c:\jenkins</workingdirectory>
<logmode>rotate</logmode>
<onfailure action="restart">
<download from="https://jenkinsmaster/jenkins/jnlpJars/slave.jar" to="c:\jenkins\slave.jar">
<extensions>
<extension enabled="false" classname="winsw.Plugins.RunawayProcessKiller.RunawayProcessKillerExtension" id="killOnStartup">
<pidfile>c:\jenkins\jenkins_agent.pid</pidfile>
<stoptimeout>5000</stoptimeout>
<stopparentfirst>false</stopparentfirst>
</extension>
</extensions>
</download>
</onfailure>
</service>
Thanks
There are some errors in the sample "Jenkins-Slave.xml" that is presented at the linked web page (which yours is apparently based on). It has all elements and attributes named in lowercase, but actually some of them should be mixed case (as can be seen by the error message that it doesn't find attribute className).
Try this one instead:
<service>
<id>YourJenkinsSlaveServiceId</id>
<name>Your Jenkins Slave Service Name</name>
<description>This service runs an agent for Jenkins automation server.</description>
<executable>C:\Program Files\Java\JRE8\bin\java.exe</executable>
<arguments>-Xrs -jar "%BASE%\slave.jar" -jnlpUrl http://YourJenkinsServer:8080/computer/YourNodeName/slave-agent.jnlp -secret YourSecretStringConsistingOfHexadecimalCharacters -workDir=C:\YourNodeWorkDir</arguments>
<logmode>rotate</logmode>
<onfailure action="restart" />
<download from="http://YourJenkinsServer:8080/jnlpJars/agent.jar" to="%BASE%\slave.jar"/>
<extensions>
<extension enabled="true" className="winsw.Plugins.RunawayProcessKiller.RunawayProcessKillerExtension" id="killOnStartup">
<pidfile>%BASE%\jenkins_agent.pid</pidfile>
<stopTimeout>5000</stopTimeout>
<stopParentFirst>false</stopParentFirst>
</extension>
</extensions>
</service>
This is from a more detailed explanation of how to install an agent as a Windows service which I have given in this answer.
I too has the same issue similarly..
System.IO.FileNotFoundException: Unable to locate jenkins.xml file within executable directory or any parents
at winsw.ServiceDescriptor..ctor()
at winsw.WrapperService.Run(String[] _args, ServiceDescriptor descriptor)
at winsw.WrapperService.Main(String[] args)
Solution:
Save your jenkins-agent file as xml format. not just jenkins-agent.xml
we can use notepad++ to save the xml type.
similarly remove .exe at end of jenkins-agent.exe
Hope its useful.... cheers !!
The className, stopTimeout and stopParentFirst should not be in lower case.

Jenkins - can't see "Manage Jenkins" option

I've just installed the latest version of Jenkins and enabled the so-called "Project-based Matrix Authorization Strategy".
I have added a few users with all privileges and some of them can see the "Manage Jenkins" option after logging into Jenkins, but there are people who can log in but can't see this option.
Really strange behavior. I have checked the configuration in jenkins.xml but it seems ok. Do you have any idea what can be an issue?
Thank you for any suggestions,
Foxrafi
Try using the link https://<JENKINS_URL>:8080/manage loaded the Manage Jenkins option on the UI.
OS: CentOS
Java Version: 1.8
It seems the permissions in config.xml are case-sensitive. So when there is such an entry :
<permission>hudson.model.Item.Build:mysuperuserlogin</permission>
and you log using LDAP authentication and this variant of password MySuperUserLogin, you will be able to log in successfully but you won't be able to use the permission.
Looks like your authorizationStrategy has been updated
Step 1: Go to your config.xml file and open this to any editor
sudo vim /var/lib/jenkins/config.xml
Step 2: Search authorizationStrategy tag inside xml file and change the value to
<authorizationStrategy class="hudson.security.FullControlOnceLoggedInAuthorizationStrategy">
Step 3: Restart Jenkins:
sudo systemctl restart jenkins
Try to log in now!
Here is the default xml file of Jenkins you can crosscheck your other configurations
<?xml version='1.1' encoding='UTF-8'?>
<hudson>
<disabledAdministrativeMonitors/>
<version>2.277.2</version>
<numExecutors>2</numExecutors>
<mode>NORMAL</mode>
<useSecurity>true</useSecurity>
<authorizationStrategy class="hudson.security.FullControlOnceLoggedInAuthorizationStrategy">
<denyAnonymousReadAccess>false</denyAnonymousReadAccess>
</authorizationStrategy>
<securityRealm class="hudson.security.HudsonPrivateSecurityRealm">
<disableSignup>true</disableSignup>
<enableCaptcha>false</enableCaptcha>
</securityRealm>
<disableRememberMe>false</disableRememberMe>
<projectNamingStrategy class="jenkins.model.ProjectNamingStrategy$DefaultProjectNamingStrategy"/>
<workspaceDir>${JENKINS_HOME}/workspace/${ITEM_FULL_NAME}</workspaceDir>
<buildsDir>${ITEM_ROOTDIR}/builds</buildsDir>
<markupFormatter class="hudson.markup.EscapedMarkupFormatter"/>
<jdks/>
<viewsTabBar class="hudson.views.DefaultViewsTabBar"/>
<myViewsTabBar class="hudson.views.DefaultMyViewsTabBar"/>
<clouds/>
<scmCheckoutRetryCount>0</scmCheckoutRetryCount>
<views>
<hudson.model.AllView>
<owner class="hudson" reference="../../.."/>
<name>all</name>
<filterExecutors>false</filterExecutors>
<filterQueue>false</filterQueue>
<properties class="hudson.model.View$PropertyList"/>
</hudson.model.AllView>
</views>
<primaryView>all</primaryView>
<slaveAgentPort>-1</slaveAgentPort>
<label></label>
<crumbIssuer class="hudson.security.csrf.DefaultCrumbIssuer">
<excludeClientIPFromCrumb>false</excludeClientIPFromCrumb>
</crumbIssuer>
<nodeProperties/>
<globalNodeProperties/>
</hudson>

Create Job Dynamically in Jenkins

I have a job in jenkins with a configuration, then, with the jenkins API in /cli i can get-job (API method) with an xml structure of my job and then i can create-job (API method) in jenkins with the followed xml.
?xml version='1.0' encoding='UTF-8'?>
<project>
<actions/>
<description></description>
<keepDependencies>false</keepDependencies>
<properties/>
<scm class="hudson.plugins.git.GitSCM" plugin="git#2.2.7">
<configVersion>2</configVersion>
<userRemoteConfigs>
<hudson.plugins.git.UserRemoteConfig>
<url>https://username:password#bitbucket.org/repoowner/project.git</url>
<credentialsId>550e8400-e29b-41d4-a716-446655440000</credentialsId>
</hudson.plugins.git.UserRemoteConfig>
</userRemoteConfigs>
....
Even if i give this url tag "https://username:password#bitbucket.org/repoowner/project.git" jenkins needs authentication to work, so in credentialsId tag jenkins give an UUID.
I want to be able to create a job dynamically by an external application with a given URL in this format "https://username:password#bitbucket.org/repoowner/project.git".
How can it be done?
Thanks.
You can get the credentialsId via the API and the credentials-store plugin.
e.g. for credentials in global Domain
${ your-jenkins-domain }/credential-store/domain/_/api/xml
<domainWrapper>
<credentials>
<_XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/>
</credentials>
<description></description>
<displayName></displayName>
<fullDisplayName></fullDisplayName>
<fullName>credential-store/_</fullName>
<global>true</global>
<urlName>_</urlName>
</domainWrapper>
But on some point it is a bit tricky:
when accessing the xml api for global domain the id already has a '_' as prefix. When using other domains the prefix is missing (but in a job a prefix is added... couldn't figure out where the prefix can be found)
e.g. I stored github access data in a separated domain, the credentialsId tag was:
<XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/>
but used in a job id was:
0XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
Actually i solve the problem just creating an generic user in bitbucket, then the UUID its always the same and i can just copy and paste that UUID to the others project.xml files.

SCP / SSHEXEC - number of connection attempts

I am using scp task followed by sshexec in my ant build.xml. I derive the value for password from a Password field on the screen. The user doesnt have the ability to check if its the right password or not until the task completes successfully.
As a result, if the entered password is incorrect, does Scp / sshexec retry to connect? Is there any handle to limit the number of connection retries?
The sshexec and scp tasks use Java Secure Channel JSch, see ant manual library dependencies.
I had a similiar problem, as JSch tries to authenticate 6 times configured in the com.jcraft.jsch.JSch Class. When wrong password was used, the user account got locked.
Simply patched the com.jcraft.jsch.JSch Class like this :
from :
config.put("MaxAuthTries", "6");
to :
config.put("MaxAuthTries", "3");
Means JSch will only try 3 times to authenticate.
-- Edit after comment --
Download JSch release zip here - the latest version is 0.1.51
Unzip
Open jsch-0.1.51/src/main/java/com/jcraft/jsch/JSch.java
Change line 124
from
config.put("MaxAuthTries", "6");
to
config.put("MaxAuthTries", "3");
Save
Run jsch-0.1.51/build.bat or build.sh according to your OS
Use jsch-0.1.51/dist/lib/jsch-0.1.5.jar
Here a solution which does not require you to manually patch and rebuild the JSch library.
In order to limit the retry count to 1, just add the following script snippet either at the beginning of your Ant script, or before invoking scp and sshexec tasks, e.g.:
<script language="javascript"> <![CDATA[
com.jcraft.jsch.JSch.setConfig("MaxAuthTries", "1");
]]> </script>
<sshexec host="..." username="..." password="..." command="..."/>
You'll need JSch 0.1.46 or higher! I tested with Ant 1.9.4 and JSch 0.1.51 / 0.1.52.

Ant scp task failure

I have one requirement: copy local files to remote system.
I have done the following:
downloaded jsch-0.1.44.jar and copied to lib folder of Ant
set the path and every thing
My buildfile is:
<project name="ImportedBuild" default="all">
<target name="copyFileToRemote">
<echo>2222222222 copyFileToRemote Examples:::::::::::::</echo>
<scp file="sample.txt" todir="${username}:${password}#${hostname}:/shared"/>
</target>
</project>
When I run Ant, I get this error:
BUILD FAILED com.jcraft.jsch.JSchException: reject HostKey: 10.184.74.168
at com.jcraft.jsch.Session.checkHost(Session.java:712)
at com.jcraft.jsch.Session.connect(Session.java:313)
at com.jcraft.jsch.Session.connect(Session.java:154)
at org.apache.tools.ant.taskdefs.optional.ssh.SSHBase.openSession(SSHBase.java:212)
at org.apache.tools.ant.taskdefs.optional.ssh.Scp.upload(Scp.java:291)
at org.apache.tools.ant.taskdefs.optional.ssh.Scp.execute(Scp.java:203)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
... etc ...
Any ideas how to resolve this?
According to the Ant scp task docs, trust attribute:
This trusts all unknown hosts if set
to yes/true. Note If you set this to
false (the default), the host you
connect to must be listed in your
knownhosts file, this also implies
that the file exists.
The trust attribute is not used in your task call, so it appears that the host (10.184.74.168) is not in your knownhosts file. Suggest you add trust="true", or add the host to the knownhosts file.
Be sure your ~/.ssh/known_hosts file is using un-hashed hostnames; if the lines start |1|base64data..., JSch appears unable to parse them. Create lines of the format hostname[,hostname|ip]* ssh-keytype base64data....
See man 8 sshd on the precise format of known_hosts, and tips on where to find the host's public key.

Resources