Docker - Jenkins 컨테이너에 jq 설치하기

Jenkins는 지속적 통합(CI) 및 지속적 배포(CD)를 자동화하는 데 널리 사용되는 오픈 소스 자동화 서버입니다. 때로는 Jenkins 파이프라인이나 스크립트 내에서 JSON 데이터를 처리해야 할 필요가 있을 수 있습니다. 이런 경우, **jq**는 매우 유용한 도구입니다. **jq**는 커맨드라인 JSON 프로세서로, JSON 형식의 데이터를 다루기 위한 강력한 도구입니다. 이 글에서는 Docker를 사용하여 Jenkins 컨테이너에 **jq**를 설치하는 방법을 안내합니다.

시작하기 전에

이 글을 따라 하기 위해서는 Docker와 Docker Compose가 설치되어 있어야 합니다. Docker Compose를 사용하면 여러 컨테이너의 설정을 docker-compose.yml 파일 하나로 관리할 수 있어 편리합니다.

Dockerfile 생성

첫 번째 단계는 **jq**를 포함한 커스텀 Jenkins 이미지를 만들기 위한 **Dockerfile**을 생성하는 것입니다. 아래는 해당 **Dockerfile**의 예시입니다:

# Dockerfile
FROM jenkins/jenkins:lts
USER root
RUN apt-get update && \
    apt-get install -y jq && \
    rm -rf /var/lib/apt/lists/*
USER jenkins

이 **Dockerfile**은 공식 Jenkins LTS 이미지를 기반으로 하며, root 사용자로 전환하여 **jq**를 설치한 후, 다시 jenkins 사용자로 전환합니다.

docker-compose.yml 수정

다음으로, docker-compose.yml 파일을 수정하여 위에서 생성한 **Dockerfile**을 사용하도록 설정합니다:

version: '3'
services:
 jenkins:
   build: .
   container_name: 'jenkins'
   restart: always
   ports:
     - '9090:8080'
     - '50000:50000'
   volumes:
     - '~/jenkins:/var/jenkins_home'
     - '/var/run/docker.sock:/var/run/docker.sock'
   environment:
     TZ: 'Asia/Seoul'

여기서 **build: .**는 현재 디렉토리에 있는 **Dockerfile**을 사용하여 이미지를 빌드하라는 의미입니다.

컨테이너 빌드 및 실행

모든 설정이 완료되었다면, 다음 명령어를 사용하여 컨테이너를 빌드하고 실행할 수 있습니다:

docker-compose up --build

이 명령어는 docker-compose.yml 파일에 정의된 설정에 따라 컨테이너를 빌드하고 실행합니다. --build 옵션은 이미지가 존재하지 않거나 **Dockerfile**이 변경된 경우 이미지를 다시 빌드하라는 지시입니다.

결론

이제 Jenkins 컨테이너 내부에서 **jq**를 사용하여 JSON 데이터를 쉽게 처리할 수 있습니다. 이 방법을 통해 Jenkins 파이프라인이나 스크립트에서 JSON 관련 작업을 보다 효율적으로 수행할 수 있게 되었습니다.


활용

| 슬렉 자동알림 : Post build task - Script

#!/bin/bash
cd /var/jenkins_home/workspace/subfolder
git_previous_successful_commit=$GIT_PREVIOUS_SUCCESSFUL_COMMIT
git_current_commit=$GIT_COMMIT
commit_messages=$(git log --pretty=format:"%h - %s" $git_previous_successful_commit..$git_current_commit)

JSON_PAYLOAD=$(jq -n \
  --arg token "xoxb-..." \
  --arg channel "..." \
  --arg text "
    subfolder 배포알림
    https://subfolder.ai
    <변경사항>
    $commit_messages
    " \
  '{token: $token, channel: $channel, text: $text}')

curl -X 'POST' \
  'https://.../v1/send/slack' \
  -H 'accept: application/json' \
  -H 'x-api-key: ...' \
  -H 'Content-Type: application/json' \
  -d "$JSON_PAYLOAD"

Subscribe to Keun's newsletter and stay updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox. It's free!
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!