Remove a file from an AWS S3 bucket.

    :param awsclient:
    :param bucket:
    :param key:
    :return:
434468
def remove_file_from_s3(awsclient, bucket, key):
    
    client_s3 = awsclient.get_client('s3')
    response = client_s3.delete_object(Bucket=bucket, Key=key)
1163168
def delete(self, key, cas=0):
        
        server = self._get_server(key)
        return server.delete(key, cas)
1290374
def del_stream(self, bucket, label):
        
        bucket = self._require_bucket(bucket)
        key = self._require_key(bucket, label)
        key.delete()
365200
def get(self, s3_path, destination_local_path):
        
        (bucket, key) = self._path_to_bucket_and_key(s3_path)
        # download the file
        self.s3.meta.client.download_file(bucket, key, destination_local_path)
562100
def remove_s3_bucket():
    """"""
    logger.debug("[#] Removing S3 bucket")
    client = boto3.client("s3", region_name=PRIMARY_REGION)
    buckets = client.list_buckets()
    matches = [x for x in buckets.get('Buckets', list())
               if x['Name'].startswith(S3_BUCKET_NAME)]
    if len(matches) == 0:
        return
    match = matches.pop()['Name']
    try:
        response = client.list_objects_v2(
            Bucket=match,
        )
    except client.exceptions.NoSuchBucket:
        logger.info("[!] S3 bucket already deleted")
        return True

    while response['KeyCount'] > 0:
        logger.debug('[*] Deleting %d objects from bucket %s'
                     % (len(response['Contents']), match))
        response = client.delete_objects(
            Bucket=match,
            Delete={
                'Objects': [{'Key': obj['Key']} for obj in response['Contents']]
            }
        )
        response = client.list_objects_v2(
            Bucket=match,
        )

    logger.debug('[#] Deleting bucket %s' % match)
    response = client.delete_bucket(
        Bucket=match
    )
    logger.info("[#] Successfully deleted the S3 bucket")

    return response
883085
def stop_s3_bucket(client, resource):
    

    bucket_policy = {
        'Version': '2012-10-17',
        'Id': 'PutObjPolicy',
        'Statement': [
            {
                'Sid': 'cinqDenyObjectUploads',
                'Effect': 'Deny',
                'Principal': '*',
                'Action': ['s3:PutObject', 's3:GetObject'],
                'Resource': 'arn:aws:s3:::{}/*'.format(resource.id)
            }
        ]
    }

    s3_removal_lifecycle_policy = {
        'Rules': [
            {'Status': 'Enabled',
             'NoncurrentVersionExpiration': {u'NoncurrentDays': 1},
             'Filter': {u'Prefix': ''},
             'Expiration': {
                 u'Date': datetime.utcnow().replace(
                     hour=0, minute=0, second=0, microsecond=0
                 ) + timedelta(days=dbconfig.get('lifecycle_expiration_days', NS_AUDITOR_REQUIRED_TAGS, 3))
             },
             'AbortIncompleteMultipartUpload': {u'DaysAfterInitiation': 3},
             'ID': 'cloudInquisitor'}
        ]
    }

    policy_exists = s3_removal_policy_exists(client, resource)
    lifecycle_policy_exists = s3_removal_lifecycle_policy_exists(client, resource)
    if policy_exists and lifecycle_policy_exists:
        return ActionStatus.IGNORED, {}

    if not policy_exists:
        client.put_bucket_policy(Bucket=resource.id, Policy=json.dumps(bucket_policy))
        logger.info('Added policy to prevent putObject in s3 bucket {} in {}'.format(
            resource.id,
            resource.account.account_name
        ))

    if not lifecycle_policy_exists:
        # Grab S3 Metrics before lifecycle policies start removing objects

        client.put_bucket_lifecycle_configuration(
            Bucket=resource.id,
            LifecycleConfiguration=s3_removal_lifecycle_policy
        )
        logger.info('Added policy to delete bucket contents in s3 bucket {} in {}'.format(
            resource.id,
            resource.account.account_name
        ))

    return ActionStatus.SUCCEED, resource.metrics()
1045485
def delete_key(self, key_to_delete):
        
        log = logging.getLogger(self.cls_logger + '.delete_key')

        log.info('Attempting to delete key: {k}'.format(k=key_to_delete))
        try:
            self.s3client.delete_object(Bucket=self.bucket_name, Key=key_to_delete)
        except ClientError:
            _, ex, trace = sys.exc_info()
            log.error('ClientError: Unable to delete key: {k}\n{e}'.format(k=key_to_delete, e=str(ex)))
            return False
        else:
            log.info('Successfully deleted key: {k}'.format(k=key_to_delete))
            return True
