コード例 #1
0
ファイル: ApiDeploy.py プロジェクト: Travelport-Czech/apila
 def run(self, clients, cache):
     api_name = name_constructor.api_name(self.params['api'],
                                          self.config['user'],
                                          self.config['branch'])
     client = clients.get('apigateway')
     api_id = bototools.get_cached_api_id_if_exists(client, cache, api_name)
     if api_id is None:
         return (False, "Api '%s' not found" % api_name)
     response = client.get_deployments(restApiId=api_id)
     response = client.create_deployment(
         restApiId=api_id, stageName=self.params['stage_name'])
     return (True, '')
コード例 #2
0
ファイル: ApiTest.py プロジェクト: Travelport-Czech/apila
 def run(self, clients, cache):
     api_name = name_constructor.api_name(self.params['api'],
                                          self.config['user'],
                                          self.config['branch'])
     path = self.params['path']
     method = self.params['method']
     placeholders = self.params.get('placeholders', {})
     queries = self.params.get('query', {})
     client = clients.get('apigateway')
     api_id = bototools.get_cached_api_id_if_exists(client, cache, api_name)
     if api_id is None:
         return (False, "Api '%s' not found" % api_name)
     resources_by_path = bototools.get_resources_by_path(client, api_id)
     if path not in resources_by_path:
         return (False, "Path '%s' not found in api %s" % (path, api_name))
     path_id = resources_by_path[path]['id']
     method_info = client.get_method(restApiId=api_id,
                                     resourceId=path_id,
                                     httpMethod=method)
     # arn:aws:apigateway:eu-central-1:lambda:path/2015-03-31/functions/arn:aws:lambda:eu-central-1:860303221267:function:main_srb_afd_attemptEvaluate/invocations
     method_uri = method_info['methodIntegration']['uri']
     region = method_uri.split(':')[3]
     url_to_test = 'https://%(api_id)s.execute-api.%(region)s.amazonaws.com/%(stage)s%(path)s%(query)s' % {
         'api_id': api_id,
         'region': region,
         'stage': self.params['stage_name'],
         'path': path.format(**placeholders),
         'query': ('?' + urlencode(queries)) if queries else ''
     }
     headers = {}
     if 'authorization' in self.params:
         headers['Authorization'] = self.params['authorization']
     if method == 'POST':
         r = requests.post(url_to_test,
                           data=self.params['request'],
                           headers=headers)
     elif method == 'GET':
         r = requests.get(url_to_test,
                          params=self.params['request'],
                          headers=headers)
     elif method == 'DELETE':
         r = requests.delete(url_to_test,
                             params=self.params['request'],
                             headers=headers)
     else:
         return (False, 'Tested method must be POST, GET nebo DELETE')
     response = r.json()
     match = self.anyMatch(self.params['response'], response)
     if match:
         return (True, '')
     else:
         return (False, 'Response %s not contain expected %s' %
                 (str(response), self.params['response']))
コード例 #3
0
ファイル: ApiAuthorizer.py プロジェクト: MiseCZ/apila
 def run(self, clients, cache):
     api_name = name_constructor.api_name(self.params['api'],
                                          self.config['user'],
                                          self.config['branch'])
     lambda_name = name_constructor.lambda_name(self.params['lambda'],
                                                self.config['user'],
                                                self.config['branch'])
     authorizer_name = self.params['name']
     cache_ttl = int(
         self.params['cache_ttl']) if 'cache_ttl' in self.params else 0
     client = clients.get('apigateway')
     lambda_client = clients.get('lambda')
     api_id = bototools.get_cached_api_id_if_exists(client, cache, api_name)
     if api_id is None:
         return (False, "Api '%s' not found" % api_name)
     lambda_params = bototools.get_lambda_params(clients.get('lambda'),
                                                 cache, lambda_name, '', '')
     if not lambda_params:
         return (False, "Lambda function '%s' not found" % lambda_name)
     lambda_arn = bototools.get_lambda_arn(lambda_params)
     authorizer = bototools.get_authorizer_by_name(client, api_id,
                                                   authorizer_name)
     if not authorizer:
         self.create(client, api_id, authorizer_name, lambda_arn, cache_ttl)
         permissions_arn = self.get_permission_arn(api_id, lambda_params)
         self.add_permission(lambda_client, lambda_name, permissions_arn,
                             uuid.uuid4().hex)
         return (True, self.CREATED)
     patch = []
     if authorizer['authorizerResultTtlInSeconds'] != cache_ttl:
         patch.append({
             'op': 'replace',
             'path': '/authorizerResultTtlInSeconds',
             'value': str(cache_ttl)
         })
     if authorizer['type'].lower() != 'token':
         patch.append({'op': 'replace', 'path': '/type', 'value': 'TOKEN'})
     if authorizer['authorizerUri'] != lambda_arn:
         patch.append({
             'op': 'replace',
             'path': '/authorizerUri',
             'value': lambda_arn
         })
     if patch:
         client.update_authorizer(restApiId=api_id,
                                  authorizerId=authorizer['id'],
                                  patchOperations=patch)
         return (True, self.CHANGED)
     return (True, '')
