Exemplo n.º 1
0
 def decrypt(self, encrypted_value):
     try:
         ciphertext_blob = base64.b64decode(encrypted_value.encode())
         response = self.client.decrypt(CiphertextBlob=ciphertext_blob)
         return response['Plaintext'].decode('utf-8')
     except Boto3Error as e:
         raise CfnSphereBotoError(e)
Exemplo n.º 2
0
 def get_parameter(self, name, with_decryption=True):
     try:
         return self.client.get_parameter(
             Name=name,
             WithDecryption=with_decryption)['Parameter']['Value']
     except (Boto3Error, ClientError) as e:
         raise CfnSphereBotoError(e)
Exemplo n.º 3
0
    def get_images(self, name_pattern):
        """
        Return list of AMIs matching the given name_pattern

        :param name_pattern: str: AMI name pattern
        :return: list(dict)
        :raise CfnSphereException:
        """
        filters = [{
            'Name': 'name',
            'Values': [name_pattern]
        }, {
            'Name': 'is-public',
            'Values': ['false']
        }, {
            'Name': 'state',
            'Values': ['available']
        }, {
            'Name': 'root-device-type',
            'Values': ['ebs']
        }]

        try:
            response = self.client.describe_images(ExecutableUsers=["self"],
                                                   Filters=filters)
        except (BotoCoreError, ClientError) as e:
            raise CfnSphereBotoError(e)

        if not response['Images']:
            raise CfnSphereException(
                "Could not find any private and available Taupage AMI")

        return response['Images']
Exemplo n.º 4
0
 def encrypt(self, key_id, cleartext_string):
     try:
         response = self.client.encrypt(KeyId=key_id,
                                        Plaintext=cleartext_string)
         return base64.b64encode(response['CiphertextBlob']).decode('utf-8')
     except (Boto3Error, ClientError) as e:
         raise CfnSphereBotoError(e)
Exemplo n.º 5
0
 def get_contents_from_url(self, url):
     try:
         (_, bucket_name, key_name) = self._parse_url(url)
         s3_object = self.s3.Object(bucket_name, key_name)
         return s3_object.get(
             ResponseContentEncoding='utf-8')["Body"].read().decode('utf-8')
     except (Boto3Error, BotoCoreError, ClientError) as e:
         raise CfnSphereBotoError(e)
Exemplo n.º 6
0
 def get_contents_from_url(self, url):
     try:
         (_, bucket_name, key_name) = self._parse_url(url)
         bucket = self.conn.get_bucket(bucket_name)
         key = bucket.get_key(key_name)
         return key.get_contents_as_string()
     except BotoServerError as e:
         raise CfnSphereBotoError(e)
Exemplo n.º 7
0
    def test_get_latest_value_raises_exception_on_error(self):
        self.cfn_mock.return_value.get_stack_parameters_dict.side_effect = CfnSphereBotoError(
            Exception("foo"))

        resolver = ParameterResolver()
        with self.assertRaises(CfnSphereException):
            resolver.get_latest_value('my-key', '|keepOrUse|default-value',
                                      'my-stack')
Exemplo n.º 8
0
 def get_stacks(self):
     """
     Get all stacks
     :return: List(boto3.resources.factory.cloudformation.Stack)
     :raise CfnSphereBotoError:
     """
     try:
         return list(self.resource.stacks.all())
     except (BotoCoreError, ClientError) as e:
         raise CfnSphereBotoError(e)
Exemplo n.º 9
0
 def my_retried_method(count_func):
     count_func()
     exception = CfnSphereBotoError(
         ClientError(error_response={
             "Error": {
                 "Code": "Throttling",
                 "Message": "Rate exceeded"
             }
         },
                     operation_name="DescribeStacks"))
     raise exception
Exemplo n.º 10
0
 def validate_template(self, template):
     """
     Validate template
     :param template: CloudFormationTemplate
     :return: boolean (true if valid)
     """
     try:
         self.client.validate_template(
             TemplateBody=template.get_template_json())
         return True
     except (BotoCoreError, ClientError) as e:
         raise CfnSphereBotoError(e)
Exemplo n.º 11
0
 def get_stack_description(self, stack_name):
     """
     Get a stacks descriptions
     :param stack_name: string
     :return dict
     :raise CfnSphereBotoError:
     """
     try:
         return self.client.describe_stacks(
             StackName=stack_name)["Stacks"][0]
     except (BotoCoreError, ClientError) as e:
         raise CfnSphereBotoError(e)
Exemplo n.º 12
0
 def get_stacks(self):
     try:
         result = []
         response = self.conn.describe_stacks()
         result.extend(response)
         while response.next_token:
             response = self.conn.describe_stacks(
                 next_token=response.next_token)
             result.extend(response)
         return result
     except BotoServerError as e:
         raise CfnSphereBotoError(e)
Exemplo n.º 13
0
    def encrypt(self, key_id, cleartext_string, encryption_context=None):
        if encryption_context is None:
            encryption_context = {}

        try:
            response = self.client.encrypt(
                KeyId=key_id,
                Plaintext=cleartext_string,
                EncryptionContext=encryption_context)

            return base64.b64encode(response['CiphertextBlob']).decode('utf-8')
        except (Boto3Error, ClientError) as e:
            raise CfnSphereBotoError(e)
Exemplo n.º 14
0
    def test_validate_stack_is_ready_for_action_raises_proper_exception_on_boto_error(self, get_stack_mock):
        get_stack_mock.side_effect = CfnSphereBotoError(None)

        stack_mock = Mock()
        stack_mock.stack_name = "my-stack"
        stack_mock.stack_status = "UPDATE_COMPLETE"
        get_stack_mock.return_value = stack_mock

        stack = CloudFormationStack('', [], 'my-stack', 'my-region')

        cfn = CloudFormation()
        with self.assertRaises(CfnSphereBotoError):
            cfn.validate_stack_is_ready_for_action(stack)
