コード例 #1
0
def get_worker_instance(availabilityZone, subnetId):
    response = client.run_instances(
        ImageId=IMAGE_ID,
        InstanceType=INSTANCE_TYPE,
        KeyName=KEY_NAME,
        MaxCount=MAX_COUNT,
        MinCount=MIN_COUNT,
        Placement={
            'AvailabilityZone': availabilityZone
        },
        SubnetId=subnetId
    )

    worker_id = response['Instances'][0]['InstanceId']
    worker_instance = ec2.Instance(worker_id)

    filters = [{
        'Name': 'instance-id',
        'Values': [worker_id]
    }]

    logging.info("Waiting for worker instance %s to start....", worker_id)
    worker_instance.wait_until_running(Filters=filters)

    return worker_instance
コード例 #2
0
ファイル: main-ver2.py プロジェクト: depaajith/Module3Python
def createNATinstance():
    global natname
    global NATid
    natname = Environmentname[0:3] + "mod3" + "NAT"
    waiter = client.get_waiter('instance_exists')

    instance = ec2.Instance('id')
    NATinstance = ec2.create_instances(
        DryRun=False,
        ImageId='ami-184dc970',  # ami-184dc970
        MinCount=1,
        MaxCount=1,
        KeyName='jeenanatk',
        SecurityGroupIds=[
            secgrpidlist[0],
        ],
        InstanceType='t2.micro',
        SubnetId=subnetidlist[0])

    NATid = NATinstance[0].id
    print "NAt id", NATid

    waiter.wait(InstanceIds=[NATid])
    # print "NAT id after wait", NATid

    ec2.create_tags(Resources=[NATid],
                    Tags=[{
                        'Key': 'Name',
                        'Value': natname
                    }])
    return
コード例 #3
0
ファイル: main-ver2.py プロジェクト: depaajith/Module3Python
def createbastionhost():
    waiter = client.get_waiter('instance_exists')
    global Bastionid
    instance = ec2.Instance('id')
    Bastionhost = ec2.create_instances(
        DryRun=False,
        ImageId='ami-8fcee4e5',  # ami-8fcee4e5
        MinCount=1,
        MaxCount=1,
        KeyName='jeenanatk',
        SecurityGroupIds=[
            secgrpidlist[0],
        ],
        InstanceType='t2.micro',
        SubnetId=subnetidlist[0])

    Bastionid = Bastionhost[0].id

    waiter.wait(InstanceIds=[Bastionid])
    # print "NAT id after wait", NATid

    ec2.create_tags(Resources=[Bastionid],
                    Tags=[{
                        'Key': 'Name',
                        'Value': 'Mod3Bastion'
                    }])
    return
コード例 #4
0
def main(cmd_args):
    logging.info("Getting a list of block devices for instance: %s", cmd_args.instance)

    instance_root_volume = get_instance_root_volume(cmd_args.instance)
    logging.info("Root volume ID: %s", instance_root_volume)

    instance = ec2.Instance(cmd_args.instance)

    filters = [{
        'Name': 'instance-id',
        'Values': [instance.id]
    }]

    logging.info("Stopping instance ID: %s", cmd_args.instance)
    instance.stop()
    instance.wait_until_stopped(Filters=filters)
    logging.info("Instance stoped")

    logging.info("Detaching volume ID: %s", instance_root_volume)
    instance.detach_volume(VolumeId=instance_root_volume)

    logging.info("Launching a new worker instance.....")
    az = instance.placement.values()[2]
    subnet = instance.subnet_id
    worker_instance = get_worker_instance(az, subnet)

    logging.info("Attaching volume to worker instance")
    worker_instance.attach_volume(
        Device='/dev/xvdz',
        VolumeId=instance_root_volume
    )

    logging.info("Replacing SSH key in the volume")
    subprocess.call(["./script.sh", "-k", cmd_args.bastion_key, "-i", cmd_args.bastion_ip, "-u", cmd_args.bastion_user, "-K", cmd_args.instance_key, "-I", worker_instance.private_ip_address, "-U", cmd_args.instance_user])

    logging.info("Terminating worker instance")
    client.terminate_instances(InstanceIds=[worker_instance.id])

    filters = [{
        'Name': 'instance-id',
        'Values': [worker_instance.id]
    }]

    worker_instance.wait_until_terminated(Filters=filters)
    logging.info("Worker instance terminated")

    logging.info("Attaching volume %s back to original instance %s", instance_root_volume, instance.id)
    instance.attach_volume(Device=instance.root_device_name, InstanceId=instance.id, VolumeId=instance_root_volume)

    filters = [{
        'Name': 'instance-id',
        'Values': [instance.id]
    }]

    logging.info("Starting back original instance %s", instance.id)
    instance.start()
    instance.wait_until_running(Filters=filters)
    logging.info("Instance started")
