-
Notifications
You must be signed in to change notification settings - Fork 61
/
config.py
1212 lines (1044 loc) · 52.1 KB
/
config.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Runway config file module."""
# pylint: disable=super-init-not-called,too-many-lines
from typing import (Any, Dict, List, Optional, # pylint: disable=unused-import
Union, Iterator, TYPE_CHECKING)
# python2 supported pylint is unable to load this when in a venv
from distutils.util import strtobool # pylint: disable=no-name-in-module,import-error
import logging
import os
import sys
from six import string_types
import yaml
from .util import MutableMap, cached_property
from .variables import Variable
# python2 supported pylint sees this is cyclic even though its only for type checking
# pylint: disable=cyclic-import
if TYPE_CHECKING:
from .context import Context # noqa: F401 pylint: disable=unused-import
LOGGER = logging.getLogger('runway')
NoneType = type(None)
class ConfigComponent(MutableMap):
"""Base class for Runway config components.
Attributes:
SUPPORTS_VARIABLES: A list of directives that support the use of
variable.
PRE_PROCESS_VARIABLES: A list of directives that support the use of
variables and needs to be resolved before the component is
processed.
"""
SUPPORTS_VARIABLES = ['env_vars', 'environments', 'parameters'] # type: List[str]
PRE_PROCESS_VARIABLES = [] # type: List[str]
@property
def data(self):
# type: () -> Dict[str, Any]
"""Sanitized output of __dict__ with properties added.
Removes anything that starts with ``_``.
"""
data = {}
for key, val in self.__dict__.items():
if not key.startswith('_'):
data[key] = val
for attr in self.SUPPORTS_VARIABLES:
data[attr] = getattr(self, attr, None)
return data
@property
def env_vars(self):
# type: () -> Any
"""Access the value of an attribute that supports variables."""
value = self._env_vars.value # pylint: disable=no-member
if isinstance(value, dict):
return value
raise ValueError('{}.env_vars is of type {}; expected type '
'of dict'.format(self.name, type(value)))
@property
def environments(self):
# type: () -> Dict[Any, Any]
"""Access the value of an attribute that supports variables."""
value = self._environments.value # pylint: disable=no-member
if isinstance(value, dict):
return value
raise ValueError('{}.environments is of type {}; expected type '
'of dict'.format(self.name, type(value)))
@property
def parameters(self):
# type: () -> Dict[str, Any]
"""Access the value of an attribute that supports variables."""
value = self._parameters.value # pylint: disable=no-member
if isinstance(value, dict):
return value
raise ValueError('{}.parameters is of type {}; expected type '
'of dict'.format(self.name, type(value)))
def get(self, key, default=None):
# type: (str, Any) -> Any
"""Implement evaluation of get."""
return getattr(self, key, getattr(self, key.replace('-', '_'), default))
def resolve(self, context, variables=None, pre_process=False):
# type: ('Context', Optional[VariablesDefinition], bool) -> None
"""Resolve attributes that support variables.
Args:
context: The current context object.
variables: Object containing variables passed to Runway.
pre_process: Only resolve the variables that are required before
the component is processed. If this is ``False``, all variables
will be resolved. This is useful to prevent errors when
variables cannot be resolved because the values are not
populated until processing has begun.
"""
for attr in (self.PRE_PROCESS_VARIABLES if pre_process
else self.SUPPORTS_VARIABLES):
LOGGER.debug('Resolving %s.%s', self.name, attr)
getattr(self, '_' + attr).resolve(context, variables=variables)
def __getitem__(self, key):
# type: (str) -> Any
"""Implement evaluation of self[key]."""
result = getattr(self, key, getattr(self, key.replace('-', '_')))
if isinstance(result, Variable):
return result.value
return result
def __len__(self):
# type: () -> int
"""Implement the built-in function len()."""
return len(self.data)
def __iter__(self):
# type: () -> Iterator[Any]
"""Return iterator object that can iterate over all attributes."""
return iter(self.data)
class ModuleDefinition(ConfigComponent): # pylint: disable=too-many-instance-attributes
"""A module defines the directory to be processed and applicable options.
It can consist of `CloudFormation`_ (using `CFNgin`_),
`Terraform`_, `Serverless Framework`_, `AWS CDK`_, `Kubernetes`_, or
a :ref:`Static Site<mod-staticsite>`. It is recommended to place the
appropriate extension on each directory for identification (but it
is not required). See :ref:`Repo Structure<repo-structure>` for
examples of a module directory structure.
+------------------+-----------------------------------------------+
| Suffix/Extension | IaC Tool/Framework |
+==================+===============================================+
| ``.cdk`` | `AWS CDK`_ |
+------------------+-----------------------------------------------+
| ``.cfn`` | `CloudFormation`_ |
+------------------+-----------------------------------------------+
| ``.sls`` | `Serverless Framework`_ |
+------------------+-----------------------------------------------+
| ``.tf`` | `Terraform`_ |
+------------------+-----------------------------------------------+
| ``.k8s`` | `Kubernetes`_ |
+------------------+-----------------------------------------------+
| ``.web`` | :ref:`Static Site<mod-staticsite>` |
+------------------+-----------------------------------------------+
A module is only deployed if there is a corresponding environment file
present or parameters are provided. This can take the form of either a file
in the module folder or the ``parameters`` option being defined. The naming
format varies per-module type.
See :ref:`Module Configurations<module-configurations>` for acceptable
environment file name formats.
Modules can be defined as a string or a mapping. The minimum
requirement for a module is a string that is equal to the name of
the module directory. Providing a string is the same as providing a
value for ``path`` in a mapping definition.
Example:
.. code-block:: yaml
deployments:
- modules:
- my-module.cfn # this
- path: my-module.cfn # is the same as this
Using a map to define a module provides the ability to specify
per-module ``options``, parameters, environment variables,tags,
and even a custom class for processing the module. The options that
can be used with each module vary. For detailed information about
module-specific options, see
:ref:`Module Configurations<module-configurations>`.
Example:
.. code-block:: yaml
deployments:
- modules:
- name: my-module
path: my-module.tf
environments:
prod: 111111111111/us-east-1
dev:
- 222222222222/us-east-1
- 333333333333/us-east-1
lab: true
parameters:
image_id: ${var image_id.${env DEPLOY_ENVIRONMENT}}
tags:
- app:example
- my-tag
options:
terraform_backend_config:
region: us-east-1
terraform_backend_cfn_outputs:
bucket: StackName::OutputName
dynamodb_table: StackName::OutputName
One special map keyword, ``parallel``, indicates a list of child
modules that will be executed in parallel (simultaneously) if the
``CI`` :ref:`environment variable is set<non-interactive-mode>`.
Example:
In this example, ``backend.tf`` will be deployed followed by the services
that will be utilizing it. The services will be deployed in parallel.
After the services have completed, ``frontend.tf`` will be deployed.
.. code-block:: yaml
deployments:
- modules:
- backend.tf
- parallel:
- servicea.cfn # any normal module option can be used here
- path: serviceb.cfn
- path: servicec.cfn
parameters:
count: ${var count.${env DEPLOY_ENVIRONMENT}}
- frontend.tf
"""
SUPPORTS_VARIABLES = ['class_path', 'env_vars', 'environments',
'options', 'parameters', 'path']
def __init__(self, # pylint: disable=too-many-arguments
name, # type: str
path, # type: str
class_path=None, # type: Optional[str]
type_str=None, # type: Optional[str]
environments=None, # type: Optional[Dict[str, Dict[str, Any]]]
parameters=None, # type: Optional[Dict[str, Any]]
env_vars=None, # type: Optional[Dict[str, Dict[str, Any]]]
options=None, # type: Optional[Dict[str, Any]]
tags=None, # type: Optional[Dict[str, str]]
child_modules=None # type: Optional[List[Union[str, Dict[str, Any]]]]
# pylint only complains for python2
): # pylint: disable=bad-continuation
# type: (...) -> None
""".. Runway module definition.
Keyword Args:
name (str): Name of the module. Used to more easily identify
where different modules begin/end in the logs.
path (str): Path to the module relative to the Runway config
file. This cannot be higher than the Runway config file. See
`Path`_ for detailed usage.
class_path (Optional[str]): Path to custom Runway module class.
Also used for static site deployments. See
:ref:`Module Configurations<module-configurations>` for
detailed usage.
type_str (Optional[str]): Alias for type of module to use
:ref:`Module Configurations<module-configurations>` for
detailed usage.
environments (Optional[Dict[str, Dict[str, Any]]]): Optional
mapping of environment names to a booleon value used to
explicitly deploy or not deploy in an environment. This
can be used when an environment specific variables file
and parameters are not needed to force a module to deploy
anyway or, explicitly skip a module even if a file or
parameters are found. The mapping can also have a string
(or list of strings) value of $ACCOUNT_ID/$REGION to lock
an environment to specific regions in a specific accounts.
If it matches, it will act as an explicit deploy.
env_vars (Optional[Dict[str, Dict[str, Any]]]): A mapping of
OS environment variable overrides to apply when processing
modules in the deployment. Can be defined per environment
or for all environments by omiting the environment name.
Takes precedence over values set at the deployment-level.
options (Optional[Dict[str, Any]]): Module-specific options.
See :ref:`Module Configurations<module-configurations>`
for detailed usage. Takes precedence over values set at the
deployment-level.
parameters (Optional(Dict[str, Any])): Module level parameters that
are akin to a `CloudFormation`_ parameter in functionality.
These can be used to pass variable values to your modules in
place of a ``.env``/``.tfenv``/environment config file.
Through the use of `Lookups`_, the value can differ per
deploy environment, region, etc.
tags (Optional[Dict[str, str]]): Module tags used to select
which modules to process using CLI arguments.
(``--tag <tag>...``)
child_modules (Optional[List[Union[str, Dict[str, Any]]]]):
Child modules that can be executed in parallel
.. rubric:: Lookup Resolution
+---------------------+-----------------------------------------------+
| Keyword / Directive | Support |
+=====================+===============================================+
| ``name`` | None |
+---------------------+-----------------------------------------------+
| ``path`` | `env lookup`_, `var lookup`_ |
+---------------------+-----------------------------------------------+
| ``class_path`` | `env lookup`_, `var lookup`_ |
+---------------------+-----------------------------------------------+
| ``environments`` | `env lookup`_, `var lookup`_ |
+---------------------+-----------------------------------------------+
| ``env_vars`` | `env lookup`_, `var lookup`_ |
+---------------------+-----------------------------------------------+
| ``options`` | `env lookup`_, `var lookup`_ |
+---------------------+-----------------------------------------------+
| ``parameters`` | `env lookup`_, `var lookup`_ |
+---------------------+-----------------------------------------------+
| ``tags`` | None |
+---------------------+-----------------------------------------------+
References:
- `AWS CDK`_
- `CloudFormation`_
- `Serverless Framework`_
- `CFNgin`_
- `Troposphere`_
- `Terraform`_
- `Kubernetes`_
- :ref:`Static Site<mod-staticsite>`
- :ref:`Module Configurations<module-configurations>` -
detailed module ``options``
- :ref:`Repo Structure<repo-structure>` - examples of
directory structure
- :ref:`command-deploy`
- :ref:`command-destroy`
- :ref:`command-plan`
"""
self.name = name
self._path = Variable(name + '.path', path, 'runway')
self._class_path = Variable(name + '.class_path', class_path, 'runway')
self.type = type_str
self._environments = Variable(name + '.environments',
environments or {}, 'runway')
self._parameters = Variable(name + '.parameters', parameters or {},
'runway')
self._env_vars = Variable(name + '.env_vars', env_vars or {}, 'runway')
self._options = Variable(name + '.options', options or {}, 'runway')
self.tags = tags or {}
self.child_modules = child_modules or []
@property
def class_path(self):
# type: () -> Optional[str]
"""Access the value of an attribute that supports variables."""
value = self._class_path.value
if not value:
return None
if isinstance(value, str):
return value
raise ValueError('{}.class_path = {} is of type {}; expected type '
'of str'.format(self.name, value, type(value)))
@property
def options(self):
# type: () -> Dict[Any, Any]
"""Access the value of an attribute that supports variables."""
value = self._options.value
if isinstance(value, dict):
return value
raise ValueError('{}.options is of type {}; expected type '
'of dict'.format(self.name, type(value)))
@property
def path(self):
# type: () -> str
"""Access the value of an attribute that supports variables."""
value = self._path.value # pylint: disable=no-member
if isinstance(value, str):
return value
raise ValueError('{}.path is of type {}; expected type '
'of str'.format(self.name, type(value)))
@classmethod
def from_list(cls, modules):
# type: (List[Union[Dict[str, Any], str]]) -> List[ModuleDefinition]
"""Instantiate ModuleDefinition from a list."""
results = []
for mod in modules:
if isinstance(mod, str):
results.append(cls(name=mod, path=mod))
continue
if mod.get('parallel'):
name = 'parallel_parent'
child_modules = ModuleDefinition.from_list(mod.pop('parallel'))
path = '[' + ', '.join([x.path for x in child_modules]) + ']'
if mod:
LOGGER.warning(
'Invalid keys found in parallel module config have been ignored: %s',
', '.join(mod.keys())
)
else:
name = mod.pop('name', mod['path'])
child_modules = None
path = mod.pop('path')
results.append(cls(name,
path,
class_path=mod.pop('class_path', None),
type_str=mod.pop('type', None),
environments=mod.pop('environments', {}),
env_vars=mod.pop('env_vars', {}),
options=mod.pop('options', {}),
parameters=mod.pop('parameters', {}),
tags=mod.pop('tags', {}),
child_modules=child_modules))
if mod:
LOGGER.warning(
'Invalid keys found in module %s have been ignored: %s',
name, ', '.join(mod.keys())
)
return results
class FutureDefinition(MutableMap):
"""Opt-in to future functionality before the next major release.
Availability of these toggles will be removed at each major release as
the functionality will then be considered current.
Lookups are not supported as these values should be static.
"""
def __init__(self, strict_environments=False, **kwargs):
# type: (bool, bool) -> None
"""Instantiate class.
Keyword Args:
strict_environments (bool): Wether to enable strict environments.
"""
self.strict_environments = strict_environments
if kwargs:
LOGGER.warning(
'Invalid key(s) found in "future" have been ignored: %s',
', '.join(kwargs.keys())
)
@cached_property
def enabled(self):
# type: () -> List[str]
"""List all enabled future functionality.
Returns:
List[str]: All functionality that is enabled.
"""
return [k for k, v in self.data.items() if v]
def __setattr__(self, key, value):
# type: (str, bool) -> None
"""Set attribute to a bool value only.
Args:
key (str): Attribute name.
value (bool): Attribute value.
Raises:
TypeError: Value is not bool.
"""
if isinstance(value, bool):
return super(FutureDefinition, self).__setattr__(key, value)
raise TypeError('unsupported type {} for future.{}; '
'must be of type "bool"'.format(type(value), key))
class DeploymentDefinition(ConfigComponent): # pylint: disable=too-many-instance-attributes
"""A deployment defines modules and options that affect the modules.
Deployments are processed during a ``deploy``/``destroy``/``plan``
action. If the processing of one deployment fails, the action will
end.
During a ``deploy``/``destroy`` action, the user has the option to
select which deployment will run unless the ``CI`` environment
variable is set, the ``--tag <tag>...`` cli option was provided, or
only one deployment is defined.
Example:
.. code-block:: yaml
deployments:
- modules: # minimum requirements for a deployment
# "./" can alternatively be used for the module name to indicate
# the current directory
- my-module.cfn
regions:
- us-east-1
- name: detailed-deployment # optional
modules:
- path: my-other-modules.cfn
type: cloudformation
regions:
- us-east-1
environments:
prod: 111111111111/us-east-1
dev:
- 222222222222/us-east-1
- 333333333333/us-east-1
lab: true
account_id: ${var account_ids} # optional
assume_role: ${var assume_role} # optional
parameters: # optional
region: ${env AWS_REGION}
image_id: ${var image_id.${env DEPLOY_ENVIRONMENT}}
env_vars: # optional environment variable overrides
AWS_PROFILE: ${var aws_profile.${env DEPLOY_ENVIRONMENT}::default=default}
APP_PATH: ${var app_path.${env DEPLOY_ENVIRONMENT}}
"""
SUPPORTS_VARIABLES = ['account_alias', 'account_id', 'assume_role',
'env_vars', 'environments', 'module_options',
'regions', 'parallel_regions', 'parameters']
PRE_PROCESS_VARIABLES = ['account_alias', 'account_id', 'assume_role',
'env_vars', 'regions']
def __init__(self, deployment):
# type: (Dict[str, Any]) -> None
""".. Runway deployment definition.
Keyword Args:
account_alias (Optional[Dict[str, str]]): A mapping of
``$environment: $alias`` that, if provided, is used to
verify the currently assumed role or credentials.
account_id (Optional[Dict[str, Union[str, int]]]): A mapping
of ``$environment: $id`` that, if provided, is used to
verify the currently assumed role or credentials.
assume_role (Optional[Dict[str, Union[str, Dict[str, str]]]]):
A mapping of ``$environment: $role`` or
``$environment: {arn: $role, duration: $int}`` to assume
a role when processing a deployment. ``arn: $role`` can
be used to apply the same role to all environment.
``post_deploy_env_revert: true`` can also be provided to
revert credentials after processing.
environments (Optional[Dict[str, Dict[str, Any]]]): Optional
mapping of environment names to a booleon value used to
explicitly enable or disable in an environment. This
can be used when an environment specific variables file
and parameters are not needed to force a module to enable
anyway or, explicitly skip a module even if a file or
parameters are found. The mapping can also have a string
(or list of strings) value of $ACCOUNT_ID/$REGION to lock
an environment to specific regions in a specific accounts.
If it matches, it will act as an explicit enable.
env_vars (Optional[Dict[str, Dict[str, Any]]]): A mapping of
OS environment variable overrides to apply when processing
modules in the deployment. Can be defined per environment
or for all environments by omiting the environment name.
modules (Optional[List[Dict[str, Any]]]): A list of modules
to be processed in the order they are defined.
module_options (Optional[Dict[str, Any]]): Options that are
shared among all modules in the deployment.
name (str): Name of the deployment. Used to more easily
identify where different deployments begin/end in the logs.
type (str): The type of module we are deploying. By default
Runway will first check to see if you explicitly specify
the module type, after that it will check to see if a
valid module extension exists on the directory, and
finally it will attempt to autodetect the type of module.
Valid values are: ``serverless``, ``terraform``, ``cdk``,
``kubernetes``, ``cloudformation``, ``static``.
regions (List[str]): AWS region names where modules will be
deployed/destroyed. Can optionally define as a map with
``parallel`` as the key and a list of regions as the value.
See **parallel_regions** for more info.
parallel_regions: Can be defined in place of ``regions.parallel[]``.
This will cause all modules in the deployment to be executed
in all provided regions in parallel (at the same time).
Only takes effect when the ``CI`` environment variable is set,
enabling non-interactive mode, as prompts will not be able
to be presented. If ``CI`` is not set, the regions will be
processed one at a time. This can be used in tandom with
**parallel modules**. ``assume_role.post_deploy_env_revert``
will always be ``true`` when run in parallel.
parameters (Optional(Dict[str, Any])): Module level parameters that
are akin to a `CloudFormation`_ parameter in functionality.
These can be used to pass variable values to your modules in
place of a ``.env``/``.tfenv``/environment config file.
Through the use of `Lookups`_, the value can differ per
deploy environment, region, etc.
.. rubric:: Lookup Resolution
.. important:: Due to how a deployment is processed, values are
resolved twice. Once before processing and once during
processing. Because of this, the keywords/directives
that are resolved before processing will not have
access to values set during process like ``AWS_REGION``,
``AWS_DEFAULT_REGION``, and ``DEPLOY_ENVIRONMENT`` for
the pre-processing resolution but, if they are resolved
again during processing, these will be available. To
avoide errors during the first resolution due to the
value not existing, provide a default value for the
:ref:`Lookup <Lookups>`.
+---------------------+-----------------------------------------------+
| Keyword / Directive | Support |
+=====================+===============================================+
| ``account_alias`` | `env lookup`_ (``AWS_REGION`` and |
| | ``AWS_DEFAULT_REGION`` will not have been set |
| | by Runway yet), `var lookup`_ |
+---------------------+-----------------------------------------------+
| ``account_id`` | `env lookup`_ (``AWS_REGION`` and |
| | ``AWS_DEFAULT_REGION`` will not have been set |
| | by Runway yet), `var lookup`_ |
+---------------------+-----------------------------------------------+
| ``assume_role`` | `env lookup`_ (``AWS_REGION`` and |
| | ``AWS_DEFAULT_REGION`` will not have been set |
| | by Runway yet), `var lookup`_ |
+---------------------+-----------------------------------------------+
| ``environments`` | `env lookup`_, `var lookup`_ |
+---------------------+-----------------------------------------------+
| ``env_vars`` | `env lookup`_ (``AWS_REGION``, |
| | ``DEPLOY_ENVIRONMENT``, and |
| | ``AWS_DEFAULT_REGION`` will not have been set |
| | by Runway during pre-process resolution. |
| | provide a default value to avoide errors.), |
| | `var lookup`_ |
+---------------------+-----------------------------------------------+
| ``modules`` | No direct support. See `module`_ for details |
| | on support within a module definition. |
+---------------------+-----------------------------------------------+
| ``module_options`` | `env lookup`_, `var lookup`_ |
+---------------------+-----------------------------------------------+
| ``name`` | None |
+---------------------+-----------------------------------------------+
| ``regions`` | `env lookup`_ (``AWS_REGION`` and |
| | ``AWS_DEFAULT_REGION`` will not have been set |
| | by Runway yet), `var lookup`_ |
+---------------------+-----------------------------------------------+
| ``parallel_regions``| `env lookup`_ (``AWS_REGION`` and |
| | ``AWS_DEFAULT_REGION`` will not have been set |
| | by Runway yet), `var lookup`_ |
+---------------------+-----------------------------------------------+
| ``parameters`` | `env lookup`_, `var lookup`_ |
+---------------------+-----------------------------------------------+
References:
- :class:`module<runway.config.ModuleDefinition>`
- :ref:`command-deploy`
- :ref:`command-destroy`
- :ref:`command-plan`
"""
self._reverse = False
self.name = deployment.pop('name') # type: str
self._account_alias = Variable(
self.name + '.account_alias', deployment.pop(
'account_alias', deployment.pop('account-alias', {})
), 'runway'
) # type: Variable
self._account_id = Variable(self.name + '.account_id', deployment.pop(
'account_id', deployment.pop('account-id', {})
), 'runway') # type: Variable
self._assume_role = Variable(
self.name + '.assume_role', deployment.pop(
'assume_role', deployment.pop('assume-role', {})
), 'runway'
) # type: Variable
self._environments = Variable(
self.name + '.environments', deployment.pop('environments', {}),
'runway'
) # type: Variable
self._parameters = Variable(
self.name + '.parameters', deployment.pop('parameters', {}),
'runway'
) # type: Variable
self._env_vars = Variable(self.name + '.env_vars', deployment.pop(
'env_vars', deployment.pop('env-vars', {})
), 'runway') # type: Variable
if deployment.pop('current_dir', False):
# Deprecated in 1.0 (late 2019). Retain for at least a major version.
LOGGER.warning('DEPRECATION WARNING: The "current_dir" option has '
'been deprecated in favor of a "./" module '
'definition. Please update your config.')
modules = ['.' + os.sep]
else:
if not deployment.get('modules'):
LOGGER.error('No modules have been defined in your Runway '
'deployment.')
sys.exit(1)
modules = deployment.pop('modules')
self.modules = ModuleDefinition.from_list(
modules
) # type: List[ModuleDefinition]
self._module_options = Variable(
self.name + '.module_options', deployment.pop(
'module_options', deployment.pop('module-options', {})
), 'runway'
) # type: Variable
# should add variable resolve here to support parallel region
# dict in the resolved variable
regions = deployment.pop(
'regions', []
)
if regions and deployment.get('parallel_regions'):
LOGGER.error('Found "regions" and "parallel_regions" in '
'deployment "%s"; only one can be defined',
self.name)
sys.exit(1)
if isinstance(regions, dict) and regions.get('parallel'):
self._parallel_regions = Variable(
self.name + '.parallel_regions', regions.pop('parallel'),
'runway'
) # type: Variable
self._regions = Variable(self.name + '.regions',
[], 'runway') # type: Variable
else:
self._regions = Variable(self.name + '.regions',
regions, 'runway')
self._parallel_regions = Variable(
self.name + '.parallel_regions',
deployment.pop('parallel_regions', []),
'runway'
)
if deployment:
LOGGER.warning(
'Invalid keys found in deployment %s have been ignored: %s',
self.name, ', '.join(deployment.keys())
)
@property
def account_alias(self):
# type: () -> Union[Dict[Any, Any], str]
"""Access the value of an attribute that supports variables."""
value = self._account_alias.value
if isinstance(value, (dict, string_types)):
return value
raise ValueError('{}.account_alias is of type {}; expected type '
'of dict or str'.format(self.name, type(value)))
@property
def account_id(self):
# type: () -> Union[Dict[Any, Any], str]
"""Access the value of an attribute that supports variables."""
value = self._account_id.value
if isinstance(value, (dict, string_types)):
return value
if isinstance(value, int):
return str(value)
raise ValueError('{}.account_id is of type {}; expected type '
'of dict, int, or str'.format(self.name, type(value)))
@property
def assume_role(self):
# type: () -> Union[Dict[Any, Any], str]
"""Access the value of an attribute that supports variables."""
value = self._assume_role.value
if isinstance(value, (dict, string_types)):
return value
raise ValueError('{}.assume_role is of type {}; expected type '
'of dict or str'.format(self.name, type(value)))
@property
def module_options(self):
# type: () -> Dict[Any, Any]
"""Access the value of an attribute that supports variables."""
value = self._module_options.value
if isinstance(value, dict):
return value
raise ValueError('{}.module_options is of type {}; expected type '
'of dict'.format(self.name, type(value)))
@property
def regions(self):
# type: () -> List[str]
"""Access the value of an attribute that supports variables."""
value = self._regions.value
if isinstance(value, list):
if self._reverse:
return value[::-1]
return value
raise ValueError('{}.regions is of type {}; expected type '
'of list'.format(self.name, type(value)))
@property
def parallel_regions(self):
# type: () -> List[str]
"""Access the value of an attribute that supports variables."""
value = self._parallel_regions.value
if isinstance(value, list):
return value
raise ValueError('{}.parallel_regions is of type {}; expected type '
'of list'.format(self.name, type(value)))
def reverse(self):
"""Reverse the order of modules and regions."""
if self._reverse:
self._reverse = False
else:
self._reverse = True
self.modules.reverse()
@classmethod
def from_list(cls, deployments):
# type: (Optional[List[Dict[str, Any]]]) -> List[DeploymentDefinition]
"""Instantiate DeploymentDefinitions from a list."""
results = []
if not deployments:
return []
for i, deployment in enumerate(deployments):
if not deployment.get('name'):
deployment['name'] = 'deployment_{}'.format(str(i + 1))
results.append(cls(deployment))
return results
class TestDefinition(ConfigComponent):
"""Tests can be defined as part of the Runway config file.
This is to remove the need for complex Makefiles or scripts to initiate
test runners. Simply define all tests for a project in the Runway
config file and use the ``runway test`` :ref:`command<command-test>`
to execute them.
Example:
.. code-block:: yaml
tests:
- name: my-test
type: script
required: false
args:
commands:
- echo "Hello World!"
"""
SUPPORTS_VARIABLES = ['args', 'required']
def __init__(self,
name, # type: str
test_type, # type: str
args=None, # type: Optional[Dict[str, Any]]
required=True # type: bool
# pylint only complains for python2
): # pylint: disable=bad-continuation
# type: (...) -> None
""".. Runway test definitions.
Keyword Args:
name (str): Name of the test. Used to more easily identify
where different tests begin/end in the logs.
type (str): The type of test to run. See
:ref:`Build-in Test Types<built-in-test-types>`
for supported test types.
args (Optional[Dict[str, Any]]): Arguments to be passed to
the test. Supported arguments vary by test type. See
:ref:`Build-in Test Types<built-in-test-types>` for the
list of arguments supported by each test type.
required (bool): If false, testing will continue if the test
fails. *(default: true)*
.. rubric:: Lookup Resolution
.. note:: Runway does not set ``AWS_REGION`` or ``AWS_DEFAULT_REGION``
environment variables. If the ``DEPLOY_ENVIRONMENT``
environment variable is not manually set, it will always
be ``test`` and is not determined from the branch or
directory.
+---------------------+-----------------------------------------------+
| Keyword / Directive | Support |
+=====================+===============================================+
| ``args`` | `env lookup`_, `var lookup`_ |
+---------------------+-----------------------------------------------+
| ``required`` | `env lookup`_, `var lookup`_ |
+---------------------+-----------------------------------------------+
References:
- :ref:`Build-in Test Types<built-in-test-types>` - Supported
test types and their
arguments
- :ref:`test command<command-test>`
"""
self.name = name
self.type = test_type
self._args = Variable(self.name + '.args', args or {}, 'runway')
self._required = Variable(self.name + '.required', required, 'runway')
@property
def args(self):
# type: () -> Dict[str, Any]
"""Access the value of an attribute that supports variables."""
value = self._args.value
if isinstance(value, dict):
return value
raise ValueError('{}.args is of type {}; expected type '
'of dict'.format(self.name, type(value)))
@property
def required(self):
# type: () -> bool
"""Access the value of an attribute that supports variables."""
value = self._required.value
if isinstance(value, bool):
return value
try:
value = strtobool(value)
return value
except ValueError:
pass
raise ValueError('{}.required is of type {}; expected type '
'of bool'.format(self.name, type(value)))
@classmethod
def from_list(cls, tests):
# type: (Optional[List[Dict[str, Any]]]) -> List[TestDefinition]
"""Instantiate TestDefinitions from a list."""
results = []
if not tests:
return []
for index, test in enumerate(tests):
name = test.pop('name', 'test_{}'.format(index + 1))
results.append(cls(name, test.pop('type'),
test.pop('args', {}),
test.pop('required', False)))
if test:
LOGGER.warning(
'Invalid keys found in test %s have been ignored: %s',
name, ', '.join(test.keys())
)
return results
class VariablesDefinition(MutableMap):
"""A variable definitions for the Runway config file.
Runway variables are used to fill values that could change based on any
number of circumstances. They can also be used to simplify the Runway config
file by pulling lengthy definitions into another file. Variables can be used
in the config file by providing the `var lookup`_ to any keyword/directive
that supports :ref:`Lookups <Lookups>`.
By default, Runway will look for and load a ``runway.variables.yml`` or
``runway.variables.yaml`` file that is in the same directory as the
Runway config file. The file path and name of the file can optionally be
defined in the config file. If the file path is explicitly provided and
the file can't be found, an error will be raised.
Variables can also be defined in the Runway config file directly. This can
either be in place of a dedicated variables file, extend an existing file,
or override values from the file.
.. rubric:: Lookup Resolution
Runway lookup resolution is not supported within the variables definition
block or variables file. Attempts to use Runway :ref:`Lookups <Lookups>`
within the variables definition block or variables file will result in
the literal value being processed.
Example:
.. code-block:: yaml
variables:
sys_path: ./ # defaults to the current directory
file_path: secrets.yaml
# define additional variables or override those in the variables file
another_var: some_value
deployments:
- modules:
- ${var sampleapp.definition}
regions: ${var sampleapp.regions}
"""
default_names = ['runway.variables.yml', 'runway.variables.yaml']
def __init__(self, file_path=None, sys_path=None, **kwargs):
""".. Not really needed but cleans up the docs.
Keyword Args:
file_path: Explicit path to a variables file. If it cannot be found
Runway will exit.
sys_path: Directory to base relative paths off of.