-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJenkinsfile
84 lines (83 loc) · 2.45 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
def AWS_REGION = 'us-west-1'
def AWS_CRED_NAME = 'aws-credentials'
def BUILD_DATE = new Date(currentBuild.startTimeInMillis).format("yyyy-MM-dd-HH-mm")
def AMI_IMAGE_ID
pipeline {
agent any
stages {
stage('Validate Packer and Terraform configs') {
when {
branch 'master'
}
steps {
script {
withCredentials([[
$class: 'AmazonWebServicesCredentialsBinding',
credentialsId: "${AWS_CRED_NAME}",
accessKeyVariable: 'AWS_ACCESS_KEY',
secretKeyVariable: 'AWS_SECRET_KEY'
]]) {
sh "env"
sh "packer validate packer/ami-build.json"
sh "cd terraform && terraform init"
}
}
}
}
stage('Build Packer image') {
when {
branch 'master'
}
steps {
script {
withCredentials([[
$class: 'AmazonWebServicesCredentialsBinding',
credentialsId: "${AWS_CRED_NAME}",
accessKeyVariable: 'AWS_ACCESS_KEY',
secretKeyVariable: 'AWS_SECRET_KEY'
]]) {
sh(
script: """
/usr/bin/packer build -var 'ami_uniq_id=${BUILD_DATE}' \
-var 'aws_access_key=${AWS_ACCESS_KEY}' \
-var 'aws_secret_key=${AWS_SECRET_KEY}' \
-machine-readable packer/ami-build.json | tee build.log
""")
AMI_IMAGE_ID = sh(
script: """
grep 'artifact,0,id' build.log | cut -d, -f6 | cut -d: -f2
""",
returnStdout: true).trim()
}
}
}
}
stage('Deploy Infrastructure') {
when {
branch 'master'
}
steps {
script {
withCredentials([[
$class: 'AmazonWebServicesCredentialsBinding',
credentialsId: "${AWS_CRED_NAME}",
accessKeyVariable: 'AWS_ACCESS_KEY',
secretKeyVariable: 'AWS_SECRET_KEY'
]]) {
sh """
cd terraform
terraform init
terraform plan -var 'ami_image_id=${AMI_IMAGE_ID}'
terraform apply -auto-approve -var 'ami_image_id=${AMI_IMAGE_ID}'
"""
}
}
}
}
}
post {
always {
deleteDir()
}
}
}