GitSCM credentials programmatically with Groovy - jenkins

How can I pass the credential information when creating a job based on a Jenkinsfile in GitHub?
#!groovy
import hudson.*
import jenkins.*
import jenkins.model.*
import hudson.model.*
import hudson.plugins.git.*;
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.*
// Creating the credential to access GitHub
def parent = Jenkins.instance
def source = new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource("HIDDEN")
def ck1 = new BasicSSHUserPrivateKey(CredentialsScope.GLOBAL, "GitHub", "user", source, "password", "My Description")
SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(), ck1)
// Creating the pipeline
def scm = new GitSCM("ssh-url")
scm.branches = [new BranchSpec("*/main")]
def flowDefinition = new org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition(scm, "Jenkinsfile")
def job = new org.jenkinsci.plugins.workflow.job.WorkflowJob(parent, "Dev-1")
job.definition = flowDefinition
parent.save()
parent.reload()
The result when I run it is the following:
stderr: git#github.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.

Related

Edit user in Jenkins via groovy script

I am wondering if I can change password, username, email in Jenkins user. Because I am able to create user via groovy script like this:
import hudson.model.*
def user = instance.securityRealm.createAccount(userId, password)
user.addProperty(new Mailer.UserProperty(email));
instance.save()
Jenkins interface allows me to manage user credentials, but script which allow to change password/email/username would be very helpfull. I didnt find examples.
I tried many times with script like this, but It didnt work
import hudson.model.*
User user = User.getAll().get(1)
user.setProperty(newPassword)
Here's a simple code that works :
import jenkins.model.*
import hudson.security.*
import hudson.tasks.Mailer
def env = System.getenv()
def jenkins = Jenkins.getInstance()
if(!(jenkins.getSecurityRealm() instanceof HudsonPrivateSecurityRealm))
jenkins.setSecurityRealm(new HudsonPrivateSecurityRealm(false))
if(!(jenkins.getAuthorizationStrategy() instanceof GlobalMatrixAuthorizationStrategy))
jenkins.setAuthorizationStrategy(new GlobalMatrixAuthorizationStrategy())
// update admin Jenkins user account
def user = jenkins.getSecurityRealm().getUser('admin')
email= 'jenkins-admin#gmail.com'
user.addProperty(new Mailer.UserProperty(email));
For Jenkins Jenkins 2.361.1, I have used such Jenkins groovy script to update user's password:
User.getById("userName",false).addProperty(hudson.security.HudsonPrivateSecurityRealm.Details.fromPlainPassword("new-password"));
You can also easily run it from bash script or similar, given $USERNAME and $PASSWORD are set:
echo "script=User.getById(\"$USERNAME\",false).addProperty(hudson.security.HudsonPrivateSecurityRealm.Details.fromPlainPassword(\"$PASSWORD\"));" | \
curl -d #- --user admin:access_token http://<ip>:8080/scriptText

How to use the credentials stored in Jenkins in a groovy script in jenkins DSL

I am using jenkins with Jobdsl to create jenkins jobs. I am trying to build a parameterized job by adding a groovy script in active choice parameter. The script uses a credential stored in jenkins credential, I am trying to fetch it in my script by using the code
import jenkins.model.*
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
credentialsId = '1672622gjj'
def jenkinsCredentials = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.Credentials.class,
Jenkins.instance,
null,
null
).find{it.id == credentialsId};
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class, Jenkins.instance, null, null ).find{
it.id == credentialsId}
println(creds.username)
println(creds.password)
This code gives me the credential name and password but the result of the branches is blank. I am using `creds.password` as the authorization token.
What I am doing wrong?
You can replace the string there the same way, you do already with your script name (+ the strings), yet this not groovy at all.
So this should work:
... "curl ... 'Authorization: token ${creds.password}' ...

How can I modify IamInstanceProfile in a Jenkins Slave template ec-2 plugin?

I am trying to modify IamInstanceProfile in Jenkins AWC EC-2 plugin slave template configuration but it's not working.
import hudson.model.*
import hudson.node_monitors.*
import hudson.slaves.*
import java.util.concurrent.*
import jenkins.model.*
import hudson.plugins.ec2.*
import com.amazonaws.services.ec2.model.*
jenkins = Hudson.instance
def now = new Date()
def instance = Jenkins.getInstance()
def clouds = instance.clouds
def temp=instance.clouds[0].getTemplates()[0]
println temp.getIamInstanceProfile()
def riRequest = new RunInstancesRequest()
riRequest.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(temp.getIamInstanceProfile()));
println riRequest
Jenkins.instance.save()
It executes without any error but without updating the IamInstanceProfile.
I figured it out from https://github.com/jenkinsci/ec2-plugin/blob/master/src/main/java/hudson/plugins/ec2/SlaveTemplate.java and found out iamInstanceProfile is a read-only property.

