在 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')
最佳答案
简短的回答是这还不可能,但计划允许进行此类自定义。您已经可以通过 S3 客户端上可用的新 upload_file
和 download_file
自定义看到它们的实际效果。计划是对 Boto 3 资源使用相同类型的机制。
- 资源会在创建包含所有方法/属性的属性字典的类时触发某种事件
- 将自己的方法挂接到属性字典中
- 该类是使用您的自定义方法创建的 - 无需猴子修补。
看这里:
https://github.com/boto/boto3/blob/develop/boto3/session.py#L314-L318 https://github.com/boto/boto3/tree/develop/boto3/s3
Boto 3 的可扩展性绝对在我们的关注范围内。
关于python - 如何扩展 Boto3 资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28996265/