Programmer:)

[Jenkins] 공유 라이브러리 심화 본문

DEV/Jenkins

[Jenkins] 공유 라이브러리 심화

ryeggg 2024. 7. 16. 14:48
반응형

 

 

[Jenkins] 공유 라이브러리

파이프라인 간소화를 위해 조사하던 중 공유라이브러리 라는게 눈에 띄었다.작업진행하면서 기록남기는 중이라 삽질내용이 들어갈 수 있는 점 주의하자. step1. 일단 깃에 저장소를 하나 판다.

ryeggg.tistory.com

 

 

작업해두었던 파이프라인코드를 전부 라이브러리 호출방식으로 변경했다.

젠킨스 접속해서 코드를 하나하나 다 바꿔주는 것도 귀찮았고

이번처럼 컴퓨터 포맷후 경로 달라지는 부분과

다른 파이프라인에서 같은 기능의 job을 다시 구성해서 쓰는게 너무 불필요한 작업이라고 생각했다.

 

내 구성

-경로관리 

-실질적인 함수

 

-파이프라인

 

이렇게 총 3개로 이루어졌다.

 

경로관리

src/org/name/Paths.groovy

package org.name

class Paths{
    static final String unity_2019_4_3f1 = "/Applications/Unity/Hub/Editor/2019.4.3f1/Unity.app/Contents/MacOS/Unity"
    static final String unity_2019_4_40f1 = "/Applications/Unity/Hub/Editor/2019.4.40f1/Unity.app/Contents/MacOS/Unity"
    static final String xcode = "/Applications/Xcode.app"
    static final String desktop = "/Users/imac27/Desktop"

    static final String git_repository = "/Users/imac27/git_repository"


    static final String workspace = "/Volumes/LaCie/Jenkins/workspace"
    static final String workspace_mts = "/Users/imac27/workspace_mts"

    static final String googleDrive = "/Volumes/LaCie/Build"



    static String getWinVersionPath(String connectServer) {
        return "Application/Desktop/${connectServer}"
    }
    static String getWin32Path(String connectServer) {
        return "Application/Desktop/${connectServer}/32bit"
    }

    static String getWin64Path(String connectServer) {
        return "Application/Desktop/${connectServer}/64bit"
    }

    static String getOSXVersionPath(String connectServer) {
        return "Application/Desktop_osx/${connectServer}"
    }
    static String getOSXPath(String connectServer) {
        return "Application/Desktop_osx/${connectServer}/64bit"
    }




    static String getSshDirectoryWinVersionPath(String connectServer) {
        return "desktop/Windows/${connectServer}/Version"
    }

    static String getSshDirectoryOSXVersionPath(String connectServer) {
        return "desktop/OSX/${connectServer}/Version"
    }


    static String getSshDirectoryWin32Path(String connectServer) {
        return "desktop/Windows/${connectServer}/Client32"
    }

    static String getSshDirectoryWin64Path(String connectServer) {
        return "desktop/Windows/${connectServer}/Client"
    }

    static String getSshDirectoryOSXPath(String connectServer) {
        return "desktop/OSX/${connectServer}/Client"
    }




    static String getAndroidResourcePath(String target, String connectServer, String company) {
        return "${workspace_mts}/Application/Mobile/Build/${target}/${connectServer}/${company}"
    }

    static String getSshDirectoryAndroidResourcePath(String target, String connectServer, String company) {
        return "mobile/${target}/${connectServer}/${company}/Resource"
    }

    static String getSshDirectoryAndroidVersionPath(String target, String connectServer, String company) {
        return "mobile/${target}/${connectServer}/${company}/Version"
    }

    
}

 

 

실직적인 함수

var/shareCode.groovy

 

package vars
import org.name.Paths

def call_Paths() {
    return new Paths()
}

def info(message) {
    echo "INFO: ${message}"
}

def warning(message) {
    echo "WARNING: ${message}"
}


def download_gitlab(String repository, String branch) {
    echo "download_gitlab ${branch}"

    script{
            dir(repository) {
                git branch: "${branch}", url: 'git@git.~~~.git'
            }
        }
}

//폴더 삭제
def cleanFolders(String pipelineName) {
    echo "Folder ReFactoring"
    def paths = new Paths()

    sh (script : """
    if [ -e ${paths.workspace}/${pipelineName}/Application/Desktop/Build ]; then
       rm -rf ${paths.workspace}/${pipelineName}/Application/Desktop/Build
    fi
    """)
}