Jenkins: Automate CI Docker instance

I'm trying to setup Jenkins to be fully automated once I launch it from a docker container.
My question is how do I automate the configuration of the global Jenkins settings. For example the items in manage jenkins and credentials?
I'm using this a reference:
https://wiki.jenkins.io/display/jenkins/remote+access+api
Currently, I have the set these items up manually. I would like to fully automate the CI server creation. Is this possible with Jenkins or is there some human intervention that is required?
Any help would be greatly appreciated.
we used chef to setup the master , and it run some groovy scripts to install all the plugin and configuration. it almost done fully automatically , beside 1 or 2 plugins that I didn't find the syntax to configure all others works fine.
I installed all the plugins using Jenkins CLI , check yourJenkins/cli/ for reference.
for the general configuration you can install all the tools
import jenkins.model.*
import hudson.model.*
def inst1 = Jenkins.getInstance()
def desc1 = inst1.getDescriptor("hudson.tools.JDKInstaller")
println desc1.doPostCredential('buildJenkins#gmail.com','JenkinsOracleXXXXX')
import jenkins.model.*
import hudson.model.*
import hudson.tools.*
// JDK installation
def inst = Jenkins.getInstance()
def desc = inst.getDescriptor("hudson.model.JDK")
def versions = [
"jdk-1.8.101": "jdk-8u101-oth-JPR",
// "jdk-1.8.102": "jdk-8u102-oth-JPR"
]
general variables
// general properties
instance = Jenkins.getInstance()
globalNodeProperties = instance.getGlobalNodeProperties()
envVarsNodePropertyList = globalNodeProperties.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class)
newEnvVarsNodeProperty = null
envVars = null
if ( envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0 ) {
newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty();
globalNodeProperties.add(newEnvVarsNodeProperty)
envVars = newEnvVarsNodeProperty.getEnvVars()
} else {
envVars = envVarsNodePropertyList.get(0).getEnvVars()
}
envVars.put("ARTIFACTORY_URL", "artifactory-url")
envVars.put("ARTIFACTORY_USER", "jenkins")
envVars.put("DOCKER_USER", "docker-push")
instance.save()
email address
// admin Email
def jenkinsLocationConfiguration = JenkinsLocationConfiguration.get()
jenkinsLocationConfiguration.setAdminAddress('admin#yours.com')
jenkinsLocationConfiguration.save()
there a lot of examples , just look for groovy Jenkins configuration ..
if you have any specific question let me know.

Triggering a Job on start up in Jenkins

I am trying to get a new job to run every time my Jenkins restarts. I want to do this through "init.groovy" script. For example let's say if I restart my jenkins server it will execute a job that says "Hello world". And I have to create this job from my init.groovy script.
I have this code so far
import jenkins.model.Jenkins
import org.jenkinsci.plugins.workflow.job.WorkflowJob
WorkflowJob job = Jenkins.instance.createProject(WorkflowJob, 'my-pipeline2')
now I don't know how to configure this job instance without getting into the GUI. I want to add pipeline scripts to it. Like echo "Hello world". And then I want to finally build this job. I want to do all that from this one init.groovy script. I couldn't find any solution to this over internet. So any help is greatly appreciated. Thanks
You could also try the Startup Trigger plugin.
Once installed, go the Job that you want to trigger after startup and in the section 'Build Triggers', check 'Build when Jenkins first starts'
(This question may be old, but hope my answer helps someone)
So I have finally done this with the following groovy script.
#!groovy
import jenkins.model.*
import hudson.security.*
import jenkins.install.*;
import hudson.triggers.SCMTrigger;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
def instance = Jenkins.getInstance()
println "--> creating local user 'admin'"
def hudsonRealm = new HudsonPrivateSecurityRealm(false)
hudsonRealm.createAccount('admin','admin')
instance.setSecurityRealm(hudsonRealm)
def strategy = new FullControlOnceLoggedInAuthorizationStrategy()
instance.setAuthorizationStrategy(strategy)
instance.save()
jenkins = Jenkins.instance;
workflowJob = new WorkflowJob(jenkins, "workflow2");
jobName = "create-dsl-job2";
gitTrigger = new SCMTrigger("* * * * *");
dslProject = new hudson.model.FreeStyleProject(jenkins, jobName);
dslProject.addTrigger(gitTrigger);
jenkins.add(dslProject, jobName);
job = jenkins.getItem(jobName)
builders = job.getBuildersList()
hudson.tasks.Shell newShell = new hudson.tasks.Shell("echo \"Hello\" ")
builders.replace(newShell)
gitTrigger.start(dslProject, true);

Resources