How to extract members of a group in Jenkins using Groovy? - jenkins

I am using Active directory plugin and in a need of listing the members of a active directory group in Jenkins itself using groovy. I have tried below code and it always returns null.
import jenkins.model.*
import hudson.security.*
import hudson.plugins.active_directory.*
def instance = Jenkins.getInstance()
String domain = 'my.domai.com'
String site = 'ldap.com:3268'
String server = 'ldap.com:3268'
String bindName = 'user'
String bindPassword = 'passwd'
adrealm = new ActiveDirectorySecurityRealm(domain, site, bindName, bindPassword, server)
adrealm.loadGroupByGroupname("my_team").getMembers()

Related

Connecting to Azure DevOps and TFS with VssConnection and username/password

I have a service which import tasks from TFS and Azure Devops. I use Microsoft.TeamFoundationServer.Client 16.153.0
I'm trying to connect to TFS using next code
var httpClient = new WorkItemTrackingHttpClient(new Uri(_settings.ServerAddress), new VssBasicCredential(_settings.Login, _settings.Password));
var taskQuery = "..."
var queryResult = await httpClient.QueryByWiqlAsync(tasksQuery, timePrecision:true);
This code works only for first time. If I change login/password and import tasks again it still using previous login/password even if it wrongs. And It doesn't work for azure devops.
What do I wrong?
Try using the following code to connect to DevOps. It obtain the PAT you defined in the code:
Uri uri = new Uri(_uri);
string personalAccessToken = _personalAccessToken;
string project = _project;
VssBasicCredential credentials = new VssBasicCredential("", _personalAccessToken);

Spring data rest shows id as path variable in swagger for POST method in mongo repository?

I am just using MongoRepository. Below is my entity class:
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "product")
#Data
#ToString
#EqualsAndHashCode
#JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Product {
#Id private String id;
#Indexed(unique = true)
private String name;
private boolean displayAds;
}
When I view the resource in Swagger the POST method appears as follows:
This is my repository:
import org.springframework.data.mongodb.repository.MongoRepository;
public interface ProductRepository extends MongoRepository<Product, String> {
}
Why does this happen? Is there a fix? I'm using springfox-swagger2 and springfox-swagger-ui.
Anyway it can post via Postman without adding such path variable.
Updating to 2.8.0 should resolve the issue.
This seems to have been a bug in Springfox version 2.7.0. Should be fixed in 2.8.0 as highlighted here.

Cannot cast object in Jenkins job generator

I have a problem with my DSL job generator:
Processing DSL script seed.groovy
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'com.dabsquared.gitlabjenkins.connection.GitLabApiTokenImpl#4046fd60' with class 'com.dabsquared.gitlabjenkins.connection.GitLabApiTokenImpl' to class 'com.dabsquared.gitlabjenkins.connection.GitLabApiTokenImpl'
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.continueCastOnSAM(DefaultTypeTransformation.java:405)
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.continueCastOnNumber(DefaultTypeTransformation.java:319)
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType(DefaultTypeTransformation.java:232)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.castToType(ScriptBytecodeAdapter.java:603)
at com.blue.devops.generator.Generator$_closure1.doCall(Generator.groovy:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
I am running a DSL job generator that access gitswarm API, gets the information about available projects and their branches and creates Jenkins jobs.
Interaction with gitswarm api is done via Client class - my gitswarm API client.
Generator.groovy:
class Generator {
SystemCredentialsProvider systemCredentialsProvider = (SystemCredentialsProvider) Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0]
CredentialsStore credentialsStore = (CredentialsStore) systemCredentialsProvider.getStore()
Domain domain = Domain.global()
List<Credentials> credentials = credentialsStore.getCredentials(domain)
Client client
Generator(String tokenId="gitswarm_token") {
credentials.each { Credentials credentials ->
if(credentials.getId() == tokenId) {
GitLabApiTokenImpl token = (GitLabApiTokenImpl) credentials //line 28
client = new Client(apiToken: token.getApiToken().getPlainText())
}
}
}
boolean generateJobs(DslFactory factory) {
ArrayList<Project> supportedProjects = client.getSupportedProjects()
supportedProjects.each { supportedProject ->
handleProject(supportedProject, factory)
}
return true
}
}
Jenkins is running this DSL seed job:
import com.blue.devops.generator.Generator
new Generator().generateJobs(this)
Please help
The Job DSL classloader does not support access to classes provided by other plugins. So you can't import a class from another plugin and can't cast an object to that class.
But Groovy is a dynamic language. You don't need to cast an object to a specific class to be able to access it's members. Groovy will figure that out at runtime. The following example show how to get the API token with using any classes from plugins.
def systemCredentialsProvider = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0]
def credentials = systemCredentialsProvider.credentials
def gitlabCredentials = credentials.find { it.id == 'test' }
def apiToken = gitlabCredentials.apiToken.plainText

