-
Notifications
You must be signed in to change notification settings - Fork 3
/
CloudFormation.scala
245 lines (210 loc) · 9.04 KB
/
CloudFormation.scala
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package com.github.tptodorov.sbt.cloudformation
import java.io.FileNotFoundException
import java.util
import com.amazonaws.auth.{AWSCredentials, DefaultAWSCredentialsProviderChain}
import com.amazonaws.regions._
import com.amazonaws.services.cloudformation.AmazonCloudFormationClient
import com.amazonaws.services.cloudformation.model._
import sbt.Keys._
import sbt._
import scala.collection.JavaConverters._
import scala.language.implicitConversions
import scala.collection.immutable.Iterable
import scala.util.{Failure, Try}
object CloudFormation extends AutoPlugin {
object autoImport {
lazy val Production = config("production")
lazy val Staging = config("staging")
//Keys
type Parameters = Map[String, String]
type Tags = Map[String, String]
// for all configurations
val awsCredentials = taskKey[AWSCredentials]("AWS credentials")
val templatesSourceFolder = settingKey[File]("folder where CloudFormation templates are")
val templates = settingKey[Seq[File]]("template sources")
// in each configuration
val stackTemplateFile = taskKey[File]("default template to use for this configuration")
val stackTemplate = taskKey[String]("content of default template to use for this configuration")
val stackParams = taskKey[Parameters]("Parameters applied to the template for this configuration")
val stackTags = settingKey[Tags]("Tags of this stack")
val stackCapabilities = settingKey[Seq[String]]("The list of capabilities that you want to allow in the stack . E.g.[CAPABILITY_IAM]")
val stackRegion = settingKey[String]("The region where the stacks are deployed. E.g. eu-west-1 ")
val stackName = settingKey[String]("stack name")
// stack operations
val stackValidate = taskKey[Seq[File]]("validate templates")
val stackStatus = taskKey[Option[String]]("describe stack status")
val stackWait = taskKey[Option[String]]("evaluates the stack until it becomes COMPLETED or FAILED, returns last status")
val stackDescribe = taskKey[Option[Stack]]("describe stack completely")
val stackCreate = taskKey[String]("create a stack and returns its stackId")
val stackDelete = taskKey[Unit]("delete a stack")
val stackUpdate = taskKey[String]("update a stack")
val stackClient = taskKey[AmazonCloudFormationClient]("AWS CloudFormation Client")
}
import autoImport._
private lazy val awsCredentialsProvider = new DefaultAWSCredentialsProviderChain()
override def trigger = allRequirements
override lazy val projectSettings = {
defaultSettings
}
lazy val validationSettings = Seq(
templatesSourceFolder := {
baseDirectory.value / "src/main/aws"
},
templates := {
val templates = templatesSourceFolder.value ** GlobFilter("*.template")
templates.get
},
awsCredentials := {
awsCredentialsProvider.getCredentials
},
stackValidate := {
def validateTemplate(client: AmazonCloudFormationClient, log: Logger)(template: sbt.File): (File, Try[List[String]]) = {
(template, Try {
val request: ValidateTemplateRequest = new ValidateTemplateRequest()
request.setTemplateBody(IO.read(template))
val result = client.validateTemplate(request)
log.debug(s"result from validating $template : $result")
log.info(s"validated $template")
result.getParameters.asScala.toList.map(_.getParameterKey)
})
}
val client = new AmazonCloudFormationClient(awsCredentials.value)
val s = streams.value
val results: Seq[(File, Try[List[String]])] = templates.value.map(validateTemplate(client, s.log))
results.foreach { case (template, parameterKeys) =>
parameterKeys match {
case Failure(e) => s.log.error(s"validation of $template failed with: \n ${e.getMessage}")
case _ =>
}
}
if (results.exists(_._2.isFailure)) {
sys.error("some AWS CloudFormation templates failed to validate!")
}
templates.value
}
)
lazy val defaultSettings = validationSettings ++ Seq(
stackRegion := System.getenv("AWS_DEFAULT_REGION"),
stackTemplateFile := templates.value.headOption.getOrElse(throw new FileNotFoundException("*.template not found in this project")),
stackTemplate := IO.read(stackTemplateFile.value),
stackName := normalizedName.value,
stackCapabilities := Seq()
) ++ makeOperationConfig(Staging) ++ makeOperationConfig(Production)
implicit private def parametersToList(params: Parameters): util.Collection[Parameter] = {
val ps: Iterable[Parameter] = for {
(k, v) <- params
} yield {
val p = new Parameter()
p.setParameterKey(k)
p.setParameterValue(v)
p
}
ps.toList.asJava
}
implicit private def tagsToList(tags: Tags): util.Collection[Tag] = {
val ps: Iterable[Tag] = for {
(k, v) <- tags
} yield {
val p = new Tag()
p.setKey(k)
p.setValue(v)
p
}
ps.toList.asJava
}
private def fetchStatus(stack: String, cl: AmazonCloudFormationClient): Option[String] = {
Try {
val request: DescribeStacksRequest = new DescribeStacksRequest()
request.setStackName(stack)
val response = cl.describeStacks(request)
response.getStacks.asScala.toList.headOption.map(stack => stack.getStackStatus)
}.toOption.flatten
}
def makeOperationConfig(config: Configuration) = Seq(
awsCredentials in config := awsCredentials.value,
stackTemplate in config := stackTemplate.value,
stackParams in config := Map(),
stackTags in config := Map(),
stackName in config := {
s"${stackName.value}-${config.name}"
},
stackRegion in config := stackRegion.value,
stackCapabilities in config := stackCapabilities.value,
stackClient in config := {
val region = (stackRegion in config).value
if (region == null)
throw new IllegalArgumentException("stackRegion must be set")
val credentials = (awsCredentials in config).value
val client = new AmazonCloudFormationClient(credentials)
client.setRegion(Region.getRegion(Regions.fromName(region)))
client
},
stackDescribe in config := {
Try {
val request: DescribeStacksRequest = new DescribeStacksRequest()
val stack = (stackName in config).value
request.setStackName(stack)
val cloudformationClient = (stackClient in config).value
val response = cloudformationClient.describeStacks(request)
val stacks: List[Stack] = response.getStacks.asScala.toList
stacks.foreach(stack => streams.value.log.debug(s"${stack.toString}"))
stacks.headOption
}.toOption.flatten
},
stackStatus in config := {
val stack = (stackName in config).value
val cloudformationClient = (stackClient in config).value
fetchStatus(stack, cloudformationClient)
},
stackWait in config := {
val stack = (stackName in config).value
val cloudformationClient = (stackClient in config).value
def statuses: Stream[String] = Stream.cons(fetchStatus(stack, cloudformationClient).orNull, statuses)
val progressStatuses: Stream[String] = statuses.takeWhile(s => Option(s).exists(_.endsWith("_PROGRESS")))
progressStatuses foreach {
_ =>
Thread.sleep(10000)
}
statuses.headOption
},
stackCreate in config := {
val request = new CreateStackRequest
request.setStackName((stackName in config).value)
request.setTemplateBody((stackTemplate in config).value)
request.setCapabilities((stackCapabilities in config).value.asJava)
request.setParameters((stackParams in config).value)
request.setTags((stackTags in config).value)
val cloudformationClient = (stackClient in config).value
val result = cloudformationClient.createStack(request)
streams.value.log.info(s"created stack ${request.getStackName} / ${result.getStackId}")
result.getStackId
},
stackDelete in config := {
val request = new DeleteStackRequest
request.setStackName((stackName in config).value)
val cloudformationClient = (stackClient in config).value
cloudformationClient.deleteStack(request)
streams.value.log.info(s"deleted stack ${request.getStackName} ")
},
stackUpdate in config := {
val request = new UpdateStackRequest
request.setStackName((stackName in config).value)
request.setTemplateBody((stackTemplate in config).value)
request.setCapabilities((stackCapabilities in config).value.asJava)
request.setParameters((stackParams in config).value)
val cf = (stackClient in config).value
Try {
val result = cf.updateStack(request)
streams.value.log.info(s"updated stack ${request.getStackName} / ${result.getStackId}")
result.getStackId
}
.recover {
case e: com.amazonaws.services.cloudformation.model.AmazonCloudFormationException =>
streams.value.log.info(s"nothing to update ${request.getStackName}")
val d = (stackDescribe in config).value
d.get.getStackId
}
.get
}
)
}