본문 바로가기
  • [성공하는 개발자] - Developer
Server/AWS

[Jenkins] SSH 사용 - pipeline SSH Agent

by Sein-JH 2023. 7. 10.
728x90

 

- jenkins 관리 > Manage Credentials

- Stores scoped to Jenkins > global > Add Credntials 선택

- ssh 정보 입력

1 ) PIPELINE 에서 SSH 사용하기

env.TARGET_HOST = "hsnam@192.168.0.2"
node {
    try {
        stage('ssh-test') {
            sshagent (credentials: ['192.168.0.2-ssh']) {
                sh 'ssh -o StrictHostKeyChecking=no "uptime"'
            }
        }
    } catch (env) {
        echo 'error = ' + env
        throw env
    }
}
  • 위와 같이 pipline script를 작성하고 job을 실행 하면 해당 서버의 uptime 결과를 확인 할 수 있다.

 

2 ) PIPELINE 에서 SSH 사용하기

  1. 새로운 Item 생성 > Pipeline 선택
  2. pipeline 항목에 테스트 내용 입력 후 저장
pipeline {
    agent any
    stages {
        stage('test ssh') {
            steps {        
                sshagent (credentials: ['jenkins-ssh']) {
                sh """
                    ssh -o StrictHostKeyChecking=no ${TARGET_HOST} "pwd"
                """
                }
            }
        }

        stage('multiline ssh') {
            steps {        
                sshagent (credentials: ['jenkins-ssh']) {
                sh """
                    ssh -o StrictHostKeyChecking=no ${TARGET_HOST} '
                    rm -rf test
                    mkdir test
                    cd test
                    mkdir test2
                    cd test2
                    pwd
                    '
                """
                }
            }
        }
    }
    environment {
        TARGET_HOST = "test@192.168.0.7"
    }
}
  1. 해당 Item의 Build Now를 클릭하여 실행하여 ssh 접속 후 경로가 출력 되는 것을 확인

5. Bad configuration option 에러 발생시

  • 원인
    • Host key checking : 터미널에서 ssh 접속시 아래와 같은 메세지가 출력되는 경우 jenkins에서 접속시 발생Are you sure you want to continue connecting (yes/no)?
  • 해결
    • Host key checking을 비활성화 하는 옵션을 한번 이상 사용
    ssh -o StrictHostKeyChecking=no test@192.168.0.7 "pwd"

댓글