コード例 #4
0
def get_yaml_tags_constructors(config):
    return {
        '!table_name':
        (lambda loader, node: name_constructor.table_name(
            loader.construct_scalar(node), config),
         'create a table name from given base name and config.yml\n    (uses fields user and branch from dict dynamodb if present, else from root config)'
         ),
        '!api_name': (lambda loader, node: name_constructor.api_name(
            loader.construct_scalar(node), config['user'], config['branch']),
                      'create an api name from given base name and config.yml'
                      ),
        '!lambda_name': (lambda loader, node: name_constructor.lambda_name(
            loader.construct_scalar(node), config['user'], config['branch']
        ), 'create a lambda name from given base name and config.yml'),
        '!config': (lambda loader, node: config[loader.construct_scalar(node)],
                    'return config value for given key'),
        '!template':
        (lambda loader, node: loader.construct_scalar(node).format(**config),
         'use given string as a template for rendering config.yml\n    i.e.: "-name !template Super task for an user {user} on a branch {branch}"\n    Don\'t use this to compose a lambda name, an api name etc - use defined functions for this!!!'
         )
    }
コード例 #5
0
    def run(self, clients, cache):
        api_name = name_constructor.api_name(self.params['api'],
                                             self.config['user'],
                                             self.config['branch'])
        lambda_name = name_constructor.lambda_name(self.params['lambda'],
                                                   self.config['user'],
                                                   self.config['branch'])
        lambda_params = bototools.get_lambda_params(clients.get('lambda'),
                                                    cache, lambda_name,
                                                    self.params['path'],
                                                    self.params['method'])
        if lambda_params is None:
            return (False, "Lambda function '%s' not found" % lambda_name)
        lambda_arn = bototools.get_lambda_arn(lambda_params)
        path = self.params['path']
        client = clients.get('apigateway')
        api_id = bototools.get_cached_api_id_if_exists(client, cache, api_name)
        if api_id is None:
            return (False, "Api '%s' not found" % api_name)
        result = ''
        resources_by_path = bototools.get_resources_by_path(client, api_id)
        if path in resources_by_path:
            path_id = resources_by_path[path]['id']
        else:
            path_id = bototools.create_resource_id_by_path(
                client, api_id, path, resources_by_path)
            result = self.CREATED
        cache.put('resource', api_name + ':' + path, path_id)
        try:
            method_info = client.get_method(restApiId=api_id,
                                            resourceId=path_id,
                                            httpMethod=self.params['method'])


#{u'apiKeyRequired': False, u'httpMethod': u'POST', u'methodIntegration': {u'integrationResponses': {u'200': {u'responseTemplates': {u'application/json': None}, u'statusCode': u'200'}}, u'passthroughBehavior': u'WHEN_NO_MATCH', u'cacheKeyParameters': [], u'uri': u'arn:aws:apigateway:eu-central-1:lambda:path/2015-03-31/functions/arn:aws:lambda:eu-central-1:860303221267:function:main_srbt_afd_attemptEvaluate/invocations', u'httpMethod': u'POST', u'cacheNamespace': u'ez205t', u'type': u'AWS'}, u'requestParameters': {}, 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': '7b577a6b-913a-11e6-afe9-53022ccbd313', 'HTTPHeaders': {'x-amzn-requestid': '7b577a6b-913a-11e6-afe9-53022ccbd313', 'date': 'Thu, 13 Oct 2016 11:45:04 GMT', 'content-length': '594', 'content-type': 'application/json'}}, u'methodResponses': {u'200': {u'responseModels': {u'application/json': u'Empty'}, u'statusCode': u'200'}}, u'authorizationType': u'NONE'}
        except botocore.exceptions.ClientError:
            permissions_arn = self.get_permission_arn(api_id, lambda_params)
            self.create_method(client, api_id, path_id, lambda_arn)
            self.add_permission(clients.get('lambda'), lambda_name,
                                permissions_arn,
                                uuid.uuid4().hex)
            return (True, self.CREATED)
        if 'methodIntegration' not in method_info:
            self.create_integration(client, api_id, path_id, lambda_arn)
            method_info['methodIntegration'] = client.get_integration(
                restApiId=api_id,
                resourceId=path_id,
                httpMethod=self.params['method'])
            result = self.CHANGED
        method_integration = method_info['methodIntegration']
        if method_integration['type'] != 'AWS_PROXY':
            return (
                False,
                "Method integration request must be of type 'AWS_PROXY', not '%s'"
                % method_integration['type'])
        if method_integration['uri'] != lambda_arn:
            client.update_integration(restApiId=api_id,
                                      resourceId=path_id,
                                      httpMethod=self.params['method'],
                                      patchOperations=[{
                                          'op': 'replace',
                                          'path': '/uri',
                                          'value': lambda_arn
                                      }])
            result = self.CHANGED
        patch = []
        if 'authorizer' in self.params:
            if method_info['authorizationType'] != 'CUSTOM':
                patch.append({
                    'op': 'replace',
                    'path': '/authorizationType',
                    'value': 'CUSTOM'
                })
            authorizer = bototools.get_authorizer_by_name(
                client, api_id, self.params['authorizer'])
            if 'authorizerId' not in method_info or method_info[
                    'authorizerId'] != authorizer['id']:
                patch.append({
                    'op': 'replace',
                    'path': '/authorizerId',
                    'value': authorizer['id']
                })
        else:
            if method_info['authorizationType'] != 'NONE':
                patch.append({
                    'op': 'replace',
                    'path': '/authorizationType',
                    'value': 'NONE'
                })
        if patch:
            client.update_method(restApiId=api_id,
                                 resourceId=path_id,
                                 httpMethod=self.params['method'],
                                 patchOperations=patch)
            result = self.CHANGED
        return (True, result)