티스토리 뷰

개발관련

Jenkins Remote API

길나미 2017. 3. 27. 16:59

Jenkins에서는 Remote API를 제공하고 있다. 


https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API



기능은 

  1. retrieve information from Jenkins for programmatic consumption.
  2. trigger a new build
  3. create/copy jobs

요약하자면 배치작업들에 대한 관리가 가능하단 얘기다. 




정작 내가 필요한건 젠킨스에 등록된 전체유저의 정보를 가져오는것이었다. 

개발시 여러툴을 사용하는데 그에 따른 유저의 통합관리에 대한 필요성이 있어 해당API를 찾아보게 되었다.  


https://wiki.jenkins-ci.org/display/JENKINS/Authenticating+scripted+clients


Java로 만들거고 httpclient 4.3.x를 이용하여 테스코드를 작성해 보았다. 



import java.io.IOException;
import java.net.URI;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Simple class to launch a jenkins build on run@Cloud platform, should also work on every jenkins instance (not tested)
 *
 */
public class TestPreemptive {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Test
	public void executeJenkins() throws Exception{
		
		String url = "http://localhost:8080/asynchPeople/api/json";
		String user = "USER_NAME";
		String password = "API_TOKEN"; //api token정보 
		
		String response = scrape(url, user, password);
		logger.debug(response);
	}
	
	public String scrape(String urlString, String username, String password) throws ClientProtocolException, IOException {
		URI uri = URI.create(urlString);
		HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(username, password));
		// Create AuthCache instance
		AuthCache authCache = new BasicAuthCache();
		// Generate BASIC scheme object and add it to the local auth cache
		BasicScheme basicAuth = new BasicScheme();
		authCache.put(host, basicAuth);
		CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
		HttpGet httpGet = new HttpGet(uri);
		// Add AuthCache to the execution context
		HttpClientContext localContext = HttpClientContext.create();
		localContext.setAuthCache(authCache);

		HttpResponse response = httpClient.execute(host, httpGet, localContext);

		return EntityUtils.toString(response.getEntity());
	}
}


실행결과 내가 원하는 정보가 출력되었다. 


{"_class":"hudson.model.View$AsynchPeople$People",
"users":[
{"lastChange":null,"project":null,"user":{"absoluteUrl":"http://localhost:8080/user/user1","fullName":"user1"}},
{"lastChange":null,"project":null,"user":{"absoluteUrl":"http://localhost:8080/user/user2","fullName":"user2"}}
]}


이번엔 내가 원하는 정보를 scope에 추가해보았다. 

        @Test
	public void executeJenkins() throws Exception{
		
		String url = "http://localhost:8080/asynchPeople/api/json?tree=users[user[id,fullName,property[address]]]&pretty=true";
		String user = "USER_NAME";
		String password = "API_TOKEN"; //api token정보 
		
		String response = scrape(url, user, password);
		logger.debug(response);
	}


그랬더니 pretty 하게 추가 정보가 필터링된 값이 넘어오는것을 확인 할 수 있다.

{
  "_class" : "hudson.model.View$AsynchPeople$People",
  "users" : [
    {
      "user" : {
        "fullName" : "wingdeep",
        "id" : "wingdeep",
        "property" : [
          {
            "_class" : "jenkins.security.ApiTokenProperty"
          },
          {
            "_class" : "com.cloudbees.plugins.credentials.UserCredentialsProvider$UserCredentialsProperty"
          },
          {
            "_class" : "hudson.plugins.emailext.watching.EmailExtWatchAction$UserProperty"
          },
          {
            "_class" : "hudson.model.MyViewsProperty"
          },
          {
            "_class" : "org.jenkinsci.plugins.displayurlapi.user.PreferredProviderUserProperty"
          },
          {
            "_class" : "hudson.model.PaneStatusProperties"
          },
          {
            "_class" : "hudson.search.UserSearchProperty"
          },
          {
            "_class" : "hudson.security.HudsonPrivateSecurityRealm$Details"
          },
          {
            "_class" : "hudson.tasks.Mailer$UserProperty",
            "address" : "gilnami100@gmail.com"
          },
          {
            "_class" : "jenkins.security.LastGrantedAuthoritiesProperty"
          }
        ]
      }
    },
    {
      "user" : {
        "fullName" : "MANAGE_DOMAINS",
        "id" : "MANAGE_DOMAINS",
        "property" : [
          {
            "_class" : "jenkins.security.ApiTokenProperty"
          },
          {
            "_class" : "com.cloudbees.plugins.credentials.UserCredentialsProvider$UserCredentialsProperty"
          },
          {
            "_class" : "hudson.tasks.Mailer$UserProperty",
            "address" : null
          },
          {
            "_class" : "hudson.plugins.emailext.watching.EmailExtWatchAction$UserProperty"
          },
          {
            "_class" : "hudson.model.MyViewsProperty"
          },
          {
            "_class" : "org.jenkinsci.plugins.displayurlapi.user.PreferredProviderUserProperty"
          },
          {
            "_class" : "hudson.model.PaneStatusProperties"
          },
          {
            "_class" : "hudson.search.UserSearchProperty"
          }
        ]
      }
    }
  ]
}


api 호출시 password는 실제 비밀번호를 넣어도 되지만 보안상 내정보 > Configuration에서 API Token을 확인한다. 


'개발관련' 카테고리의 다른 글

Springboot response server-header 숨기기  (4) 2017.09.25
Jenkins Window 설치  (0) 2017.03.07
oAuth와 SSO의 차이  (0) 2017.02.01
원격접속 프로그램  (0) 2017.01.27
ssh git 연결시 RSA 키 생성 및 등록 방법  (0) 2016.11.28
댓글