-
Notifications
You must be signed in to change notification settings - Fork 9
/
terraform-destroy
73 lines (68 loc) · 3.36 KB
/
terraform-destroy
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
node {
// Mark the code checkout 'Checkout'....
stage 'Checkout'
// // Get some code from a GitHub repository
git credentialsId: "${env.GITHUB_CREDENTIALS}", url: "${env.GITHUB_REPO}"
// Setup the AWS Credentials
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: "${env.AWS_CREDENTIALS}",
usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
env.AWS_ACCESS_KEY_ID = "$USERNAME"
env.AWS_SECRET_ACCESS_KEY = "$PASSWORD"
}
// Get the Terraform tool.
def tfHome = tool name: 'Terraform', type: 'com.cloudbees.jenkins.plugins.customtools.CustomTool'
env.PATH = "${tfHome}:${env.PATH}"
wrap([$class: 'AnsiColorBuildWrapper', colorMapName: 'xterm']) {
// Mark the code build 'plan'....
stage name: 'Plan', concurrency: 1
// Output Terraform version
sh "terraform --version"
//Remove the terraform state file so we always start from a clean state
if (fileExists(".terraform/terraform.tfstate")) {
sh "rm -rf .terraform/terraform.tfstate"
}
if (fileExists("status")) {
sh "rm status"
}
sh "./jenkins-init"
sh "terraform get"
sh "set +e; terraform plan -destroy -out=plan.out -var-file=environments/${env.PROJECT}/${env.PROJECT}.tfvars -detailed-exitcode; echo \$? > status"
def exitCode = readFile('status').trim()
def destroy = false
echo "Terraform Plan Exit Code: ${exitCode}"
if (exitCode == "0") {
currentBuild.result = 'SUCCESS'
}
if (exitCode == "1") {
// slackSend channel: '#ci', color: '#0080ff', message: "Plan Failed: ${env.JOB_NAME} - ${env.BUILD_NUMBER} ()"
currentBuild.result = 'FAILURE'
}
if (exitCode == "2") {
stash name: "plan", includes: "plan.out"
// slackSend channel: '#ci', color: 'good', message: "Plan Awaiting Approval: ${env.JOB_NAME} - ${env.BUILD_NUMBER} ()"
try {
input message: 'Destroy Plan?', ok: 'Destroy'
destroy = true
} catch (err) {
// slackSend channel: '#ci', color: 'warning', message: "Plan Discarded: ${env.JOB_NAME} - ${env.BUILD_NUMBER} ()"
destroy = false
currentBuild.result = 'UNSTABLE'
}
}
if (destroy) {
stage name: 'Destroy', concurrency: 1
unstash 'plan'
if (fileExists("status.destroy")) {
sh "rm status.destroy"
}
sh "set +e; terraform destroy -force -var-file=environments/${env.PROJECT}/${env.PROJECT}.tfvars; echo \$? > status.destroy"
def destroyExitCode = readFile('status.destroy').trim()
if (destroyExitCode == "0") {
// slackSend channel: '#ci', color: 'good', message: "Changes Applied ${env.JOB_NAME} - ${env.BUILD_NUMBER} ()"
} else {
// slackSend channel: '#ci', color: 'danger', message: "Destroy Failed: ${env.JOB_NAME} - ${env.BUILD_NUMBER} ()"
currentBuild.result = 'FAILURE'
}
}
}
}