티스토리 뷰

ssh 명령을 jenkins 상에서 사용할일이 다수 있는 상황에서 ssh 를 pipeline을 통해 어떻게 사용할수 있는지에 대하여 알아보도록 하자.

 

ssh plugin을 사용하기 위해서는 다음과 같은 plugin 설치가 필요하다.
(이름은 ssh pipeline steps로 검색된다.)

plugin 설치가 완료된후 ssh key를 등록한다.

배포되어질 서버에 ssh key를 ssh-copy-id 명령을 이용하던지 아니면 기존에 가지고 있던 key파일이 있다면 해당 파일을 이용하여 등록한다.

개인적으로 Passphrase(비밀번호)를 지정하지 않았기에 Passpharse는 빈칸으로 생성하였다.

이후 생성된 credential(ID : ec2-user-server)을 사용하여 pipeline을 작성해보자.

제목에서 언급되었듯이 pipeline은 scripted 방식으로 작성한다.

podTemplate() {
    node() {
        stage('clone the source codes') {
            sh 'echo "start"'
            checkout([$class: 'GitSCM', 
                    branches: [[name: '*/master']],
                    doGenerateSubmoduleConfigurations: false,
                    extensions: [],
                    submoduleCfg: [],
                    userRemoteConfigs: [[credentialsId: 'jacobbaek', refspec: '+refs/pull/*:refs/remotes/origin/pr/*', url: 'https://gitlab.com/JacobBaek/springtemplateprj.git']]])
        }
        stage('run the commands') {
            sh 'echo "done"'
        }
        withCredentials([sshUserPrivateKey(credentialsId: 'ec2-user-server', keyFileVariable: 'identity', passphraseVariable: 'passphrase', usernameVariable: 'userName')]) {
            def remote = [:]
            remote.name = "test-ssh-vm"
            remote.host = "ec2-xxx-xxx-xxx-xxx.ap-northeast-x.compute.amazonaws.com"
            remote.allowAnyHosts = true
            remote.user = userName
            remote.identityFile = identity
            //remote.passphrase = passphrase
            stage("SSH Steps Rocks!") {
                writeFile file: 'test.sh', text: 'ls'
                sshCommand remote: remote, command: 'for i in {1..5}; do echo -n \"Loop \$i \"; date ; sleep 1; done'
                sshScript remote: remote, script: 'test.sh'
                sshPut remote: remote, from: 'test.sh', into: '.'
                sshGet remote: remote, from: 'test.sh', into: 'test_new.sh', override: true
                sshRemove remote: remote, path: 'test.sh'
            }
        }
    }
}

sshUserPrivatekey 를 사용하여 remote(https://github.com/jenkinsci/ssh-steps-plugin#remote)라는 groovy 변수에 관련 정보를 추가하여 인증을 수행하게 한다.

위는 sshUserPrivatekey를 활용한 방법이며 그외에 usernamePassword, file, certificate, dockerCert등 다양한

아래는 credential을 사용하는 다양한 방법에 대하여 설명된 blog이다

sshCommand, sshScript, sshPut, sshGet 등 다양한 action을 module을 이용하여 지정할 수 있다.

'DevOps > System&Tools' 카테고리의 다른 글

How to use minio as Terraform backend  (0) 2020.05.28
Helm usage  (0) 2020.01.23
How to use GitLab API  (0) 2019.11.27
Jenkinsfile example using ssh and scp  (0) 2019.11.25
variables in Jenkinsfile  (0) 2019.11.22
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함