【问题标题】:How to extend a Boto3 resource?如何扩展 Boto3 资源?
【发布时间】:2015-09-26 04:16:16
【问题描述】:

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

更新

基于Daniel's answer,我想出了以下代码。需要最新版本的 Boto 3,以及用于 SSH 连接的 Spur (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')

【问题讨论】:

    标签: python boto boto3 botocore


    【解决方案1】:

    简短的回答是这尚不可能,但计划允许此类自定义。您已经可以在 S3 客户端上使用新的 upload_filedownload_file 自定义来查看它们的实际效果。计划是对 Boto 3 资源使用相同的机制。

    1. 在创建包含所有方法/属性的属性字典的类时,资源将触发某种事件
    2. 您将自己的方法挂钩到属性字典中
    3. 该类是使用您的自定义方法创建的 - 不需要猴子补丁。

    看这里:

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

    Boto 3 的可扩展性绝对是我们关注的焦点。

    【讨论】:

    • 谢谢丹尼尔。我根据您提供的资源编写了一些代码。我会在 boto3 准备好后尝试运行它。
    • 该主题已在 Extensibility Guide 下的 boto3 文档中介绍。
    • 谢谢本。我已经用一个可运行的代码 sn-p 更新了这个问题,并将接受这个答案。
    • 我还写了a blog post 来讲述我目前使用它的经历。可能对其他人有用。
    猜你喜欢
    • 2014-05-28
    • 1970-01-01
    • 2014-04-28
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多