准备一个 Service Account,对目标 cluster 具有k8s admin权限,以便部署。
防火墙已开通 Jenkins 出站到Docker hub,方便 push/pull image
防火墙已开通 Jenkins 到 目标 cluster,以便部署。
插件安装
Kubernetes Plugin
Google Kubernetes Engine Plugin (我的例子是部署到 GKE cluster)
Jenkins 配置
Manage Nodes and Clouds
1. Go to `Manage Jenkins` –> `Manage Nodes and Clouds`2. Click `Configure Clouds`3. Add a new Cloud select `Kubernetes`4. Click `Kubernetes Cloud Detail5. Enter `jenkins` namespace in `Kubernetes Namespace` field6. Click `Test Connection` --> result show `Connected to Kubernetes v1.22.12-gke.2300`7. Click `Save`8. Enter `http://jenkins-service.jenkins.svc.cluster.local:8080` in `Jenkins URL` field9. Enter `jenkins-agent:50000` in `Jenkins tunnel` field10. Click `Add Pod Template` then `Pod Template Details`
11. Input `Name`=`jenkins-agent`, `Namespace`=`jenkins`, `Labels`=`kubeagent`
12. (Optional) 如果不添加 container template, the Jenkins Kubernetes plugin will use the default JNLP image from the Docker hub to spin up the agents.如果你要覆盖默认的jnlp image 可以 Click `Add Container` to add Container Template,输入 `Name`=`jnlp`, `Docker Image`=`your_registry/jenkins/inbound-agent:4.11-1-jdk11`
Ensure that you remove the sleep and 9999999 default argument from the container template.
Manage Credentials
Add `Usernames with password` for docker hub account/pwd,比如 wade_test_dockerhub
Add `Google Service Account from private key` 比如 gcp_sa_json_key
Go to Jenkins home –> New Item and create a freestyle project,命名为 quick-test在 job description 部分, add the label `kubeagent` for `Restrict where this project can be run`.
这个label 和我们上面创建 pod template时用的label一致. 这样的话 Jenkins就知道用哪个 pod template 作为 agent container.
随便添加一个shell 作为build steps
点Build Now
查看Console Output
Agent jenkins-agent-l7hw9 is provisioned from template jenkins-agent
......
Building remotely on jenkins-agent-l7hw9 (kubeagent) in workspace /home/jenkins/agent/workspace/quick-test
containers: # list of containers that you want present for your build, you can define a default container in the Jenkinsfile
- name: maven
image: maven:3.5.4-jdk-8-slim
command: ["tail", "-f", "/dev/null"] # this or any command that is bascially a noop is required, this is so that you don't overwrite the entrypoint of the base container
imagePullPolicy: Always # use cache or pull image for agent
resources: # request and limit the resources your build contaienr