job-dsl - How to pass credentials while creating jobs from gitlab repo branches?

I am creating a jobs for each application branches from github.
I am not sure how to pass the credentials to the repo link?
import groovy.json.*
def project = 'app-ras'
def branchApi = new URL("https://gitlab.etctcssd.com/sdadev/${project}/branches")
def branches = new JsonSlurper().parse(branchApi.newReader())
branches.each {
def branchName = it.name
def jobName = "${project}-${branchName}".replaceAll('/','-')
job(jobName) {
scm {
git("https://gitlab.etctcssd.com/sdadev/${project}.git", branchName)
}
}
}
Our project is secure project in gitlab, so how can I pass the credentials in this case?
I am sure it would redirect to login page. But I am not sure how to handle this. Any help would be greatly appreciated.
I hope it will work in the following way:
import groovy.json.JsonSlurper
def project = 'app-ras'
def branchApi = new URL("https://gitlab.etctcssd.com/sdadev/${project}/branches")
def branches = new JsonSlurper().parse(branchApi.newReader())
branches.each {
def branchName = it.name
String jobName = "${project}-${branchName}".replaceAll('/', '-')
job(jobName) {
scm {
git {
branch(branchName)
remote {
url("https://gitlab.etctcssd.com/sdadev/${project}.git")
credentials("HERE")
}
}
}
}
}
Try to substitute HERE with plain credentials (a kind of an access token) or with credential ID (of type Secret text) defined under Jenkins -> Credentials.
Also, are you using gitlab or github?
EDIT
So as far as I understood you have problems with fetching the branches names not with the Jenkins DSL. Here you can see how to fetch branches from gitlab. In groovy in can be done in the following way:
URLConnection connBranches = new URL("https://gitlab.etctcssd.com/sdadev/${project}/branches").openConnection()
connBranches.setRequestProperty("PRIVATE-TOKEN", "PASTE TOKEN VALUE HERE")
new JsonSlurper().parse(new BufferedReader(new InputStreamReader(connBranches.getInputStream())))

Groovy script to Grails app

Well I am new to Groovy/Grails. I have written a Groovy script that uses RESTClient to make HTTP POST request to JIRA server. The POST request sends a JQL query and receives the result in JSON format. Here's the full code:
import groovyx.net.http.RESTClient;
import groovyx.net.http.HttpResponseDecorator;
import org.apache.http.HttpRequest;
import org.apache.http.protocol.HttpContext;
import org.apache.http.HttpRequestInterceptor;
import groovy.json.JsonSlurper;
import static groovyx.net.http.Method.*
import static groovyx.net.http.ContentType.*
#Grab(value = 'org.codehaus.groovy:groovy-all:2.1.6',
initClass = false)
#Grapes([
#Grab(group = 'org.codehaus.groovy.modules.http-builder',
module = 'http-builder', version = '0.5.2'),
#GrabExclude('org.codehaus.groovy:groovy')
])
// connect to JIRA
def jiraApiUrl = 'http://my-jira.com/rest/api/2/'
def jiraClient = new RESTClient(jiraApiUrl);
// authentication
def basic = 'Basic ' + 'username:password'.bytes.encodeBase64().toString()
jiraClient.client.addRequestInterceptor (
new HttpRequestInterceptor() {
void process(HttpRequest httpRequest,
HttpContext httpContext) {
httpRequest.addHeader('Authorization', basic)
}
})
// http post method
def uriPath = 'search'
def param = [maxResults : 1, jql : '<jql-query>']
def Issues = jiraClient.post(requestContentType : JSON, path : uriPath, body : param)
def slurpedIssues = new JsonSlurper().parseText(Issues.data.toString())
println Issues.data.total
I need to migrate this script to a Grails app. Any suggestions as to how to do the same?
Define dependencies in BuildConfig (except the groovy dependency)
copy script contents to a Service
Possible extension:
use the grails rest plugin or grails rest-client-builder plugin instead of http-builder
Putting the logic into Service object will give you the ability to do dependency injection, which is native to grails services.
Also, you should consider using AsyncHTTPBuilder if your app has many users trying to make requests.
I strongly believe that the service response will be directly rendered to JSON
//your controller
class AbcController{
//your action
def save() {
render(abcService.save(params) as JSON)//your service response now been rendered to JSON
}
}
//your service class class AbcService {
def save(params){
....
return something
}
}

Resources