Ejemplo n.º 1
0
    def create_wsgi_api(self):
        """Create/Update api definition for wsgi app"""
        swagger_api = False
        # If there is already an exsiting swagger api template,
        # fetch it so we won't  duplicate it 
        #if os.path.isfile(self.get_swagger_template()) and self.get_apigateway_name():
        swagger_api = self.if_api_exist_by_name(self.get_apigateway_name())
        
        iam = IAM()

        for lm_func in self._config.get('Lambda'):
            if lm_func.get('Type') != AWSLambda.FUNCTION_TYPE_WSGI or lm_func.get('DisableApiGateway'):
                continue
            
            function_name = self.get_lmdo_format_name(lm_func.get('FunctionName'))

            role = iam.get_lambda_apigateway_default_role(function_name)
            
            Oprint.info('Create/Update API Gateway for wsgi function {}'.format(lm_func.get('FunctionName')), 'apigateway')

            to_replace = {
                "$title": self.get_apigateway_name(),
                "$version": str(datetime.datetime.utcnow()),
                "$basePath": lm_func.get('ApiBasePath') or '/res',
                "$apiRegion": self.get_region(),
                "$functionRegion": self.get_region(),
                "$accountId": self.get_account_id(),
                "$functionName": function_name,
                "$credentials": role['Role'].get('Arn')
            }

            # Enable cognito user pool as authorizer
            if lm_func.get('CognitoUserPoolId'):
                se_replace = {
                    "$apiRegion": self.get_region(),
                    "$accountId": self.get_account_id(),
                    "$userPoolId": lm_func.get('CognitoUserPoolId'),
                    "$CognitoUserPool": 'CognitoUserPool-{}'.format(lm_func.get('FunctionName'))
                }

                to_replace["$securityDefinitions"] = self.get_apigateway_authorizer(se_replace)
                to_replace["$authorizer"] = '{"' + str(se_replace['$CognitoUserPool'])+'":[]}'
            else:
                to_replace["$securityDefinitions"] = ''
                to_replace["$authorizer"] = ''

            template_dir = get_template(APIGATEWAY_SWAGGER_WSGI)
            if not template_dir:
                Oprint.err('Template {} for creating wsgi APIGateway hasn\'t been installed or missing'.format(APIGATEWAY_SWAGGER_WSGI), 'apigateway')
            
            with open(template_dir, 'r') as outfile:
                body = update_template(outfile.read(), to_replace)
                
                if not swagger_api:
                    swagger_api = self.import_rest_api(body)
                else:
                    # Always overwrite for update
                    self.put_rest_api(swagger_api.get('id'), body, 'merge')

        return swagger_api
Ejemplo n.º 2
0
    def create_api_by_swagger(self):
        """Create/Update api definition by swagger"""
        # Exist if no swagger definition
        if not os.path.isfile(self.get_swagger_template()):
            return True

        api = self.if_api_exist_by_name(self.get_apigateway_name())
        with open(self.get_swagger_template(), 'r') as outfile:
            to_replace = {
                "$title": self.get_apigateway_name(),
                "$version": str(datetime.datetime.utcnow())
            }

            # Replace variable in swagger template with content in a file.
            var_to_file = self._config.get('ApiVarMapToFile')
            if (var_to_file):
                for var_name, file_name in var_to_file.iteritems():
                    with open('{}/{}'.format(SWAGGER_DIR, file_name), 'r') as ofile:
                        file_content = ofile.read()
                        to_replace[var_name] = file_content.replace('\n', '\\n').replace('"', '\\"')

            var_to_var = self._config.get('ApiVarMapToVar')
            if var_to_var:
                for var_name, replacement in var_to_var.iteritems():
                    to_replace[var_name] = replacement
                    
            body = update_template(outfile.read(), to_replace)

            if not api:
                return self.import_rest_api(body)
            else:
                # Always overwrite for update
                return self.put_rest_api(api.get('id'), body, 'overwrite')

        return False
Ejemplo n.º 3
0
    def get_apigateway_authorizer(self, to_replace):
        template = ',"securityDefinitions": {' \
              '"$CognitoUserPool": {' \
                  '"type": "apiKey",' \
                  '"name": "Authorization",'\
                  '"in": "header",' \
                  '"x-amazon-apigateway-authtype": "cognito_user_pools",' \
                  '"x-amazon-apigateway-authorizer": {' \
                    '"type": "cognito_user_pools",' \
                      '"providerARNs": [' \
                        '"arn:aws:cognito-idp:$apiRegion:$accountId:userpool/$userPoolId"' \
                      ']' \
                 '}' \
              '}' \
          '}' 

        return update_template(template, to_replace)
Ejemplo n.º 4
0
Archivo: iam.py Proyecto: piwell/lmdo
    def create_lambda_role(self, role_name, role_policy):
        """
            Create role for Lambda, all policies
            store in the assume role policy doc
            so that we can do update
            If not set, will using default
            which enables Lambda for invoking
            and logging
        """
        try:
            Oprint.info(
                'Start creating role {} and policie for Lambda'.format(
                    role_name), 'iam')

            assume_roles = []
            if role_policy:
                assume_roles = role_policy.get('AssumeRoles')

            role_doc = self.get_lambda_default_assume_role_doc(
                extra_services=assume_roles)

            role = self.get_role(role_name)

            if not role:
                role = self._client.create_role(
                    RoleName=role_name,
                    AssumeRolePolicyDocument=json.dumps(role_doc))
            else:
                self._client.update_assume_role_policy(
                    RoleName=role_name, PolicyDocument=json.dumps(role_doc))

            to_replace = {
                "$region": self.get_region(),
                "$accountId": self.get_account_id()
            }

            policy_doc = []
            if role_policy and role_policy.get('PolicyDocument'):
                _, policy_doc = FileLoader(
                    file_path=role_policy.get('PolicyDocument')).process()
                policy_doc = policy_doc['Statement']

            policy_doc = self.get_lambda_default_policy_doc(
                extra_statement=policy_doc)

            policy_doc = update_template(json.dumps(policy_doc), to_replace)

            # Do inline policy so that when deleting the role, it'll be deleted
            self._client.put_role_policy(
                RoleName=role_name,
                PolicyName='{}-policy'.format(role_name),
                PolicyDocument=policy_doc)

            if role_policy and role_policy is dict and role_policy.get(
                    'ManagedPolicyArns'):
                for m_policy_arn in role_policy.get('ManagedPolicyArns'):
                    self._client.attach_role_policy(RoleName=role_name,
                                                    PolicyArn=m_policy_arn)

            Oprint.info(
                'Complete creating role {} and policie for Lambda'.format(
                    role_name), 'iam')
        except Exception as e:
            Oprint.err(e, 'iam')

        return role