上一节我们提到了如何连接EC2,也就是boto.ec2.connect_to_region()方法。在连接到EC2后,我们可以获取当前所在区域的instance信息,下面我们来看几种常用的方法。首先还是先连接到EC2:
import boto
conn = boto.ec2.connect_to_region('ap-northeast-1')
reservations = conn.get_all_instances()
这个方法会获取class boto.resultset.ResultSet 并返回一个list值。类似于:
[Reservation:xxxxxxx, Reservation:xxxxxxx]
这里要理解reservation的概念,它不是instance的id,它是包含instance的一个object或者理解为action。
我们可以在AWS的控制台中通过手动的 Launch instance来理解:
在我们手动launch一个实例的时候,我们可以配置instance的type、network、count等等一系列的属性值,最后Launch出我们想要的instance。当然我们可以一次Launch一个instance也可以一次launch N多个instance。一个成功Launch的过程就是一个reservation,所以一个reservation里可以包含1个instance也可以包含N多次instance,也就是说reservation是一个成功Launch所产生的对象。
前面我们获取到了所有的reservation,而且这是一个列表,那么列表中第一个元素reservations[0]就是该区域目前存在的第一个被Launch的动作。我们通过这个元素可以取出该reservation中的instance信息。
instances = reservations[0].instances
这里获取到的instances 同样是一个list,这里的元素就是具体的instance的id,也就是AWS控制台上可以看到的Instance_ID,一个id对应一个instance。
instance = instances[0]
这样我们就可以取到instance,它是一个
class 'boto.ec2.instance.Instance',也就是一个实例化后的instance class。
它有非常多的属性可以供我们查看,我们可以使用instance.__doc__来查看它的说明我文档,你能在这里找到所有的属性值。AWS控制台上大多数的值都可以在这里获取,比如常用的:
state 运行状态
launch_time 创建日期
ip_address public ip
private_ip_address private ip
更多属性值可以参考官方文档http://boto.readthedocs.org/en/latest/ref/ec2.html#module-boto.ec2.instance
下一节我们讲解如何通过boto Launch一个instance。