티스토리 뷰
반응형
Jenkins에서는 Remote API를 제공하고 있다.
https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API
기능은
- retrieve information from Jenkins for programmatic consumption.
- trigger a new build
- 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을 확인한다.
'개발관련' 카테고리의 다른 글
| OpenAI 연동 개발을 위한 API Key 발급받기 (0) | 2025.01.04 |
|---|---|
| Springboot response server-header 숨기기 (4) | 2017.09.25 |
| Jenkins Window 설치 (0) | 2017.03.07 |
| oAuth와 SSO의 차이 (0) | 2017.02.01 |
| 원격접속 프로그램 (0) | 2017.01.27 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- openai api key
- select count(*) performence
- 스프링 크로스도메인
- 원격접속 무료툴
- 젠킨스 api
- mysql count 성능
- 원격접속툴
- spring mybatis
- openai 키 발급
- BeanCreationException
- response server header
- oauth sso 차이
- jenkins asyncpeople
- mysql count
- 아이맥 m4
- 객체지향언어 자바
- google vm ssh
- java.lang.UnsatisfiedLinkError
- imac m4
- 작은거에소스라치게놀라는나
- common-dbcp
- 스프링 마이바티즈 연동오류
- 아이맥24 m4
- no net in java.library.path
- jenkins user list
- springboot server header
- 젠킨스 윈도우 설치
- 인덱스 자료구조
- Google ssh console
- jenkins remote api
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 | 31 |
글 보관함