-
Notifications
You must be signed in to change notification settings - Fork 2
/
Jenkinsfile
170 lines (140 loc) · 5.1 KB
/
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#!groovy
def git_url = '[email protected]:Constantin07/test.git'
def plan_exitcode
def apply_exitcode
def aborted = false
// Get comment of last commit
def get_comment() {
def f = 'output_file.txt'
def status = sh(returnStatus: true, script: "git log -1 --pretty=%B > ${f}")
if (status != 0) {
currentBuild.result = 'FAILED'
error "Failed to read last commit's comment"
} else {
return readFile(f).trim()
}
sh "rm ${f}"
}
node {
// Set path to terraform
env.PATH = "/usr/local/bin:${env.PATH}"
properties(
[buildDiscarder(logRotator(artifactDaysToKeepStr: '', numToKeepStr: '10')),
[$class: 'GithubProjectProperty',
projectUrlStr: 'https://github.com/Constantin07/test'],
pipelineTriggers([pollSCM('''TZ=Europe/London
* * * * *''')]),
// Allow only one change at a time
disableConcurrentBuilds()
])
timestamps {
stage('Checkout'){
checkout([
$class: 'GitSCM',
branches: [[name: '*/master']],
doGenerateSubmoduleConfigurations: false,
extensions: [[$class: 'CleanBeforeCheckout']],
userRemoteConfigs: [[credentialsId: 'Git', url: git_url]]
])
// Add comment to build description
currentBuild.description = get_comment()
}
stage('Get secrets'){
sh 'git crypt unlock'
}
dir(path: './terraform') {
stage('Validate') {
// Remove the terraform state file so we always start from a clean state
if (fileExists(".terraform/terraform.tfstate")) {
sh '''rm -rf .terraform/terraform.tfstate'
rm -f plan.out'
rm -f terraform.tfstate.backup
'''
}
ansiColor('xterm') {
//Print terraform version
sh 'terraform --version'
//Rewrite in cannonical format
sh 'terraform fmt -list=true -diff=false'
withCredentials([[$class: 'AmazonWebServicesCredentialsBinding',
accessKeyVariable: 'AWS_ACCESS_KEY_ID',
secretKeyVariable: 'AWS_SECRET_ACCESS_KEY',
credentialsId: 'Amazon Credentials']]) {
echo 'Initialize S3 backend'
retry(3){
sh 'terraform init -get=true -force-copy'
}
}
//Load modules
sh 'terraform get -update=true'
//Syntax validation
sh 'terraform validate'
}
}
milestone label: 'Validate'
stage(name: 'Plan', concurency: 1) {
ansiColor('xterm') {
withCredentials([[$class: 'AmazonWebServicesCredentialsBinding',
accessKeyVariable: 'AWS_ACCESS_KEY_ID',
secretKeyVariable: 'AWS_SECRET_ACCESS_KEY',
credentialsId: 'Amazon Credentials']]) {
plan_exitcode = sh(returnStatus: true,
script: 'terraform plan -detailed-exitcode -out=plan.out')
}
echo "Terraform plan exit code: ${plan_exitcode}"
if(plan_exitcode == 0) {
echo 'No changes to apply.'
currentBuild.result = 'SUCCESS'
}
if(plan_exitcode == 1) {
// Error (send a message via HipChat)
echo 'Plan Failed.'
currentBuild.result = 'FAILURE'
}
if(plan_exitcode == 2) {
// Succeeded, there is a diff to apply (send a message via HiChat)
stash name: "plan", includes: "plan.out"
echo 'Plan Awaiting Approval.'
}
}
}
milestone label: 'Plan'
if(plan_exitcode == 2) {
stage(name: 'Approve', concurency: 1) {
try {
timeout(time: 3, unit: 'MINUTES') {
input(message: 'Please review the plan. Do you want to apply?', ok: 'Apply', submitter: 'admin')
}
} catch(err) {
aborted = true
echo 'Timeout reached or user aborted. Plan Discarded.'
currentBuild.result = 'ABORTED'
}
}
if(aborted == true) {
return
}
stage(name: 'Apply', concurency: 1) {
unstash 'plan'
ansiColor('xterm') {
withCredentials([[$class: 'AmazonWebServicesCredentialsBinding',
accessKeyVariable: 'AWS_ACCESS_KEY_ID',
secretKeyVariable: 'AWS_SECRET_ACCESS_KEY',
credentialsId: 'Amazon Credentials']]) {
apply_exitcode = sh(returnStatus: true, script: 'terraform apply -auto-approve plan.out')
}
}
if(apply_exitcode == 0) {
echo "Changes Applied."
} else {
echo 'Apply Failed.'
currentBuild.result = 'FAILURE'
}
}
}
stage(name: 'Cleanup', concurency: 1) {
cleanWs()
}
}
}
}