コード例 #5
0
def terminate(RI_NAME, S_NEW_NAME=None):
    client = boto3.client('ec2')
    instance_vol = []
    RI_ID = None
    instance = [
        i for i in ec2.instances.filter(Filters=[{
            'Name': 'tag:Name',
            'Values': [RI_NAME]
        }, {
            'Name': 'instance-state-name',
            'Values': ['running']
        }])
    ]
    for i in instance:
        RI_ID = i.id
        print(RI_ID)
    if RI_ID != None:
        print('\nWe are terminating...', RI_NAME)
    else:
        print("\nSeems you are trying to remove instance with don't exist")
        sys.exit(1)

    try:
        instance = ec2.Instance(RI_ID)
        for device in instance.block_device_mappings:
            if (device.get('DeviceName')) == '/dev/xvdh':
                volume = device.get('Ebs')
                instance_vol.append(volume.get('VolumeId'))

        response = client.terminate_instances(InstanceIds=[
            RI_ID,
        ],
                                              DryRun=False)
        wait_time(RI_NAME)
        if (S_NEW_NAME == None):
            for vm in instance_vol:
                volume = ec2.Volume(vm)
                response = volume.delete()
            print("\nInstance terminated and volume deleted")
        else:
            for vm in instance_vol:
                try:
                    snapshot = ec2.create_snapshot(
                        VolumeId=vm, Description="Snapshot from instance")
                    snapshot = ec2.Snapshot(snapshot.id)
                    tag = snapshot.create_tags(Tags=[
                        {
                            'Key': 'Name',
                            'Value': S_NEW_NAME
                        },
                    ])
                    print(
                        "\nPlease save this snapshot name.Use it in next instance creation: ",
                        S_NEW_NAME)
                except:
                    raise
    except:
        sys.exit(1)
コード例 #6
0
ファイル: replaceKey.py プロジェクト: williamhargrove/python
def get_instance_root_volume(instance_id):
    instance = ec2.Instance(instance_id)
    blocks = list(instance.block_device_mappings)

    for block in blocks:
        if block['DeviceName'] == instance.root_device_name:
            volume = block['Ebs']['VolumeId']

    return volume
コード例 #7
0
def rm():
    for i in ec2.instances.all():
        for tag in i.tags:
            if RI_NAME in tag['Value']:
                RI_ID = i.instance_id
            else:
                print(
                    "Seems you are trying to remove instance with dont exist")
                sys.exit(1)

            try:
                instance = ec2.Instance(RI_ID)
                for device in instance.block_device_mappings:
                    if (device.get('DeviceName')) == '/dev/xvdh':
                        volume = device.get('Ebs')
                        instance_vol.append(volume.get('VolumeId'))

                response = client.terminate_instances(InstanceIds=[
                    RI_ID,
                ],
                                                      DryRun=False)
                if (R_VOL == "Y"):
                    S_NEW_NAME = (input(
                        "\nEnter volume snap name you want to give:")).strip()
                    for vm in instance_vol:
                        try:
                            snapshot = ec2.create_snapshot(
                                VolumeId=vm,
                                Description="Snapshot from instance")
                            snapshot = ec2.Snapshot(snapshot.id)
                            tag = snapshot.create_tags(Tags=[
                                {
                                    'Key': 'Name',
                                    'Value': S_NEW_NAME
                                },
                            ])
                            print(
                                "Please save this snapshot name.Use it in next instance creation: ",
                                S_NEW_NAME)
                        except:
                            raise
                elif (R_VOL == "N"):
                    print("Termination is in process...")
                    for vm in instance_vol:
                        volume = ec2.Volume(vm)
                        response = volume.detach_from_instance(
                            Device='/dev/xvdh', Force=True, InstanceId=RI_ID)
                        time.sleep(120)
                        response = volume.delete()
                    print("\nInstance terminated and volume deleted")
                else:
                    print(
                        "You haven't choosed what to do with volume correctly")

            except:
                sys.exit(1)