//unity build
def buildHTS_Win(String pipelineName, String server, String company, String at) {
    echo "buildHTS_Win ${server} ${at}"
    def paths = new Paths()

    sh (script : """
    ${paths.unity_2019_4_3f1} \
    -quit \
    -batchmode \
    -projectPath ${paths.workspace}/${pipelineName}/Application/Desktop \
    -executeMethod ProjectBuild.BuildStartInJenkins \
    -buildTarget StandaloneWindows \
    -ConnectServer ${server} \
    -Company ${company} \
    -at ${at}
    """)
}

//Addressable build
def buildMTS_Addressable(String target, String server, String company) {
    echo "buildMTS_Addressable ${server}"
    def paths = new Paths()

    sh (script : """
    ${paths.unity_2019_4_40f1} \
    -quit \
    -batchmode \
    -projectPath ${paths.workspace_mts}/Application/Mobile \
    -executeMethod ProjectBuild.AddressableInJenkins \
    -buildTarget ${target}\
    -ConnectServer ${server} \
    -Company ${company}
    """)
}


//SFTP 전송
def sendSFTP(String originPath, String remotePath) {
    echo "sendSFTP originPath: ${originPath} // remotePath : ${remotePath}"

    def paths = new Paths()


     script{
            sshPublisher(publishers: [sshPublisherDesc(configName: '~~', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '', execTimeout: 120000, flatten: false, 
            makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: """${remotePath}""", remoteDirectorySDF: false, 
            removePrefix: """${originPath}""", sourceFiles: """${originPath}/**""")], 
            usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
        }
}


//구글마켓 업로드
def upload_googleStore(String releaseName) {
    echo "upload_googleStore"
    script{
            androidApkUpload filesPattern: '**/*.aab', 
            googleCredentialsId: '~~~',
            releaseName: """${releaseName}""",
            rolloutPercentage: '100', trackName: 'internal'
        }
}


//텔레그램 전송
def sendTelegram(String content) {
    echo "sendTelegram"

    sh (script : """
    curl -X POST \
    -d chat_id=~~ \
    -d parse_mode=HTML \
    -d text="${content}" \
    https://api.telegram.org/bot~~~~~/sendMessage
    """)

}

 

 

파이프라인에서 활용

 

@Library('share_code') _
pipeline {
    agent any

    environment{
        //*************************중요*************************//
        //빌드 설정 값
        CONNECTSERVER = "dev" //dev , dev_st, staging , real
        BRANCH = "DEV" //DEV , DEV_ST, STAGING, REAL
        PIPELINEPROJECT_NAME = "test"
        COMPANY_NAME = "~~~"
        TARGET = "Android";

        APK = "false" //apk로 할건지 aab로 할건지
    }
    
    stages {

        stage('download gitlab project') {
            steps {
                script{
                    def paths = shareCode.call_Paths()

                    dir(paths.workspace_mts) {
                        git branch: "${BRANCH}", url: '~~~~'

                    }
                }
            }
        }


        stage('Build Addressable') {
            steps {
                script{
                    shareCode.buildMTS_Addressable(env.TARGET, env.CONNECTSERVER, env.COMPANY_NAME)
                }
            }
        }

        
        stage('SFTP_Addressable') {
            when{
                environment name : "CONNECTSERVER", value : "dev"
            }
            steps {
                script{
                    def paths = shareCode.call_Paths()

                    originPath = "${env.COMPANY_NAME}"
                    echo "origin path: ${originPath}"

                    def remotePath = paths.getSshDirectoryAndroidResourcePath(env.TARGET, env.CONNECTSERVER, env.COMPANY_NAME)
                    echo "remote path: ${remotePath}"

                    shareCode.sendSFTP(originPath, remotePath)
                }
            }
        }

        
        stage('Build AAB') {
            when{
                environment name : "APK", value : "false"
            }
            steps {
                script{
                    shareCode.buildMTS_Android(env.TARGET, env.CONNECTSERVER, env.COMPANY_NAME, "64")
                }
            }
        }

       
        stage('Upload GooglePlayStore DEV') {
            when{
                allOf{
                    environment name : "APK", value : "false"
                    environment name : "CONNECTSERVER", value : "dev"
                }
            }
            steps {
                script{
                    shareCode.upload_googleStore("~~~")
                }
            }
        }

       
        stage('send telegram'){
            steps {
                script{
                    shareCode.sendTelegram("안드로이드 빌드가 완료되었습니다.")
                }
            }
        }
        
    }
}

 

 

이런식으로 활용했다. :)

반응형

'DEV > Jenkins' 카테고리의 다른 글

[Jenkins] Telegram 연동하기  (0) 2024.07.12
[Jenkins] 공유 라이브러리  (0) 2024.07.11
[Jenkins] Home Directory 변경하기  (0) 2024.07.10
[Jenkins] mac homebrew 이용 remove  (0) 2024.02.19
[Unity] CMD로 Build 하는 방법  (0) 2023.01.13
Comments