如何扩展 Boto3 资源?

How to extend a Boto3 resource?

在 boto3 上,如何扩展 ResourceModel?我不想做的是继承 boto3.resources.factory.ec2.Instance 并向其添加 run 方法。该方法将用于通过 SSH 在由 Python 对象表示的 EC2 实例上远程执行 运行 命令。我希望以一种干净的方式做到这一点,即不诉诸猴子补丁或其他晦涩的技术。

更新

基于 , I came up with the following code. Requires a recent version of Boto 3, and Spur 的 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')

简短的回答是这还不可能,但计划允许进行此类自定义。您已经可以通过 S3 客户端上提供的新 upload_filedownload_file 定制看到它们的实际效果。计划是对 Boto 3 资源使用相同类型的机制。

  1. Resources 在创建包含所有 methods/attributes
  2. 的属性字典的 class 时会触发某种事件
  3. 你将自己的方法挂接到属性字典中
  4. class 使用您的自定义方法创建 - 无需猴子修补。

看这里:

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

Boto 3 的可扩展性绝对在我们的关注范围内。