-
Notifications
You must be signed in to change notification settings - Fork 334
/
deploy.py
260 lines (218 loc) · 8.76 KB
/
deploy.py
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
"""
Copyright 2017-present Airbnb, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from streamalert.shared import rule_table
from streamalert.shared.logger import get_logger
from streamalert_cli import helpers
from streamalert_cli.manage_lambda import package
from streamalert_cli.terraform.generate import terraform_generate_handler
from streamalert_cli.utils import (
add_default_lambda_args,
CLICommand,
MutuallyExclusiveStagingAction,
set_parser_epilog,
)
LOGGER = get_logger(__name__)
class DeployCommand(CLICommand):
description = 'Deploy the specified AWS Lambda function(s)'
@classmethod
def setup_subparser(cls, subparser):
"""Add the deploy subparser: manage.py deploy [options]"""
set_parser_epilog(
subparser,
epilog=(
'''\
Example:
manage.py deploy --function rule alert
'''
)
)
# Flag to manually bypass rule staging for new rules upon deploy
# This only has an effect if rule staging is enabled
subparser.add_argument(
'--skip-rule-staging',
action='store_true',
help='Skip staging of new rules so they go directly into production'
)
# flag to manually demote specific rules to staging during deploy
subparser.add_argument(
'--stage-rules',
action=MutuallyExclusiveStagingAction,
default=set(),
help='Stage the rules provided in a space-separated list',
nargs='+'
)
# flag to manually bypass rule staging for specific rules during deploy
subparser.add_argument(
'--unstage-rules',
action=MutuallyExclusiveStagingAction,
default=set(),
help='Unstage the rules provided in a space-separated list',
nargs='+'
)
add_default_lambda_args(subparser)
@classmethod
def handler(cls, options, config):
"""CLI handler for deploying new versions of Lambda functions
Args:
options (argparse.Namespace): Parsed argparse namespace from the CLI
config (CLIConfig): Loaded StreamAlert config
Returns:
bool: False if errors occurred, True otherwise
"""
# Make sure the Terraform code is up to date
if not terraform_generate_handler(config=config):
return False
if not deploy(config, options.functions, options.clusters):
return False
# Update the rule table now if the rules engine is being deployed
if 'rule' in set(options.functions):
_update_rule_table(options, config)
return True
def deploy(config, functions, clusters=None):
"""Deploy the functions
Args:
functions (set): Set of functions being deployed
config (CLIConfig): Loaded StreamAlert config
clusters (set=None): Optional clusters to target for this deploy
Returns:
bool: False if errors occurred, True otherwise
"""
LOGGER.info('Deploying: %s', ', '.join(sorted(functions)))
deployment_package = package.LambdaPackage(config)
package_path = deployment_package.create()
if not package_path:
return False
# Terraform apply only to the module which contains our lambda functions
clusters = clusters or config.clusters()
deploy_targets = _lambda_terraform_targets(config, functions, clusters)
LOGGER.debug('Applying terraform targets: %s', ', '.join(sorted(deploy_targets)))
# Terraform applies the new package and publishes a new version
return helpers.tf_runner(targets=deploy_targets)
def _update_rule_table(options, config):
"""Update the rule table with any staging information
Args:
options (argparse.Namespace): Various options from the CLI needed for actions
config (CLIConfig): The loaded StreamAlert config
"""
# If rule staging is disabled, do not update the rules table
if not config['global']['infrastructure']['rule_staging'].get('enabled', False):
return
# Get the rule import paths to load
rule_import_paths = config['global']['general']['rule_locations']
table_name = '{}_streamalert_rules'.format(config['global']['account']['prefix'])
table = rule_table.RuleTable(table_name, *rule_import_paths)
table.update(options.skip_rule_staging)
if options.stage_rules or options.unstage_rules:
# Create a dictionary of rule_name: stage=True|False
rules = {rule_name: False for rule_name in options.unstage_rules}
rules.update({rule_name: True for rule_name in options.stage_rules})
for rule, stage in rules.items():
table.toggle_staged_state(rule, stage)
def _lambda_terraform_targets(config, functions, clusters):
"""Return any terraform targets for the function(s) being deployed
NOTE: This is very hacky and should go away. A complete refactor of how we peform
terraform generation would help with this, but this hack will do for now.
Args:
config (CLIConfig): The loaded StreamAlert config
functions (list): Functions to target during deploy
clusters (list): Clusters to target during deploy
Returns:
set: Terraform module paths to target during this deployment
"""
target_mapping = {
'alert': {
'targets': {
'module.alert_processor_iam',
'module.alert_processor_lambda',
},
'enabled': True # required function
},
'alert_merger': {
'targets': {
'module.alert_merger_iam',
'module.alert_merger_lambda',
},
'enabled': True # required function
},
'artifact_extractor': {
'targets': {
'module.artifact_extractor',
'module.artifact_extractor_lambda'
},
'enabled': config['lambda'].get('artifact_extractor_config', {}).get('enabled', False)
},
'athena': {
'targets': {
'module.athena_partitioner_iam',
'module.athena_partitioner_lambda',
},
'enabled': True # required function
},
'rule': {
'targets': {
'module.rules_engine_iam',
'module.rules_engine_lambda',
},
'enabled': True # required function
},
'classifier': {
'targets': {
'module.classifier_{}_{}'.format(cluster, suffix)
for suffix in {'lambda', 'iam'}
for cluster in clusters
},
'enabled': bool(clusters) # one cluster at least is required
},
'apps': {
'targets': {
'module.app_{}_{}_{}'.format(app_info['app_name'], cluster, suffix)
for suffix in {'lambda', 'iam'}
for cluster in clusters
for app_info in config['clusters'][cluster]['modules'].get(
'streamalert_apps', {}
).values()
if 'app_name' in app_info
},
'enabled': any(
info['modules'].get('streamalert_apps')
for info in config['clusters'].values()
)
},
'rule_promo': {
'targets': {
'module.rule_promotion_iam',
'module.rule_promotion_lambda',
},
'enabled': config['lambda'].get('rule_promotion_config', {}).get('enabled', False)
},
'scheduled_queries': {
'targets': {
'module.scheduled_queries',
},
'enabled': config['scheduled_queries'].get('enabled', False),
},
'threat_intel_downloader': {
'targets': {
'module.threat_intel_downloader',
'module.threat_intel_downloader_iam',
},
'enabled': config['lambda'].get('threat_intel_downloader_config', False),
}
}
targets = set()
for function in functions:
if not target_mapping[function]['enabled']:
LOGGER.warning('Function is not enabled and will be ignored: %s', function)
continue
targets.update(target_mapping[function]['targets'])
return targets