Skip to content

Commit 6c53449

Browse files
authored
Merge pull request #580 from zalando-stups/ci/fix-pipeline
Fix testing pipeline
2 parents 841a68e + e1bc0f5 commit 6c53449

File tree

8 files changed

+76
-66
lines changed

8 files changed

+76
-66
lines changed

delivery.yaml

+3-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ notifications:
66
pipeline:
77
- id: build
88
type: script
9-
overlay: ci/python
9+
vm_config:
10+
type: linux
11+
image: cdp-runtime/python-3.9
1012
commands:
1113
- desc: "Install dependencies"
1214
cmd: pip install -r requirements.txt

senza/arguments.py

+39-13
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,50 @@
66
# pylint: disable=locally-disabled, invalid-name
77
import boto3.session
88
import click
9+
import configparser
10+
import os
911

1012
from .error_handling import HandleExceptions
1113

1214

15+
def get_region(region):
16+
"""
17+
Ensure region value.
18+
If region is not provided, get one from the config file.
19+
Raise error if still no region is set at the end.
20+
"""
21+
if not region:
22+
config = configparser.ConfigParser()
23+
try:
24+
config.read(os.path.expanduser("~/.aws/config"))
25+
if "default" in config:
26+
region = config["default"]["region"]
27+
except Exception:
28+
pass
29+
30+
if not region:
31+
raise click.UsageError(
32+
"Please specify the AWS region on the "
33+
"command line (--region) or in ~/.aws/config"
34+
)
35+
36+
return region
37+
38+
1339
def validate_region(ctx, param, value): # pylint: disable=locally-disabled, unused-argument
14-
"""Validate Click region param parameter."""
15-
16-
if value is not None:
17-
session = boto3.session.Session()
18-
valid_regions = session.get_available_regions('cloudformation')
19-
if value not in valid_regions:
20-
valid_regions.sort()
21-
raise click.BadParameter("'{}'. Region must be one of the "
22-
"following AWS regions:\n"
23-
" - {}".format(value,
24-
"\n - ".join(valid_regions)))
40+
"""Validate Click region parameter."""
41+
42+
value = get_region(value) # ensure region is set
43+
44+
session = boto3.session.Session()
45+
valid_regions = session.get_available_regions('cloudformation')
46+
if value not in valid_regions:
47+
valid_regions.sort()
48+
raise click.BadParameter("'{}'. Region must be one of the "
49+
"following AWS regions:\n"
50+
" - {}".format(value,
51+
"\n - ".join(valid_regions)))
52+
2553
return value
2654

2755

@@ -74,5 +102,3 @@ def set_stacktrace_visible(ctx, param, value): # pylint: disable=locally-disabl
74102
metavar='NAME',
75103
multiple=True,
76104
help='Specify field to be returned')
77-
78-
GLOBAL_OPTIONS = {}

senza/cli.py

