Raf*_*afa 5 python boto botocore boto3
在boto3上,我该如何扩展ResourceModel?我不想做的是子类boto3.resources.factory.ec2.Instance并run为其添加一个方法.该方法将用于通过SSH远程运行由Python对象表示的EC2实例上的命令.我希望以干净的方式做到这一点,即不使用猴子补丁或其他模糊技术.
更新
根据Daniel的回答,我提出了以下代码.需要最新版本的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')
Run Code Online (Sandbox Code Playgroud)
简而言之,这尚不可能,但计划允许此类定制。您已经可以看到它们在 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 的可扩展性绝对是我们关注的焦点。