runinstances.py

#coding:utf-8

import boto.ec2
import re
import json
import time

# 读取变量

## boto2
conn = boto.ec2.connect_to_region("us-west-2",aws_access_key_id='AKIAIYMHAQTW6CXZ6YJA',aws_secret_access_key='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')

def create_instance(info=[]):
    # 创建seuciryt
    security_name = "security-%s"%info[0]
    security_ports = info[7].split("__")
    web = conn.create_security_group(security_name, security_name)
    for security_port in security_ports:
        web.authorize('tcp', security_port, security_port, '0.0.0.0/0')
    # 创建instance
    instance_name = info[0]
    instance_type = info[1]
    instance_disksize = info[2]
    instance_imageid = info[4]
    #instance_keyname = info[5]
    instance_keyname = "zzlyzq"
    instance_count = int(info[6])
    instance_vpcid = "vpc-6755d002"
    instance_placements = [ info[3]+'b',info[3]+'c']
    #instance_placements = [ 'subnet-c2a33ea7', 'subnet-d242948b']
    if info[8] == "public":
        # 公有子网,每个可用区一个
        instance_subnetids = [ 'subnet-6e3baa09','subnet-55e3ed0d' ]
    elif info[8] == "private":
        # 私有子网,每个可用区一个
        instance_subnetids = [ 'subnet-6e3baa09', 'subnet-55e3ed0d']

    ## 准备磁盘
    dev_sda1 = boto.ec2.blockdevicemapping.EBSBlockDeviceType()
    dev_sda1.size = instance_disksize  # size in Gigabytes
    dev_sda1.volume_type = "gp2"
    bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping()
    bdm['/dev/sda1'] = dev_sda1
    # 绑定security到instance
    for count in range(instance_count):
        instance_placement = instance_placements[count%2]
        instance_subnetid = instance_subnetids[count%2]
        reservation = conn.run_instances(image_id=instance_imageid,key_name=instance_keyname,instance_type=instance_type,placement=instance_placement,subnet_id=instance_subnetid,security_groups=[security_name],block_device_map = bdm )
        # 添加tag为主机名
        instance = reservation.instances[0]
        status = instance.update()
        while status == 'pending':
            time.sleep(10)
            status = instance.update()
        if status == 'running':
            instance.add_tag("Name", instance_name)
        else:
            print('Instance status: ' + status)
            return None

def main():
    with open("./instances.csv") as f:
        for line in f:
            #print line
            info = []
            info = line.replace("\r","").replace("\n","").split(",")
            print info
            create_instance(info)
            #break


#main()
#create_security()

insteances.csv

service1,t2.micro,30,us-west-2,ami-0dde2e6d,limm,1,22_10060_10055,public
service2,t2.micro,30,us-west-2,ami-1712d877,limm,1,3389,public
service3,t2.medium,30,us-west-2,ami-0dde2e6d,limm,1,22_10060_10055,public
Copyright © opschina.org 2017 with zzlyzq@gmail.com all right reserved,powered by Gitbook该文件修订时间: 2017-07-11 11:32:48

results matching ""

    No results matching ""