+1-43
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import base64
33
import calendar
44
import collections
5-
import configparser
65
import datetime
76
import ipaddress
87
import json
@@ -37,7 +36,6 @@
3736
from senza.components.elastigroup import ELASTIGROUP_RESOURCE_TYPE
3837
from .spotinst.components import elastigroup_api
3938
from .arguments import (
40-
GLOBAL_OPTIONS,
4139
json_output_option,
4240
output_option,
4341
parameter_file_option,
@@ -46,6 +44,7 @@
4644
watch_option,
4745
watchrefresh_option,
4846
field_option,
47+
get_region
4948
)
5049
from .aws import (
5150
StackReference,
@@ -432,27 +431,6 @@ def read_parameter_file(parameter_file):
432431
return tuple(paras)
433432

434433

435-
def get_region(region):
436-
if not region:
437-
region = GLOBAL_OPTIONS.get("region")
438-
if not region:
439-
config = configparser.ConfigParser()
440-
try:
441-
config.read(os.path.expanduser("~/.aws/config"))
442-
if "default" in config:
443-
region = config["default"]["region"]
444-
except Exception:
445-
pass
446-
447-
if not region:
448-
raise click.UsageError(
449-
"Please specify the AWS region on the "
450-
"command line (--region) or in ~/.aws/config"
451-
)
452-
453-
return region
454-
455-
456434
def check_credentials(region):
457435
iam = BotoClientProxy("iam")
458436
return iam.list_account_aliases()
@@ -523,7 +501,6 @@ def all_with_version(stack_refs: list):
523501
def list_stacks(region, stack_ref, all, output, field, w, watch):
524502
"""List Cloud Formation stacks"""
525503

526-
region = get_region(region)
527504
check_credentials(region)
528505

529506
stack_refs = get_stack_refs(stack_ref)
@@ -652,7 +629,6 @@ def get_classic_load_balancer_metrics(cloudwatch, lb_name, start, now):
652629
def health(region, stack_ref, all, output, field, w, watch):
653630
"""Show stack health (ELB req/s, ..)"""
654631

655-
region = get_region(region)
656632
check_credentials(region)
657633

658634
cloudwatch = BotoClientProxy("cloudwatch", region)
@@ -753,7 +729,6 @@ def create(
753729
):
754730
"""Create a new Cloud Formation stack from the given Senza definition file"""
755731

756-
region = get_region(region)
757732
data = create_cf_template(
758733
definition, region, version, parameter, force, parameter_file
759734
)
@@ -825,7 +800,6 @@ def update(
825800
"""Update an existing Cloud Formation stack from the given Senza
826801
definition file"""
827802

828-
region = get_region(region)
829803
data = create_cf_template(
830804
definition, region, version, parameter, force, parameter_file
831805
)
@@ -844,7 +818,6 @@ def update(
844818
def print_cfjson(definition, region, version, parameter, output, force, parameter_file):
845819
"""Print the generated Cloud Formation template"""
846820

847-
region = get_region(region)
848821
data = create_cf_template(
849822
definition, region, version, parameter, force, parameter_file, pretty=True
850823
)
@@ -953,7 +926,6 @@ def delete(stack_ref, region, dry_run, force, interactive, ignore_non_existent):
953926
"""Delete a single Cloud Formation stack"""
954927

955928
stack_refs = get_stack_refs(stack_ref)
956-
region = get_region(region)
957929
check_credentials(region)
958930

959931
if not stack_refs:
@@ -1015,7 +987,6 @@ def resources(stack_ref, region, w, watch, output, field):
1015987
"""Show all resources of a single Cloud Formation stack"""
1016988

1017989
stack_refs = get_stack_refs(stack_ref)
1018-
region = get_region(region)
1019990
check_credentials(region)
1020991
cf = BotoClientProxy("cloudformation", region)
1021992

@@ -1063,7 +1034,6 @@ def events(stack_ref, region, w, watch, output, field):
10631034
"""Show all Cloud Formation events for a single stack"""
10641035

10651036
stack_refs = get_stack_refs(stack_ref)
1066-
region = get_region(region)
10671037
check_credentials(region)
10681038
cf = BotoClientProxy("cloudformation", region)
10691039

@@ -1120,7 +1090,6 @@ def events(stack_ref, region, w, watch, output, field):
11201090
def init(definition_file, region, template, user_variable):
11211091
"""Initialize a new Senza definition"""
11221092

1123-
region = get_region(region)
11241093
check_credentials(region)
11251094
account_info = AccountArguments(region=region)
11261095

@@ -1263,7 +1232,6 @@ def instances(
12631232
"""List the stack's EC2 instances"""
12641233

12651234
stack_refs = get_stack_refs(stack_ref)
1266-
region = get_region(region)
12671235
check_credentials(region)
12681236

12691237
ec2 = boto3.resource("ec2", region)
@@ -1358,7 +1326,6 @@ def status(stack_ref, region, output, field, w, watch):
13581326
"""Show stack status information"""
13591327

13601328
stack_refs = get_stack_refs(stack_ref)
1361-
region = get_region(region)
13621329
check_credentials(region)
13631330

13641331
ec2 = boto3.resource("ec2", region)
@@ -1451,7 +1418,6 @@ def domains(stack_ref, region, output, field, w, watch):
14511418
"""List the stack's Route53 domains"""
14521419

14531420
stack_refs = get_stack_refs(stack_ref)
1454-
region = get_region(region)
14551421
check_credentials(region)
14561422

14571423
cf = boto3.resource("cloudformation", region)
@@ -1560,7 +1526,6 @@ def traffic(stack_name, stack_version, percentage, region, output, timeout, inte
15601526
"""Route traffic to a specific stack (weighted DNS record)"""
15611527

15621528
stack_refs = get_stack_refs([stack_name, stack_version])
1563-
region = get_region(region)
15641529
check_credentials(region)
15651530

15661531
with OutputFormat(output):
@@ -1593,7 +1558,6 @@ def images(stack_ref, region, output, field, hide_older_than, show_instances):
15931558
"""Show all used AMIs and available Taupage AMIs"""
15941559

15951560
stack_refs = get_stack_refs(stack_ref)
1596-
region = get_region(region)
15971561
check_credentials(region)
15981562

15991563
ec2 = boto3.resource("ec2", region)
@@ -1730,7 +1694,6 @@ def console(instance_or_stack_ref, limit, region, w, watch):
17301694
# filter out instances not part of any stack
17311695
filters = [{"Name": "tag-key", "Values": ["aws:cloudformation:stack-name"]}]
17321696

1733-
region = get_region(region)
17341697
check_credentials(region)
17351698

17361699
ec2 = boto3.resource("ec2", region)
@@ -1784,7 +1747,6 @@ def dump(stack_ref, region, output):
17841747
"""Dump Cloud Formation template of existing stack"""
17851748

17861749
stack_refs = get_stack_refs(stack_ref)
1787-
region = get_region(region)
17881750
check_credentials(region)
17891751

17901752
cf = BotoClientProxy("cloudformation", region)
@@ -1848,7 +1810,6 @@ def patch(stack_ref, region, image, instance_type, user_data):
18481810
Currently supports patching ASG launch configurations and ElastiGroup groups."""
18491811

18501812
stack_refs = get_stack_refs(stack_ref)
1851-
region = get_region(region)
18521813
check_credentials(region)
18531814

18541815
if image in taupage.CHANNELS:
@@ -1948,7 +1909,6 @@ def respawn_instances(stack_ref, inplace, force, batch_size_percentage, batch_pe
19481909
Performs a rolling update to prevent downtimes."""
19491910

19501911
stack_refs = get_stack_refs(stack_ref)
1951-
region = get_region(region)
19521912
check_credentials(region)
19531913

19541914
stacks = get_stacks(stack_refs, region)
@@ -1980,7 +1940,6 @@ def scale(stack_ref, region, desired_capacity, min_size, force):
19801940
"""Scale Auto Scaling Group to desired capacity"""
19811941

19821942
stack_refs = get_stack_refs(stack_ref)
1983-
region = get_region(region)
19841943
check_credentials(region)
19851944

19861945
stacks = get_stacks(stack_refs, region)
@@ -2120,7 +2079,6 @@ def wait(stack_ref, region, deletion, timeout, interval):
21202079
"""
21212080

21222081
stack_refs = get_stack_refs(stack_ref)
2123-
region = get_region(region)
21242082
cf = BotoClientProxy("cloudformation", region)
21252083

21262084
target_status = (

senza/components/elastic_load_balancer_v2.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ def component_elastic_load_balancer_v2(definition,
8888
version = '{}-{}'.format(info["StackVersion"],
8989
configuration['NameSuffix'])
9090
loadbalancer_name = get_load_balancer_name(info["StackName"], version)
91-
del(configuration['NameSuffix'])
91+
del (configuration['NameSuffix'])
9292
else:
9393
loadbalancer_name = get_load_balancer_name(info["StackName"],
9494
info["StackVersion"])

senza/subcommands/root.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
import senza
1414
from clickclick import AliasedGroup, warning
1515

16-
from ..arguments import GLOBAL_OPTIONS, region_option
1716
from ..error_handling import sentry
1817

1918
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
@@ -132,16 +131,13 @@ def print_version(ctx, param, value):
132131
is_eager=True,
133132
help="Print the current version number and exit.",
134133
)
135-
@region_option
136-
def cli(region):
134+
def cli():
137135
"""
138136
Senza's root command.
139137
140-
It checks the version and sets the region global option before executing
141-
the sub-commands.
138+
Checks the version.
142139
143140
Sub command can be added by using `cli.add_command(SUB_COMMAND_FUNCTION)`
144141
or using the `@cli.command()` decorator
145142
"""
146143
check_senza_version(senza.__version__)
147-
GLOBAL_OPTIONS["region"] = region

senza/templates/postgresapp.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -438,7 +438,7 @@ def gather_user_variables(variables, region, account_info):
438438
variables['use_ebs'] = True
439439

440440
if variables['use_ebs']:
441-
prompt(variables, 'volume_size', 'Database volume size (GB, 10 or more)', default=defaults['volume_size'])
441+
prompt(variables, 'volume_size', 'Database volume size (GB, 10 or more)', default=str(defaults['volume_size']))
442442
prompt(variables, 'volume_type', 'Database volume type (gp2, io1 or standard)',
443443
default=defaults['volume_type'])
444444
if variables['volume_type'] == 'io1':

setup.py

+19-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import setuptools
99
from setuptools.command.test import test as TestCommand
10-
from setuptools import setup
10+
from setuptools import setup, Command
1111

1212
if sys.version_info < (3, 4, 0):
1313
sys.stderr.write('FATAL: STUPS Senza needs to be run with Python 3.4+\n')
@@ -91,6 +91,23 @@ def run_tests(self):
9191
sys.exit(errno)
9292

9393

94+
class Flake8(Command):
95+
96+
user_options = []
97+
98+
def initialize_options(self):
99+
pass
100+
101+
def finalize_options(self):
102+
pass
103+
104+
def run(self):
105+
from flake8.main.cli import main
106+
107+
errno = main(['senza'])
108+
sys.exit(errno)
109+
110+
94111
def get_install_requirements(path):
95112
content = open(os.path.join(__location__, path)).read()
96113
return [req for req in content.split('\\n') if req != '']
@@ -104,6 +121,7 @@ def setup_package():
104121
# Assemble additional setup commands
105122
cmdclass = {}
106123
cmdclass['test'] = PyTest
124+
cmdclass['flake8'] = Flake8
107125

108126
install_reqs = get_install_requirements('requirements.txt')
109127

tests/test_cli.py

+10
Original file line numberDiff line numberDiff line change
@@ -564,6 +564,16 @@ def my_resource(rtype, *args):
564564
monkeypatch.setattr('boto3.resource', my_resource)
565565
monkeypatch.setattr('senza.cli.AccountArguments', MagicMock())
566566

567+
kms_key = {'KeyId': 'key_a',
568+
'aliases': ['something'],
569+
'Description': 'This is key a',
570+
'Arn': 'arn:partition:service:region:account-id:resource-id'}
571+
monkeypatch.setattr('senza.templates.postgresapp.list_kms_keys',
572+
MagicMock(return_value=[kms_key]))
573+
monkeypatch.setattr('senza.templates.postgresapp.choice',
574+
MagicMock(return_value='{}: {}'.format(kms_key['KeyId'], kms_key['Description'])))
575+
monkeypatch.setattr('senza.templates.postgresapp.encrypt', MagicMock(return_value='encrypted_string'))
576+
567577
runner = CliRunner()
568578

569579
with runner.isolated_filesystem():

0 commit comments

Comments
 (0)