Docker Jenkins Pipeline配置ssh key从gitlab拉取代码

时间:2024-03-24 08:58:27

1. 环境

Jenkins是k8s使用yaml运行的

[[email protected] ~]# kubectl get pods -n kube-ops
NAME                        READY     STATUS    RESTARTS   AGE
jenkins2-754c69b9c6-pr6lm   1/1       Running   0          47m

[[email protected] ~]# docker ps 
CONTAINER ID        IMAGE                   COMMAND                  CREATED             STATUS              PORTS                                      NAMES
35a1313e68e2        jenkins/jenkins         "/sbin/tini -- /usr/…"   About an hour ago   Up About an hour                                               k8s_jenkins_jenkins2-754c69b9c6-pr6lm_kube-ops_28b4a548-0682-11e9-9390-000c29770a60_0

2. 进入容器生成ssh key

[[email protected] ~]# docker exec -it 35a1313e68e2 /bin/bash
#没有.ssh文件夹
[email protected]:/$ cd ~/.ssh
bash: cd: /var/jenkins_home/.ssh: No such file or directory
[email protected]:/$ mkdir ~/.ssh
[email protected]:/$ cd ~/.ssh
[email protected]:~/.ssh$ ssh-******
Generating public/private rsa key pair.
Enter file in which to save the key (/var/jenkins_home/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /var/jenkins_home/.ssh/id_rsa.
Your public key has been saved in /var/jenkins_home/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:4dgUTYXOJnAZqn373B7upua9c2L9cngoi264fa/zUKk [email protected]
The key's randomart image is:
+---[RSA 2048]----+
|        o=.o.    |
|      ..o.o      |
|      .ooo       |
|     o =..+    . |
|    . o So    o  |
|       . .   o   |
|        ..  E. o |
|        .+o=Oo* o|
|        .*OBX%o=.|
+----[SHA256]-----+
[email protected]:~/.ssh$ ls
id_rsa	id_rsa.pub

#查看公钥(配置在gitlab的ssh key上才能拉取代码)
[[email protected] ~]# cat id_rsa.pub 
ssh-rsa AAAAB3NzaC1ycxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxnOyR [email protected]

3. 配置到gitlab

Docker Jenkins Pipeline配置ssh key从gitlab拉取代码

4. Jenkins创建任务测试

测试前要安装Maven插件
Docker Jenkins Pipeline配置ssh key从gitlab拉取代码
配置maven名称
Docker Jenkins Pipeline配置ssh key从gitlab拉取代码
创建测试流水线
Docker Jenkins Pipeline配置ssh key从gitlab拉取代码
流水线脚本

#!groovy
pipeline {
	agent any
	
	environment {
		REPOSITORY="ssh://[email protected]:2222/www19930327/imooc-videos-dev.git"
	}

	tools {
       		 //工具名称必须在Jenkins 管理Jenkins → 全局工具配置中预配置。
        		maven 'M3'
    	}
	
	stages {
		stage('获取代码') {
			steps {
				echo "start fetch code from git:${REPOSITORY}"
				deleteDir()
				git "${REPOSITORY}"
			}
		}
	}
}

Docker Jenkins Pipeline配置ssh key从gitlab拉取代码
立即构建,失败
Docker Jenkins Pipeline配置ssh key从gitlab拉取代码
解决办法

[[email protected] ~]# docker exec -it 35a1313e68e2 /bin/bash
[email protected]:/$ cd ~/.ssh
[email protected]:~/.ssh$ ls
id_rsa	id_rsa.pub  known_hosts
[email protected]:~/.ssh$ git ls-remote -h ssh://[email protected]:2222/www19930327/imooc-videos-dev.git HEAD

构建成功
Docker Jenkins Pipeline配置ssh key从gitlab拉取代码