Exemplo n.º 15
0
 def get_stack_events(self, stack_name):
     """
     Get recent stack events for a given stack_name
     :param stack_name: str
     :return: list(dict)
     """
     try:
         paginator = self.client.get_paginator('describe_stack_events')
         pages = paginator.paginate(StackName=stack_name,
                                    PaginationConfig={'MaxItems': 100})
         return next(iter(pages))["StackEvents"]
     except (BotoCoreError, ClientError) as e:
         raise CfnSphereBotoError(e)
Exemplo n.º 16
0
    def decrypt(self, encrypted_value, encryption_context=None):
        if encryption_context is None:
            encryption_context = {}

        try:
            ciphertext_blob = base64.b64decode(encrypted_value.encode())
            response = self.client.decrypt(
                CiphertextBlob=ciphertext_blob,
                EncryptionContext=encryption_context)
            return response['Plaintext'].decode('utf-8')
        except Boto3Error as e:
            raise CfnSphereBotoError(e)
        except ClientError as e:
            raise CfnSphereException(e)
Exemplo n.º 17
0
 def get_stack_descriptions(self):
     """
     Get all stacks stack descriptions
     :return List(dict)
     :raise CfnSphereBotoError:
     """
     try:
         stacks = []
         for page in self.client.get_paginator(
                 'describe_stacks').paginate():
             stacks += page["Stacks"]
         return stacks
     except (BotoCoreError, ClientError) as e:
         raise CfnSphereBotoError(e)
Exemplo n.º 18
0
    def validate_stack_is_ready_for_action(self, stack):
        try:
            cfn_stack = self.get_stack(stack.name)
        except BotoServerError as e:
            raise CfnSphereBotoError(e)

        valid_states = [
            "CREATE_COMPLETE", "UPDATE_COMPLETE", "ROLLBACK_COMPLETE",
            "UPDATE_ROLLBACK_COMPLETE"
        ]

        if cfn_stack.stack_status not in valid_states:
            raise CfnStackActionFailedException(
                "Stack {0} is in '{1}' state.".format(cfn_stack.stack_name,
                                                      cfn_stack.stack_status))
Exemplo n.º 19
0
    def stack_exists(self, stack_name):
        """
        Check if a stack exists for given stack_name

        :param stack_name: str
        :return: bool
        """
        try:
            if self.get_stack(stack_name).stack_status:
                return True
            else:
                return False
        except (BotoCoreError, ClientError) as e:
            if self.is_boto_stack_does_not_exist_exception(e):
                return False
            else:
                raise CfnSphereBotoError(e)
Exemplo n.º 20
0
    def decrypt(self, encrypted_value):
        try:
            response = self.conn.decrypt(
                base64.b64decode(encrypted_value.encode()))
        except TypeError as e:
            raise InvalidEncryptedValueException(
                "Could not decode encrypted value: {0}".format(e), e)
        except binascii.Error as e:
            raise InvalidEncryptedValueException(
                "Could not decode encrypted value: {0}".format(e))
        except InvalidCiphertextException as e:
            raise InvalidEncryptedValueException(
                "Could not decrypted value: {0}".format(e))
        except BotoServerError as e:
            raise CfnSphereBotoError(e)

        return response['Plaintext']
Exemplo n.º 21
0
    def get_taupage_images(self):
        filters = {
            'name': ['Taupage-AMI-*'],
            'is-public': ['false'],
            'state': ['available'],
            'root-device-type': ['ebs']
        }
        try:
            response = self.conn.get_all_images(executable_by=["self"],
                                                filters=filters)
        except BotoServerError as e:
            raise CfnSphereBotoError(e)

        if not response:
            raise CfnSphereException(
                "Could not find any private and available Taupage AMI")

        return response
Exemplo n.º 22
0
        def wrapper(*args, **kwds):
            retries = 0

            while True:
                try:
                    return function(*args, **kwds)
                except (CfnSphereBotoError, BotoCoreError, ClientError) as e:
                    if isinstance(e, (BotoCoreError, ClientError)):
                        # Wrap Boto exception in CfnSphereBotoError so we can
                        # use it's `is_throttling_exception` attribute.
                        is_throttling_exception = CfnSphereBotoError(e).is_throttling_exception
                    else:
                        is_throttling_exception = e.is_throttling_exception

                    if not is_throttling_exception or retries >= max_retries:
                        raise e

                    sleep_time = pause_time_multiplier * (2 ** retries)
                    logger.warn(
                        "{0} call failed with: '{1}' (Will retry in {2}s)".format(function.__name__, e, sleep_time))
                    time.sleep(sleep_time)
                    retries += 1
Exemplo n.º 23
0
 def get_stack_state(self, stack_name):
     try:
         stack = self.conn.describe_stacks(stack_name)
         return stack.status
     except BotoServerError as e:
         raise CfnSphereBotoError(e)
Exemplo n.º 24
0
 def get_stack(self, stack_name):
     try:
         return self.conn.describe_stacks(stack_name)[0]
     except BotoServerError as e:
         raise CfnSphereBotoError(e)
    def test_get_latest_value_returns_default_value(self, kms, ec2_api, cfn_mock):
        cfn_mock.return_value.get_stack_parameters_dict.side_effect = CfnSphereBotoError(BotoServerError("500", "foo"))

        resolver = ParameterResolver()
        with self.assertRaises(CfnSphereException):
            resolver.get_latest_value('my-key', '|keepOrUse|default-value', 'my-stack')