460759
public function delete($key, $bucket = '')
    {
        $bucket = $bucket ? $bucket : $this->bucket;
        $encodedEntryURI = self::urlBase64Encode("{$bucket}:{$key}");
        $url = "/delete/{$encodedEntryURI}";
        return $this->fileHandle($url);
    }
366404
def delete(self, key):
        
        validate_is_bytes(key)

        self.root_hash = self._set(self.root_hash, encode_to_bin(key), b'')
1167943
def __put_key(self, local_file, target_file, acl='public-read', del_after_upload=False, overwrite=True, source="filename"):
        """"""
        action_word = "moving" if del_after_upload else "copying"

        try:
            self.k.key = target_file  # setting the path (key) of file in the container

            if source == "filename":
                # grabs the contents from local_file address. Note that it loads the whole file into memory
                self.k.set_contents_from_filename(local_file, self.AWS_HEADERS)
            elif source == "fileobj":
                self.k.set_contents_from_file(local_file, self.AWS_HEADERS)
            elif source == "string":
                self.k.set_contents_from_string(local_file, self.AWS_HEADERS)
            else:
                raise Exception("%s is not implemented as a source." % source)
            self.k.set_acl(acl)  # setting the file permissions
            self.k.close()  # not sure if it is needed. Somewhere I read it is recommended.

            self.printv("%s %s to %s" % (action_word, local_file, target_file))
            # if it is supposed to delete the local file after uploading
            if del_after_upload and source == "filename":
                try:
                    os.remove(local_file)
                except:
                    logger.error("Unable to delete the file: ", local_file, exc_info=True)

            return True

        except:
            logger.error("Error in writing to %s", target_file, exc_info=True)
            return False
927353
async def release_key(self, key, chat=None, user=None):
        
        if not self.storage.has_bucket():
            raise RuntimeError('This storage does not provide Leaky Bucket')

        if user is None and chat is None:
            user = types.User.get_current()
            chat = types.Chat.get_current()

        bucket = await self.storage.get_bucket(chat=chat, user=user)
        if bucket and key in bucket:
            del bucket['key']
            await self.storage.set_bucket(chat=chat, user=user, bucket=bucket)
            return True
        return False
839796
def copy_on_s3(self, src_file_name, dst_file_name, bucket_name):
        
        try:
            self.s3_client.head_bucket(Bucket=bucket_name)
        except botocore.exceptions.ClientError as e:  # pragma: no cover
            # If a client error is thrown, then check that it was a 404 error.
            # If it was a 404 error, then the bucket does not exist.
            error_code = int(e.response['Error']['Code'])
            if error_code == 404:
                return False

        copy_src = {
            "Bucket": bucket_name,
            "Key": src_file_name
        }
        try:
            self.s3_client.copy(
                CopySource=copy_src,
                Bucket=bucket_name,
                Key=dst_file_name
            )
            return True
        except botocore.exceptions.ClientError:  # pragma: no cover
            return False
1005122
def remove_object(self, instance, bucket_name, object_name):
        
        url = '/buckets/{}/{}/{}'.format(instance, bucket_name, object_name)
        self._client.delete_proto(url)
1155981
def delete_api_key(apiKey, region=None, key=None, keyid=None, profile=None):
    '''
    

    '''
    try:
        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
        conn.delete_api_key(apiKey=apiKey)
        return {'deleted': True}
    except ClientError as e:
        return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
1219771
def remove_key(pki_dir, id_):
    '''
    
    '''
    key = os.path.join(pki_dir, 'minions', id_)
    if os.path.isfile(key):
        os.remove(key)
        log.debug('Deleted \'%s\'', key)
1243843
def _remove_event_source(awsclient, evt_source, lambda_arn):
    
    event_source_obj = _get_event_source_obj(awsclient, evt_source)
    if event_source_obj.exists(lambda_arn):
        event_source_obj.remove(lambda_arn)
333120
def remove(self):
        
        ''' 
            
        '''
    
        title = '%s.remove' % self.__class__.__name__
    
    # request bucket delete 
        self.s3.delete_bucket(self.bucket_name)

    # return confirmation
        exit_msg = '%s collection has been removed from S3.' % self.bucket_name
        return exit_msg