How to extend the resource Boto3?

On boto3, how can I extend the ResourceModel ? What I do not need to do is subclass boto3.resources.factory.ec2.Instance and add the run method to it. This method will be used to remotely run commands in an EC2 instance represented by a Python object via SSH. I want to do it in a clean way, i.e. Without resorting to monkey patches or other obscure methods.

Update

Based on Daniel's answer , I came up with the following code. The latest version of Boto 3 and Spur is required to connect SSH ( pip install spur boto3 ).

 from boto3 import session from shlex import split from spur import SshShell # Customize here. REGION = 'AWS-REGION' INSTID = 'AWS-INSTANCE-ID' USERID = 'SSH-USER' def hook_ssh(class_attributes, **kwargs): def run(self, command): '''Run a command on the EC2 instance via SSH.''' # Create the SSH client. if not hasattr(self, '_ssh_client'): self._ssh_client = SshShell(self.public_ip_address, USERID) print(self._ssh_client.run(split(command)).output.decode()) class_attributes['run'] = run if __name__ == '__main__': b3s = session.Session() ec2 = b3s.resource('ec2', region_name=REGION) # Hook the "run" method to the "ec2.Instance" resource class. b3s.events.register('creating-resource-class.ec2.Instance', hook_ssh) # Run some commands. ec2.Instance(INSTID).run('uname -a') ec2.Instance(INSTID).run('uptime') 
+5
source share
1 answer

The short answer is that this is not yet possible, but it is planned to allow such settings. You can already see them in action with the new upload_file and download_file settings available on the S3 client. The plan is to use the same mechanism for Boto 3 resources.

  • Resources will trigger an event when creating a class that includes the dict attribute of all methods / attributes
  • You connect your own method to the dict attribute
  • The class is created using a custom method - no monkey fixes are required.

Take a look here:

https://github.com/boto/boto3/blob/develop/boto3/session.py#L314-L318 https://github.com/boto/boto3/tree/develop/boto3/s3

The Boto 3 extension is definitely on our radar.

+2
source

Source: https://habr.com/ru/post/1215175/


All Articles