스크립트 콘솔
스크립트 콘솔 (Script Console)
Jenkins에는 Groovy 스크립트 콘솔이 있어서 Jenkins 컨트롤러 런타임이나 에이전트 런타임에서 임의의 Groovy 스크립트를 실행할 수 있어요. 이 도구는 강력하지만, 보안상 위험이 크므로 관리 권한이 있는 사용자만 사용해야 합니다.
출처: Jenkins 문서
본문
Jenkins에는 Groovy 스크립트 콘솔이 있으며, 이를 통해 Jenkins 컨트롤러 런타임 또는 에이전트 런타임에서 임의의 Groovy 스크립트를 실행할 수 있습니다.
참고: 다음 사항은 모두 이해하는 것이 매우 중요합니다. 왜냐하면 이는 Jenkins 설치의 무결성에 영향을 주기 때문입니다. Jenkins Script Console:
- 접근은 Administer 권한에 의해 제어됩니다.
- Jenkins 런타임에 대한 웹 기반 Groovy 셸입니다.
- Groovy는 Java가 할 수 있는 거의 모든 것을 할 수 있는 매우 강력한 언어로, 서브프로세스 생성과 Jenkins 컨트롤러 및 에이전트에서 임의의 명령 실행을 포함합니다. 컨트롤러가 호스트에서 접근할 수 있는 파일(예:
/etc/passwd)도 읽을 수 있고, Jenkins 안에 구성된 자격 증명을 복호화할 수도 있습니다.- 사용자(또는 관리자)가 스크립트 콘솔을 실행할 수 있게 되면 Jenkins 인프라의 모든 부분에 영향을 주는 것을 막을 수 있는 관리 제어 수단을 제공하지 않습니다. 일반 Jenkins 사용자에게 Script Console 접근 권한을 부여하는 것은 곧 그들에게 Jenkins 내 관리자 권한을 주는 것과 같습니다.
- 어떤 Jenkins 설정도 구성할 수 있습니다. 보안을 비활성화하거나 재구성할 수 있고, 심지어 Jenkins 프로세스와 완전히 분리된 호스트 운영 체제에 백도어를 열 수도 있습니다. 많은 조직이 인프라에서 Jenkins에 부여하는 미션 크리티컬 중요성 때문에 이 점은 특히 중요합니다. 공격자가 거의 노력 없이 인프라 내에서 수평 이동(lateral movement)을 할 수 있게 해주기 때문입니다.
- 원래 Jenkins 개발자를 위한 디버깅 인터페이스로 의도되었지만, 현재는 Jenkins 관리자가 Jenkins를 구성하고 런타임 문제를 디버깅하는 데 사용하는 인터페이스로 성장했습니다.
관리 스크립트에 대한 추가 보안 고려 사항:
- 스크립트는 모든 보안 제어를 우회하고 모든 데이터에 접근할 수 있습니다.
- 스크립트를 통해 접근한 자격 증명은 복호화됩니다.
- 스크립트를 통해 이루어진 변경은 일반 로그에서 감사되지 않을 수 있습니다.
- 스크립트는 Jenkins를 가장 낮은 수준에서 수정하여 불안정하게 만들 수 있습니다.
Jenkins Script Console이 제공하는 강력함 때문에 Jenkins와 그 에이전트는 절대 root 사용자(Linux)나 시스템 관리자로 실행해서는 안 됩니다.
여러 컨텍스트 (Multiple contexts)
Jenkins Script Console은 컨트롤러 또는 구성된 모든 에이전트에서 실행할 수 있습니다.
컨트롤러에서 Script Console 실행
이 기능은 *"Manage Jenkins" > "Script Console"*에서 접근할 수 있습니다. 또는 Jenkins 컨트롤러의 하위 URL /script를 방문해도 됩니다.
에이전트에서 Script Console 실행
*"Manage Jenkins" > "Manage Nodes"*를 방문하세요. 아무 노드나 선택해 상태 페이지를 엽니다. 왼쪽 메뉴에서 해당 특정 에이전트에 "Script Console"을 여는 메뉴 항목을 사용할 수 있습니다.
컨트롤러 Script Console에서 에이전트에 스크립트 실행
컨트롤러 Script Console에서 개별 에이전트에 스크립트를 실행하는 것도 가능합니다. 다음 스크립트는 컨트롤러 Script Console에서 에이전트에 스크립트를 실행하는 예시입니다.
Script executes code on agent from Master Script Console
import hudson.util.RemotingDiagnostics
import jenkins.model.Jenkins
String agentName = 'your agent name'
//groovy script you want executed on an agent
groovy_script = '''
println System.getenv("PATH")
println "uname -a".execute().text
'''.trim()
String result
Jenkins.instance.slaves.find { agent ->
agent.name == agentName
}.with { agent ->
result = RemotingDiagnostics.executeGroovy(groovy_script, agent.channel)
}
println result
파일 읽기와 쓰기
컨트롤러 Script Console을 통해 컨트롤러 또는 에이전트에서 파일을 직접 읽고 쓸 수 있습니다.
Write a file to the Jenkins controller
new File('/tmp/file.txt').withWriter('UTF-8') { writer ->
try {
writer << "Writing text to file"
} finally {
writer.close()
}
}
Reading a file from the Jenkins controller
new File('/tmp/file.txt').text
Write file to agent through agent channel
import hudson.FilePath
import hudson.remoting.Channel
import jenkins.model.Jenkins
String agentName = 'some-agent'
String filePath = '/tmp/file.txt'
Channel agentChannel = Jenkins.instance.slaves.find { agent ->
agent.name == agentName
}.channel
new FilePath(agentChannel, filePath).write().with { os ->
try {
os << 'some text'
} finally {
os.close()
}
}
Read file from agent through agent channel
import hudson.FilePath
import hudson.remoting.Channel
import jenkins.model.Jenkins
import java.io.BufferedReader
import java.io.InputStreamReader
import java.nio.charset.StandardCharsets
import java.util.stream.Collectors
String agentName = 'some-agent'
String filePath = '/tmp/file.txt'
Channel agentChannel = Jenkins.instance.slaves.find { agent ->
agent.name == agentName
}.channel
String fileContents = ''
new FilePath(agentChannel, filePath).read().with { is ->
try {
fileContents = new BufferedReader(
new InputStreamReader(is, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"))
} finally {
is.close()
}
}
// print contents of the file from the agent
println '==='
println(fileContents)
println '==='
관리 기능 (Administrative capabilities)
Script Console은 Jenkins를 관리하기 위한 강력한 관리 기능을 제공합니다.
아래는 예시와 함께 제공되는 일반적인 관리 작업들입니다.
사용자 관리 (User management)
Jenkins.instance.securityRealm.allUsers.each { user ->
println user.id + ": " + user.fullName
}
import hudson.model.User
import jenkins.model.Jenkins
User user = User.get('new-user', true)
user.fullName = "New User"
user.save()
시스템 구성 (System configuration)
Jenkins.instance.systemMessage = "New system message"
Jenkins.instance.save()
println Jenkins.VERSION
시스템 설정 변경 (System Settings Changes)
System.getProperty("hudson.remoting.Launcher.pingIntervalSec") // view current setting
System.clearProperty("hudson.remoting.Launcher.pingIntervalSec") // set to default
System.setProperty("hudson.remoting.Launcher.pingIntervalSec", "") // unset header
System.setProperty("hudson.remoting.Launcher.pingIntervalSec", 0)
플러그인 관리 (Plugin management)
Jenkins.instance.pluginManager.plugins.each {
println "${it.shortName}: ${it.version}"
}
Jenkins.instance.pluginManager.getPlugin('git').disable()
노드/에이전트 관리 (Node/Agent management)
Jenkins.instance.nodes.each { node ->
println "${node.name}: ${node.numExecutors} executors"
}
Jenkins.instance.getNode('agent-name').computer.doDoDelete()
막힌 작업 종료 (Kill Stuck Job)
Jenkins.instance.getItemByFullName("your-job-name").getBuildByNumber(123).finish(hudson.model.Result.ABORTED, new java.io.IOException("Aborted"))
시스템 Groovy 모범 사례 (Best practices for system groovy)
Script Console을 관리 작업에 사용할 때는 다음을 따르는 것이 좋습니다.
-
항상 프로덕션이 아닌 환경에서 먼저 스크립트를 테스트하세요.
-
스크립트를 실행하기 전에 Jenkins 구성을 백업하세요.
-
가능하면 직접 파일시스템 조작보다 Jenkins API를 사용하세요.
-
필요한 작업만 수행되도록 스크립트 범위를 제한하세요.
-
나중에 참고할 수 있도록 스크립트에 주석을 추가하세요.
-
반복 가능한 구성을 위해 Job DSL이나 Configuration as Code 같은 플러그인 사용을 고려하세요.
-
스크립트가 전체 시스템 권한으로 실행되도록 신중히 검토하세요.
-
오래 실행되는 스크립트는 성능에 영향을 줄 수 있으므로 스크립트 실행을 모니터링하세요.
예시: 안전한 스크립트 템플릿
try {
Jenkins.instance.doSomething()
Jenkins.instance.save()
println "Operation completed successfully"
} catch(Exception e) {
println "Error: ${e.message}"
}
원격 접근 (Remote access)
Jenkins 관리자는 /script/ URL 또는 /scriptText/에 HTTP POST 요청을 보내 원격으로 Groovy 스크립트를 실행할 수 있습니다.
curl example via bash
curl -d "script=<script>" https://jenkins/script
# or to get output as a plain text result (no HTML)
curl -d "script=<script>" https://jenkins/scriptText
또한 Jenkins CLI는 groovy 명령으로 원격으로 Groovy 스크립트를 실행하거나 groovysh로 대화형으로 Groovy를 실행할 수 있는 기능을 제공합니다. 그러나 다시 한번 bash 명령 치환을 사용해 curl로 Groovy 스크립트를 실행할 수도 있습니다. 다음 예시에서 somescript.groovy는 현재 작업 디렉터리의 Groovy 스크립트입니다.
Curl submitting groovy file via bash
curl --data-urlencode "script=$(<somescript.groovy)" https://jenkins/scriptText
Jenkins에 보안이 구성되어 있다면 curl에 curl --user 옵션을 사용해 인증할 수 있습니다.
Curl submitting groovy file providing username and api token via bash
curl --user 'username:api-token' --data-urlencode \
"script=$(<somescript.groovy)" https://jenkins/scriptText
다음은 curl 대신 python을 사용하는 동등한 명령입니다.
Python submitting groovy file providing username and api token
with open('somescript.groovy', 'r') as fd:
data = fd.read()
r = requests.post('https://jenkins/scriptText', auth=('username', 'api-token'), data={'script': data})
스크립트 콘솔 제출용 단축키
마우스 없이도 스크립트를 제출할 수 있습니다. Jenkins에는 키보드로 제출할 수 있게 해주는 단축키가 있습니다.
-
Windows / Linux: Ctrl + Enter
-
Mac: Command + Enter
동영상 튜토리얼 및 추가 학습 자료
Jenkins Script Console에 대한 녹화 영상이 몇 가지 있습니다.
-
Jenkins World 2017: Mastering the Jenkins Script Console - 44분 - 사용 예시와 보안 논의
-
LA Jenkins Area Meetup 2016 - Hacking on Jenkins Internals - Jenkins Script Console - 39분 - 사용 예시
스크립트 콘솔에서 스크립트를 더 잘 작성하기 위해 다음 참고 자료를 권장합니다.
-
Learn Groovy - Groovy를 배우는 것은 Script Console용 스크립트 작성 이상으로 유용합니다. Groovy는 Pipelines, 공유 파이프라인 라이브러리, Groovy Plugin, Job DSL 플러그인, 그리고 Groovy를 활용하는 다른 많은 플러그인(Plugins enabling Groovy usage 섹션 참조)에도 관련됩니다.
-
Jenkins용 Groovy 스크립트를 코드 완성 기능으로 작성하기 - 요점은 IDE 안에서 Maven 프로젝트를 만들고
org.jenkins-ci.main:jenkins-core(및 존재할 것으로 예상되는 다른 플러그인)에 의존하는 것입니다. 그러면 Jenkins API 객체와 메서드의 코드 완성 기능으로 Groovy 스크립트를 작성할 수 있습니다.
예시 Groovy 스크립트
오래된 스크립트
Groovy 스크립트는 Jenkins 소스 코드에 직접 접근하는 특성 때문에, Script Console 스크립트는 Jenkins 소스 코드와 금방 구식이 되기 쉽습니다. Jenkins 핵심이나 Jenkins 플러그인의 public 메서드와 인터페이스가 변경되어 스크립트를 실행하다 예외가 발생할 수 있습니다. 예시를 시도할 때 이 점을 염두에 두세요. Jenkins는 다음 명령으로 로컬 개발 머신에서 쉽게 시작할 수 있습니다.
Starting a local copy of Jenkins
export JENKINS_HOME="./my_jenkins_home"
java -jar jenkins.war
CTRL+C를 사용해 Jenkins를 중지합니다. 프로덕션 Jenkins 컨트롤러에서 Script Console 예시를 시도하는 것은 권장하지 않습니다.
다음 저장소는 Jenkins용 Groovy 스크립트의 훌륭한 예시를 제공합니다.
-
CloudBees jenkins-scripts 저장소.
-
Jenkins CI jenkins-scripts 저장소의
scriptler/디렉터리(Scriptler Plugin용 스크립트). -
Sam Gleske의 jenkins-script-console-scripts 저장소.
-
Sam Gleske의 jenkins-bootstrap-shared 저장소의
scripts/디렉터리.
모든 Scriptler Plugin Groovy Script를 둘러보고 스크립트를 Scriptler Plugin과 공유해 주세요.
-
Activate Chuck Norris Plugin — 이 스크립트는 Jenkins 서버의 모든 작업에 대해 Chuck Norris 플러그인을 활성화합니다.
-
Add a Maven Installation, Tool Installation, Modify System Config
-
Add a new label to agents meeting a condition — 이 스크립트는 에이전트 노드의 라벨 멤버십을 변경하는 방법을 보여줍니다. 이 경우 기존 라벨이 특정 문자열을 포함하면 새 라벨을 만듭니다. Jenkins 명령 창에서 테스트되었습니다.
-
Add notification plugin to every job — 이 스크립트는 Notification Plugin을 모든 작업에 추가합니다.
-
Allow broken build claiming on every jobs — 다음 간단한 스크립트로 서버의 모든 작업에 옵션을 한 번에 활성화할 수 있습니다.
-
Batch-Update Mercurial branch that is checked out — Hg에서 어떤 브랜치를 체크아웃할지 여러 작업을 업데이트합니다.
-
Bulk rename projects
-
Change JVM Options in all Maven tasks of Freestyle Jobs — 이 스크립트는 프리스타일 작업에 등록된 모든 Maven 작업을 찾아 JVM 옵션을 새 값으로 교체합니다.
-
Change publish over SSH configuration
-
Change SCMTrigger for each project to disable during the night and the week-end — 이 스크립트는 매분 실행되는 모든 작업을 21:00~07:00 사이와 토요일·일요일에 비활성화되도록 쉽게 변경합니다.
-
Change Version-Number in SVN-path
-
Clone all projects in a View — 이 스크립트는 특정 뷰에 속한 모든 프로젝트를 열거하고 복제합니다.
-
Convert standard mail notifications to use the Mail-Ext Publisher plugin — 이 스크립트는 모든 프로젝트의 메일 알림을 Mail-Ext publisher 플러그인으로 교체하고 기존 수신자를 재사용합니다.
-
Delete tmp files left in workspace-files — 이 스크립트는 빌드 후 workspace-files 디렉터리에 남은 모든 tmp 파일을 삭제합니다. Windows 서버에서는 꽤 흔한 상황입니다.
-
Delete workspace for all disabled jobs — 모든 비활성 작업의 워크스페이스를 삭제해 공간을 절약합니다.
-
Disable all jobs — 이 스크립트는 Jenkins 서버의 모든 작업을 비활성화합니다.
-
Display Information About Nodes — 이 스크립트는 모든 에이전트 노드에 대한 여러 정보를 표시합니다.
-
Display job parameters — 이 스크립트는 모든 작업의 매개변수를 기본값(해당되는 경우)과 함께 표시합니다.
-
Display jobs group by the build steps they use
-
Display list of projects that were built more than 1 day ago. — 이 스크립트는 1일 이상 전에 빌드된 프로젝트 목록을 표시합니다.
-
Display mail notifications recipients — 이 스크립트는 모든 작업에 대해 알림에 사용되는 메일 수신자 목록을 표시합니다.
-
Display monitors status — Jenkins는 다양한 동작을 검증하기 위해 모니터를 사용합니다. 하나를 해제하면 Jenkins는 다시 활성화하라고 제안하지 않습니다. 이 스크립트는 모든 모니터의 상태를 확인하고 다시 활성화할 수 있게 합니다.
-
Display the number of jobs using SCM Polling from Freestyle, Pipeline and Maven
-
Display timer triggers — 이 스크립트는 더 잘 정리하기 위해 모든 작업의 타이머 트리거를 표시합니다.
-
Display Tools Location on All Nodes — 이 스크립트는 모든 에이전트에서 Jenkins 도구 위치를 찾는 데 도움이 됩니다.
-
Enable Timestamper plugin on all jobs — 다음 간단한 스크립트로 서버의 모든 작업에 옵션을 한 번에 활성화할 수 있습니다.
-
Failed Jobs — 이 스크립트는 모든 실패한 작업 목록을 표시합니다. 추가기능: 재시작.
-
Find builds currently running that has been executing for more than N seconds
-
Grant Cancel Permission for user and group that have Build permission — 이 스크립트는 전역 보안과 작업별 보안 설정 양쪽의 모든 그룹과 사용자를 살펴봅니다.
-
Invalidate Jenkins HTTP sessions — 이 스크립트는 서버에 열린 HTTP 세션이 많을 때 이를 모니터링하고 무효화할 수 있습니다.
-
Manually run log rotation on all jobs — 공간을 확보하기 위해 모든 작업에 로그 로테이션을 실행합니다.
-
Monitor and Restart Offline Agents — 이 스크립트는 수동으로 연결 해제되지 않은 오프라인 노드를 모니터링하고 재시작할 수 있습니다.
-
Monitoring Scripts — Monitoring 플러그인 사용 시 http 세션, 스레드, 메모리, JVM 또는 MBean에 대한 데이터를 표시하는 여러 스크립트.
-
My Test Grovvy
-
Parameterized System Groovy script — 이 스크립트는 시스템 groovy 스크립트에서 매개변수를 얻는 방법을 보여줍니다.
-
Preselect username in Maven Release Build
-
Printing a list of credentials and their IDs
-
Remove all disabled modules in Maven jobs — Maven 작업에서 모든 비활성 모듈을 제거합니다.
-
Remove Deployed Artifacts Actions — 이 스크립트는 Artifact Deployer Plugin이 각 빌드마다 불필요하게 저장하는 Deployed Artifacts 목록을 제거하는 데 사용됩니다.
-
Remove Git Plugin BuildsByBranch BuildData — 이 스크립트는 Git Plugin이 각 빌드마다 불필요하게 저장하는 정적 BuildsByBranch 목록을 제거하는 데 사용됩니다.
-
Set GitBlitRepositoryBrowser with custom settings on all repos — 이 스크립트는 저장소 브라우저를 업데이트할 수 있게 합니다. gitblit뿐 아니라 다른 어떤 브라우저에도 적용할 수 있습니다.
-
Update maven jobs to use the post build task to deploy artifacts — 이 스크립트는 deploy 목표가 있는 모든 maven 작업을 install로 업데이트하고 빌드 마지막에 아티팩트를 배포하도록 post build 단계를 활성화합니다.
-
Update SVN Browser
-
Wipe out workspaces of all jobs — 이 스크립트는 Jenkins 서버의 모든 작업의 워크스페이스를 지웁니다.
-
Wipe workspaces for a set of jobs on all nodes — 이 스크립트는 모든 노드에서 특정 작업들의 워크스페이스를 지웁니다.
Groovy 사용을 가능하게 하는 플러그인 (Plugins enabling Groovy usage)
-
Config File Provider Plugin — Jenkins UI를 통해 로드된 구성 파일(즉, maven용 settings.xml, XML, groovy, 커스텀 파일 등)을 제공해 작업의 워크스페이스에 복사할 수 있게 합니다.
-
Global Post Script Plugin — Jenkins가 관리하는 각 작업의 각 빌드 후 전역 구성된 groovy 스크립트를 실행합니다. 이는 공유 매개변수 집합을 기반으로 어떤 작업을 수행해야 할 때(예: 동일한 Jenkins나 원격에서 관리하는 다운스트림 작업을 매개변수화된 작업에 전달된 매개변수 기반으로 트리거) 전형적으로 사용됩니다.
-
Groovy plugin
-
Groovy Postbuild Plugin — 이 플러그인은 Jenkins JVM에서 groovy 스크립트를 실행합니다. 일반적으로 스크립트는 일부 조건을 확인하고 그에 따라 빌드 결과를 변경하거나, 빌드 히스토리에서 빌드 옆에 배지를 붙이거나, 빌드 요약 페이지에 정보를 표시합니다.
-
Groovy Remote Control Plugin — 이 플러그인은 Groovy Remote Control의 수신기를 제공하며 Jenkins에서 외부 애플리케이션을 제어할 수 있게 합니다.
-
Matrix Groovy Execution Strategy Plugin — 매트릭스 프로젝트의 실행 순서와 유효한 조합을 결정하는 플러그인.
-
Scriptler Plugin — Scriptler는 groovy 스크립트를 저장/편집하고 어떤 노드에서든 실행할 수 있게 합니다. 더 이상 groovy 코드를 복사/붙여넣기할 필요가 없습니다.
더 알아보기 (Learn more)
Script Console은 강력하지만 위험한 도구이므로 반드시 관리 권한 범위에서 신중히 사용하세요. Groovy 문법과 Jenkins 내부 API에 대한 더 깊은 내용은 Learn Groovy 자료와 Jenkins 공식 문서를 참고하세요.