如何扩展Boto3资源?

时间:2015-03-11 20:03:25

标签: python boto boto3 botocore

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

更新

根据Daniel's answer,我想出了以下代码。需要最新版本的Boto 3和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')

1 个答案:

答案 0 :(得分:2)

简短的回答是,这还不可能,但计划允许这种自定义。您已经可以使用S3客户端上提供的新upload_filedownload_file自定义功能查看它们。计划是对Boto 3资源使用相同类型的机制。

  1. 在创建包含所有方法/属性的属性dict的类时,资源将触发某种事件
  2. 您将自己的方法挂钩到属性dict
  3. 使用您的自定义方法创建类 - 不需要猴子修补。
  4. 看看这里:

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

    Boto 3的可扩展性肯定在我们的雷达上。