k8s jenkins主从设置
k8s jenkins主从设置
·
系统管理--系统配置--节点管理--Configure Clouds--配置集群
Kubernetes
- 名称:kubernetes-prod
- Kubernetes 地址:https://kubernetes.default.svc.cluster.local
- Use Jenkins Proxy:不勾选
- Kubernetes 服务证书 key:空
- 禁用 HTTPS 证书检查:不勾选
- Kubernetes 命名空间:空
- 凭据:无
- WebSocket:不勾选
- Direct Connection:不勾选
- Jenkins 地址:http://jenkins.dayi-devops.svc.cluster.local:8080/jenkins
- Jenkins 通道:空
- Connection Timeout:30
- Read Timeout:60
- 容器数量:20
- Pod Labels:
- Pod Label:
- 键:jenkins
- 值:jnlp
- 连接 Kubernetes API 的最大连接数:32
- Seconds to wait for pod to be running:600
- Pod Label:
- Pod Templates
- Pod Template
- 名称:jnlp-slave
- 命名空间:prod
- 标签列表:jnlp-slave
- 用法:只允许运行绑定到这台机器的Job
- 父级的 Pod 模板名称:为空
- Pod Template
- 容器列表
- Container Template
- 名称:jnlp
- Docker 镜像:wanyan.cn-hangzhou.cr.aliyuncs.com/yyh-prod/jenkins-jnlp:v2
- 总是拉取镜像:不勾选
- 工作目录:/home/jenkins
- 运行的命令:jenkins-agent
- 命令参数:为空
- 分配伪终端:勾选
- Environment Variables:(默认配置不操作)
- 环境变量
- 卷(Host Path Volume)
- 主机路径:/var/run/docker.sock
- 挂载路径:/var/run/docker.sock
- Host Path Volume
- 主机路径:/usr/bin/docker
- 挂载路径:/usr/bin/docker
- Host Path Volume
- 主机路径:/etc/localtime
- 挂载路径:/etc/localtime
- Persistent Volume Claim
- 申明值:webapps-data
- 只读:不勾选
- 挂载路径:/data/webapps
- 注解
- Concurrency Limit:空
- Pod Retention:Default
- 代理的空闲存活时间(分):空
- Pod 寿命(秒):空
- 连接 Jenkins 的超时时间(秒):1000
- Raw YAML for the Pod:空
- Yaml merge strategy:Override
- Show raw yaml in console:勾选
- 卷(Host Path Volume)
- 拉取镜像的 Secret
- Image Pull Secret
- 名称:aliregistry-secret
- Service Account:jenkins-prod
- Run As User ID:0 (root用户启动)
- Run As Group ID:为空
- Supplemental Groups:为空
- Host Network:不勾选
- 节点选择器:为空
- 工作空间卷:Persistent Volume Claim Workspace Volume
- 声明值:jenkins-jnlp-local
- 只读:不勾选
- 节点属性
- 工具位置:不勾选
- Image Pull Secret
- Container Template
jenkins前端应用配置
- 参数化构建过程
- Git参数
- 名称:Branch
- 描述:选择发布的分支
- 参数类型:分支或标签
- 默认值:master
- 选项参数
- 名称:Namespace
- 选项:prod
- 描述:选择发布环境
- 选项参数
- 名称:deploy_env
- 选项:deploy
- 描述:deploy发布新代码
- Git参数
Pipeline script
脚本
// 项目
// 需要修改前端项目部署的目录
def project_webdir = "channelcenter"
// 需要修改对应服务的git地址
def git_address = "http://gitlab.wanyan.com/web/channel-center-web.git"
// 认证
def git_auth = "gitlab-creds" //git login auth
pipeline {
agent { label 'jnlp-slave' }
parameters {
gitParameter branch: '', branchFilter: '.*', defaultValue: 'master', description: '选择发布的分支', name: 'Branch', quickFilterEnabled: false, selectedValue: 'NONE', sortMode: 'NONE', tagFilter: '*', type: 'PT_BRANCH_TAG' //PT_BRANCH_TAG获取分支和TAG
//gitParameter branch: '', branchFilter: '.*', defaultValue: 'master', description: '选择发布的分支', name: 'Branch', quickFilterEnabled: false, selectedValue: 'NONE', sortMode: 'NONE', tagFilter: '*', type: 'PT_BRANCH' //PT_BRANCH只获取分支
choice (choices: ['prod'], description: '选择发布环境', name: 'Namespace')
choice choices: ['deploy'], description: '''deploy发布新代码''', name: 'deploy_env'
}
stages {
stage('拉取代码'){
steps {
//build quietPeriod: 3, job: 'yyh_devops'
checkout([$class: 'GitSCM',
branches: [[name: "${params.Branch}"]],
doGenerateSubmoduleConfigurations: false,
extensions: [], submoduleCfg: [],
userRemoteConfigs: [[credentialsId: "${git_auth}", url: "${git_address}"]]
])
}
}
stage('代码编译'){
when { environment name: 'deploy_env', value: 'deploy' }
steps {
sh """
cnpm install --unsafe-perm --registry=https://registry.npm.taobao.org
cnpm run build:prod
pwd
"""
}
}
stage('部署') {
when { environment name: 'deploy_env', value: 'deploy' }
steps {
sh """
rsync -avz --delete dist/ /data/webapps/${project_webdir}
pwd
"""
}
}
}
}
jenkins后端应用配置
- 参数化构建过程
- Git参数
- 名称:Branch
- 描述:选择发布的分支
- 参数类型:分支或标签
- 默认值:master
- 选项参数
- 名称:Namespace
- 选项:prod
- 描述:选择发布环境
- 选项参数
- 名称:deploy_env
- 选项:deploy or rollback
- 描述:deploy发布新代码rollback回滚
- 字符参数
- 名称:version
- 默认值:0
- 描述:选择回滚版本号
- 清除空白字符:不勾选
- Git参数
Pipeline script
pipeline {
agent { label 'jnlp-slave' }
environment {
// 公共
registry = "wanyan.cn-hangzhou.cr.aliyuncs.com"
// 项目
project = "yyh-prod"
app_name = "${JOB_NAME}"
workdir = "/home/dayiops/${JOB_NAME}"
image_name = "${registry}/${project}/${app_name}:${BUILD_NUMBER}"
// 需要修改对应服务的端口号
app_port = "8890"
// 需要修改对应服务的git地址
git_address = "http://gitlab.wanyan.com/basic-service/auth-center.git"
// 需要修改微服务对应的gitlab群组
git_groups = "basic-service"
// 回滚镜像的版本
rollback_image_name = "${registry}/${project}/${app_name}:${version}"
// 认证
docker_registry_auth = "jenkins-aliregistry-creds" //Harbor login auth
git_auth = "gitlab-creds" //git login auth
}
parameters {
gitParameter branch: '', branchFilter: '.*', defaultValue: 'master', description: '选择发布的分支', name: 'Branch', quickFilterEnabled: false, selectedValue: 'NONE', sortMode: 'NONE', tagFilter: '*', type: 'PT_BRANCH_TAG' //PT_BRANCH_TAG获取分支和TAG
//gitParameter branch: '', branchFilter: '.*', defaultValue: 'master', description: '选择发布的分支', name: 'Branch', quickFilterEnabled: false, selectedValue: 'NONE', sortMode: 'NONE', tagFilter: '*', type: 'PT_BRANCH' //PT_BRANCH只获取分支
//choice (choices: ['1', '3', '5', '7'], description: '副本数', name: 'ReplicaCount')
choice (choices: ['prod'], description: '选择发布环境', name: 'Namespace')
choice choices: ['deploy', 'rollback'], description: '''deploy发布新代码rollback回滚''', name: 'deploy_env'
string defaultValue: '0', description: '选择回滚版本号', name: 'version', trim: false
}
stages {
stage('拉取代码'){
steps {
build quietPeriod: 3, job: 'yyh_devops'
checkout([$class: 'GitSCM',
branches: [[name: "${params.Branch}"]],
doGenerateSubmoduleConfigurations: false,
extensions: [], submoduleCfg: [],
userRemoteConfigs: [[credentialsId: "${git_auth}", url: "${git_address}"]]
])
}
}
stage('代码编译'){
when { environment name: 'deploy_env', value: 'deploy' }
steps {
sh """
mvn clean package -Dmaven.test.skip=true -U
"""
}
}
stage('构建镜像'){
when { environment name: 'deploy_env', value: 'deploy' }
steps {
dir("${WORKSPACE}/${JOB_NAME}") {
withCredentials([usernamePassword(credentialsId: "${docker_registry_auth}", passwordVariable: 'password', usernameVariable: 'username')]) {
sh """
echo '
FROM ${registry}/yyh/centos-jdk:8-jre
LABEL author='yhh'
ENV PROJECT="${JOB_NAME}"
#ENV JAVA_OPTS="-Dspring.profiles.active=production -server -Xms1024M -Xmx1024M "
ENV TZ=Asia/Shanghai
ENV LANG=en_US.UTF-8
RUN mkdir /home/dayiops/${JOB_NAME} -p
WORKDIR /home/dayiops/${JOB_NAME}
ADD target/${JOB_NAME}.jar ${workdir}/
EXPOSE ${app_port}/tcp
ENTRYPOINT ["java","-Dspring.profiles.active=k8s${Namespace}","-Dmaven.wagon.http.ssl.insecure=true","-Dmaven.wagon.http.ssl.allowall=true","-server","-Xms1024M","-Xmx1024M","-XX:+HeapDumpOnOutOfMemoryError","-jar","${JOB_NAME}.jar"]
' > Dockerfile
docker login -u ${username} -p '${password}' ${registry}
docker build -t ${image_name} .
docker push ${image_name}
"""
}
}
}
}
stage('部署到K8S平台'){
when { environment name: 'deploy_env', value: 'deploy' }
steps {
dir("$WORKSPACE/../yyh_devops/${git_groups}/${JOB_NAME}") {
sh """
sed -i 's#{APP_NAME}#${JOB_NAME}#g' k8s-deployment.yaml
sed -i 's#{APP_PORT}#${app_port}#g' k8s-deployment.yaml
sed -i 's#{IMAGE_NAME}#${image_name}#' k8s-deployment.yaml
sed -i 's#{NAME_SPACE}#${Namespace}#' k8s-deployment.yaml
sed -i 's#{ADD_ENV_LABEL}#${Namespace}#' k8s-deployment.yaml
kubectl apply -f k8s-deployment.yaml
"""
//kubernetesDeploy configs: 'k8s-deployment.yaml'
}
}
}
stage("服务启动检查"){
when { environment name: 'deploy_env', value: 'deploy' }
steps {
sleep 63
timeout(time: 31, unit: 'SECONDS') {
waitUntil {
script {
def podstatus = sh (
returnStdout: true,
//script: "kubectl get deployment -n test | grep auth-center-api | awk \'{print \$1}\'"
script: "kubectl get replicasets -n ${Namespace} |grep ${JOB_NAME} | awk \'{if (\$2 >=1 && \$4 == 0) print \"podnotready\"}\'"
)
def notrun_podname = sh (
returnStdout: true,
//script: "kubectl get deployment -n test | grep ${JOB_NAME} | awk \'{print \$1}\'"
script: "kubectl get pod -n ${Namespace} |grep ${JOB_NAME} |awk \'{if (\$2 == \"0/1\") print \$1}\'"
)
podstatus = podstatus.trim()
notrun_podname = notrun_podname.trim()
echo "******** ${JOB_NAME}服务启动状态为 ${podstatus} ********"
if( podstatus == "podnotready" ) {
//echo "${JOB_NAME} 服务启动失败 重新检测服务运行态中..."
echo "服务启动状态检查中..."
sleep 10
return false
} else {
echo "******** ${JOB_NAME} 服务启动成功... ********"
return true
}
}
}
}
}
}
stage('回滚指定的镜像'){
when { environment name: 'deploy_env', value: 'rollback' }
steps {
dir("$WORKSPACE/../yyh_devops/${git_groups}/${JOB_NAME}") {
sh """
sed -i 's#{APP_NAME}#${JOB_NAME}#g' k8s-deployment.yaml
sed -i 's#{APP_PORT}#${app_port}#g' k8s-deployment.yaml
sed -i 's#{IMAGE_NAME}#${rollback_image_name}#' k8s-deployment.yaml
sed -i 's#{NAME_SPACE}#${Namespace}#' k8s-deployment.yaml
sed -i 's#{ADD_ENV_LABEL}#${Namespace}#' k8s-deployment.yaml
kubectl apply -f k8s-deployment.yaml
"""
//kubernetesDeploy configs: 'k8s-deployment.yaml'
}
}
}
}
}
后端应用Dockerfile模板
# cat Dockerfile
FROM dayi-registry.cn-hangzhou.cr.aliyuncs.com/yyh/centos-jdk:8-jre
LABEL author=yhh
ENV PROJECT="gateway"
#ENV JAVA_OPTS="-Dspring.profiles.active=production -server -Xms1024M -Xmx1024M "
ENV TZ=Asia/Shanghai
RUN mkdir /home/dayiops/gateway -p
WORKDIR /home/dayiops/gateway
ADD target/gateway.jar /home/dayiops/gateway/
EXPOSE 8081/tcp
ENTRYPOINT ["java","-Dspring.profiles.active=k8sprod","-server","-Xms2048M","-Xmx2048M","-XX:+HeapDumpOnOutOfMemoryError","-jar","gateway.jar"]
gitlab k8s模板
#kubernetes/yyh-devops/BC/connector-api/k8s-deployment.yaml
---
apiVersion: v1
kind: Service
metadata:
name: {APP_NAME}
namespace: {NAME_SPACE}
labels:
app: {APP_NAME}
env: {ADD_ENV_LABEL}
spec:
ports:
- name: http
port: {APP_PORT}
protocol: TCP
targetPort: {APP_PORT}
selector:
app: {APP_NAME}
env: {ADD_ENV_LABEL}
sessionAffinity: None
type: ClusterIP
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: {APP_NAME}
namespace: {NAME_SPACE}
labels:
app: {APP_NAME}
env: {ADD_ENV_LABEL}
spec:
replicas: 1
selector:
matchLabels:
app: {APP_NAME}
env: {ADD_ENV_LABEL}
strategy:
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
type: RollingUpdate
template:
metadata:
labels:
app: {APP_NAME}
env: {ADD_ENV_LABEL}
spec:
imagePullSecrets:
- name: aliregistry-secret
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- podAffinityTerm:
labelSelector:
matchExpressions:
- key: app
operator: In
values:
- {APP_NAME}
topologyKey: kubernetes.io/hostname
weight: 100
containers:
- env:
- name: TZ
value: Asia/Shanghai
- name: LANG
value: en_US.UTF-8
image: {IMAGE_NAME}
imagePullPolicy: IfNotPresent
name: {APP_NAME}
ports:
- name: http
containerPort: {APP_PORT}
protocol: TCP
readinessProbe:
failureThreshold: 2
initialDelaySeconds: 30
periodSeconds: 10
successThreshold: 1
tcpSocket:
port: {APP_PORT}
timeoutSeconds: 2
livenessProbe:
failureThreshold: 2
initialDelaySeconds: 30
periodSeconds: 10
successThreshold: 1
tcpSocket:
port: {APP_PORT}
timeoutSeconds: 2
resources:
limits:
cpu: 1000m
memory: 1024Mi
requests:
cpu: 200m
memory: 256Mi
volumeMounts:
- mountPath: /data/logs
name: logs
- mountPath: /etc/localtime
name: localtime
readOnly: true
dnsPolicy: ClusterFirstWithHostNet
restartPolicy: Always
securityContext:
fsGroup: 2049
runAsGroup: 2049
runAsUser: 2049
volumes:
- emptyDir: {}
name: logs
- hostPath:
path: /etc/localtime
type: File
name: localtime
依赖任务配置(每次后端发布都会执行这个任务)
名称:yyh_devops
Pipeline yyh_devops
Pipeline script
node('jnlp-slave') {
stage('Git Clone') {
git credentialsId: 'gitlab-creds', url: 'http://gitlab.taeteadata.com/kubernetes/yyh-devops-prod.git'
}
}
更多推荐
已为社区贡献31条内容
所有评论(0)