This repository has been archived by the owner on Nov 9, 2018. It is now read-only.
/
example-Jenkinsfile
72 lines (67 loc) · 3.33 KB
/
example-Jenkinsfile
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/env groovy
podTemplate(label: 'my-build-pod', containers: [
containerTemplate(name: 'jnlp', image: 'jenkinsci/jnlp-slave:alpine', alwaysPullImage: true),
// This image has kubectl installed for deployments
containerTemplate(name: 'kubectl', image: 'lachlanevenson/k8s-kubectl:v1.7.6', ttyEnabled: true, command: 'cat'),
// A docker container to build the image
containerTemplate(name: 'docker', image: 'docker', command: 'cat', ttyEnabled: true)]) {
node ('my-build-pod') {
def project = 'project'
def appName = 'sample-app'
def imageTag = "quay.io/${project}/${appName}:${env.BRANCH_NAME}.${env.BUILD_NUMBER}"
// Store ssh credentials in Jenkins, replace GITHUB_URL with a GitHub Repo
git branch: "${env.BRANCH_NAME}", credentialsId: "{{JENKINS_CREDENTIALS}}", url: '{{GITHUB_URL}}'
stage 'Build docker image'
container('docker') {
sh("docker build -t ${imageTag} .")
}
stage 'Run Go tests'
container('docker') {
sh("docker run ${imageTag} go test")
}
stage 'Push image to the registry'
container('docker') {
// Store these credentials in Jenkins
withCredentials([[
$class: 'UsernamePasswordMultiBinding',
credentialsId: '{{DOCKER_CREDENTIALS}}',
usernameVariable: 'USERNAME',
passwordVariable: 'PASSWORD'
]]) {
sh """
docker login -u $USERNAME -p $PASSWORD quay.io
docker push ${imageTag}
"""
}
}
stage 'Deploy app'
container('kubectl') {
// This uses a kubeconfig file stored as a Jenkins secret
withCredentials([[
$class: 'FileBinding',
credentialsId: 'k8s-credentials',
variable: 'KUBECONFIG'
]]){
switch (env.BRANCH_NAME)
{
// Deploy to production
case "master":
sh("kubectl --kubeconfig=$KUBECONFIG --namespace={{APP_NAMESPACE}} apply -f ./services.yaml")
sh("kubectl --kubeconfig=$KUBECONFIG --namespace={{APP_NAMESPACE}} apply -f ./deployment.yaml")
break
// Deploy to a development environment
default:
// Create namespace if it doesn't exist
sh("kubectl --kubeconfig=$KUBECONFIG get ns ${env.BRANCH_NAME} || kubectl --kubeconfig=$KUBECONFIG create ns ${env.BRANCH_NAME}")
// Don't use public load balancing for development branches
sh("sed -i.bak 's#LoadBalancer#ClusterIP#' ./services.yaml")
sh("sed -i.bak 's#quay.io/${project}/${appName}:1.0.0#${imageTag}#' ./deployment.yaml")
sh("kubectl --kubeconfig=$KUBECONFIG --namespace=${env.BRANCH_NAME} apply -f ./services.yaml")
sh("kubectl --kubeconfig=$KUBECONFIG --namespace=${env.BRANCH_NAME} apply -f ./deployment.yaml")
echo 'To access the environment run `kubectl proxy`'
echo "Then access the service via http://localhost:8001/api/v1/proxy/namespaces/${env.BRANCH_NAME}/services/${appName}:80/"
}
}
}
}
}