Beispiel #1
0
def StartInstance(Instance, Profile, Region):
    try:
        print(" INFO : Starting Instance ", Instance)
        ec2client = dv.SetEC2Client(Profile, Region)
        ec2client.start_instances(InstanceIds=[Instance])
        waiter = ec2client.get_waiter('system_status_ok')
        waiter.wait(InstanceIds=[Instance])
        print(" INFO : Instance " + Instance, " is Ready")
    except Exception as ERR:
        print(" ERROR : Failed to start instance ", Instance)
        print(" ", ERR)
Beispiel #2
0
def StopInstance(Instance, Profile, Region):
    try:
        print(" INFO : Stoppign instance ", Instance)
        ec2client = dv.SetEC2Client(Profile, Region)
        ec2client.stop_instances(InstanceIds=[Instance])
        waiter = ec2client.get_waiter('instance_stopped')
        waiter.wait(InstanceIds=[Instance])
        print(" INFO : Instance ", Instance, " Stopped")
    except Exception as ERR:
        print(" ERROR : Failed to Stop instance ", Instance)
        print(" ", ERR)
        exit(1)
Beispiel #3
0
def listsnapshots(VolumeID, Region, Profile):
    # This gets list of snapshots are return to function for processing.
    try:
        ec2client = dv.SetEC2Client(Profile, Region)
        Result = ec2client.describe_snapshots(Filters=[
            {
                'Name': 'volume-id',
                'Values': [
                    VolumeID,
                ]
            },
        ], )
        return Result
    except exception as ERR:
        print(ERR)
        print(
            " ERROR : Failed to list Snapshot, please verify arguments like profile, host, disk etc"
        )
        exit(1)
Beispiel #4
0
def ListVolume(instance_id, Region, Profile):
    try:
        try:
            # Generate list of volumes attached to the instance
            ec2resource = dv.SetEC2Resource(Profile, Region)
            instance = ec2resource.Instance(instance_id)
        except Exception as ERR:
            print(
                " ERROR : Failed to find instance using Profile={}, Region={}. Please check Profile/Region/Hostname"
                .format(Profile, Region))
            print(" ", ERR)
            exit()
        # Initialise Volumes variable to store ist of Volumes
        Volumes = []
        # Get list of volumes attached to Instance.
        for device in instance.block_device_mappings:
            Ebs = device.get('Ebs')
            Volumes.append(Ebs.get('VolumeId'))

        # List of Volumes are available as list in Volumes.Volume
        # Set Client for describing volume
        ec2client = dv.SetEC2Client(Profile, Region)
        # Loop through Volumes and print information
        for X in Volumes:
            Y = ec2client.describe_volumes(VolumeIds=[X])
            # Loop through the Volume information provided by above commad.
            for Z in Y['Volumes']:
                # Device name is saved in a different list
                for D in Z['Attachments']:
                    Dev = D['Device']

                print(Z['VolumeId'], Z['Size'], "GB ", Dev, Z['VolumeType'])
    except Exception as ERR:
        print(
            " ERROR : Failed to get Volume information, please verify Profile, Region, Hostname etc are correct."
        )
        print(" ", ERR)
        exit(1)
Beispiel #5
0
def main():
    # ----- StartParsing the options if no arguments print help and exit.
    if args.Task is None:
        P.print_help()
        exit()

    global Profile
    Profile = args.profile
    global boto3
    global ams
    boto3 = dvclass.AWSBoto3()
    ams = dvclass.AMSCMDB()
    # ----- First section ensuring CMDB file and able to find Instance details.
    # Try to open CMDB file, if faild stop execution.
    try:
        FILE = open(LIST, "r")
        Lines = FILE.readlines()
        FILE.close()
    except Exception as ERR:
        print(ERR)
        print("ERROR : Failed to open File List ", LIST)
        exit(1)

    # Below command gets instance detals for the host from local file.
    # If Source instance not found stop execution
    try:
        result = dv.GetInstanceDetails(args.src_host, Lines)
        Region = result[0]
        instance_id = result[1]
    except Exception as ERR:
        print(ERR)
        print(" ERROR : Instance details not found in local file ", LIST)
        exit(1)

# ------ Task for list option.
    if args.Task == "list":
        try:
            print(" INFO : Using Profile : ", args.profile)
            Result = GetVolume(instance_id, Region, Profile, args.src_device,
                               args.src_host)
            # result returns Volume and Device Name
            VolumeID = Result[0]
            DeviceID = Result[1]
        except:
            print(" ERROR : Failed to volume information")
            exit(1)

        Snapshot = listsnapshots(VolumeID, Region, Profile)
        PrintSnaps(Snapshot)
        exit()
# ---- End of list Snaps

    elif args.Task == "listvol":
        # List volumes attached to Source Host specified.
        print(" INFO : Listing volumes for ", args.src_host, Region, "\n")
        Result = ListVolume(instance_id, Region, args.profile)
        # result returns Volume and Device Name
        # VolumeID = Result[0]
        # DeviceID = Result[1]
#----- End of list volumes

    elif args.Task == "clone":
        #-----Start of Clone. Source instance details already available
        try:
            # Get Destination host id and region.
            result = dv.GetInstanceDetails(args.dest_host, Lines)
            DestRegion = result[0]
            Destinstance_id = result[1]
            DestAZone = result[2]
        except Exception as ERR:
            print(ERR)
            print(" ERROR : ", args.dest_host, " Not found in CMDB")
            exit(1)

        # If snap_id not provided, use the default latest or prompt
        if args.snap_id is None:
            # Identify Disk information for Source Host
            Result = GetVolume(instance_id, Region, Profile, args.src_device,
                               args.src_host)
            # result returns Volume and Device Name
            VolumeID = Result[0]
            DeviceID = Result[1]
            # List Snapshots and select latest by default
            Snapshot = listsnapshots(VolumeID, Region, Profile)
            SNAP_ID = GetLatestSnap(Snapshot)
        else:
            SNAP_ID = args.snap_id

        try:
            # Identify Destination device to be detached, have DestInstance ID and region.
            Result = GetVolume(Destinstance_id, DestRegion, Profile,
                               args.dest_device, args.dest_host)
            # result returns Volume and Device Name
            DestVolumeID = Result[0]
            DestDeviceID = Result[1]
        except Exception as ERR:
            print(ERR)
            print(" ERROR : Failed to Destination instance volume information")
            exit(1)

        # Verify each variable have a value
        for VAR in [
                "VolumeID", "DeviceID", "DestVolumeID", "DestDeviceID",
                "SNAP_ID"
        ]:
            TestVar(VAR)
        # Promp t confirmation
        print("\n INFO : Following information found for processing")
        print("  Source      :", args.src_host, " Snapshot ID :", SNAP_ID)
        print("  Destination :", args.dest_host, " Dest Details :",
              DestVolumeID, DestDeviceID, DestAZone)

        # Create new volume with Dest Region and matching type
        Respose = input("\n Proceed ? y/n :")
        if Respose == "y":

            # Shutdown Dest Host, Detach diskand delete
            StopInstance(Destinstance_id, Profile, Region)
            print(" INFO :", args.dest_host, " Stopped, detaching volume")
            # Set Boto3 resource for handling device.
            ec2resource = dv.SetEC2Resource(Profile, Region)
            ec2client = dv.SetEC2Client(Profile, Region)
            # Detach the volume and delete disk
            volume = ec2resource.Volume(DestVolumeID)
            try:
                # Detach volume from the Instance and delete Volum.
                volume.detach_from_instance(InstanceId=Destinstance_id,
                                            Force=True)
                waiter = ec2client.get_waiter('volume_available')
                waiter.wait(VolumeIds=[DestVolumeID], )
                print(" INFO : Volume Detached")
                volume.delete()
                print(" INFO : Volume Deleted")
            except Exception as ERR:
                print(ERR)
                print(" ERROR : Failed to remove Volume from ", args.dest_host,
                      DestVolumeID)
                exit(1)

            # Create new volume from snapshot

            try:
                print(" INFO : Creating Volume from Snapshot", SNAP_ID,
                      DestAZone, args.voltype)
                # If Volume size provide as argument create new volume for specified size.
                if args.volsize is None:
                    NewVol = ec2resource.create_volume(
                        SnapshotId=SNAP_ID,
                        AvailabilityZone=DestAZone,
                        VolumeType=args.voltype)
                else:
                    print(" INFO : New Volume Size is {}GB".format(
                        args.volsize))
                    NewVol = ec2resource.create_volume(
                        SnapshotId=SNAP_ID,
                        AvailabilityZone=DestAZone,
                        VolumeType=args.voltype,
                        Size=int(args.volsize))

                waiter = ec2client.get_waiter('volume_available')
                waiter.wait(VolumeIds=[NewVol.id])
                print(" INFO : New Volume ", NewVol.id,
                      " Created from " + SNAP_ID, " and is Available")
            except Exception as ERR:
                print(ERR, " ERROR : Failed to create Volume from Snap")
                exit(1)

            # Attach new vol and start instance.
            try:
                print(" INFO : Attaching Volume to Instance :",
                      args.dest_device, Destinstance_id, NewVol.id)
                ec2client.attach_volume(InstanceId=Destinstance_id,
                                        VolumeId=NewVol.id,
                                        Device=args.dest_device)
                # ec2.Instance(Destinstance_id).attach_volume(VolumeId=NewVol, Device=args.dest_device)
            except Exception as ERR:
                print(ERR, " ERROR : Faild to attach Volume to instance")
                exit(1)
            # Start the Dest instance
            StartInstance(Destinstance_id, Profile, Region)

            exit(0)
        else:
            print(" ERROR : Aborting activity")
            exit(1)
#-----End of Clone

    elif args.Task == "copy":
        #-----
        try:
            # Get Destination host id and region.
            result = dv.GetInstanceDetails(args.dest_host, Lines)
            DestRegion = result[0]
            Destinstance_id = result[1]
            DestAZone = result[2]
        except Exception as ERR:
            print(ERR)
            print(" ERROR : ", args.dest_host, " Not found in CMDB")
            exit(1)

        # If snap_id not provided, use latest snapshot of device src_device
        if args.snap_id is None:
            # If Snapshot ID not provided, use src_device to get latest snapshot and use it.
            try:
                # Identify Disk information for Source Host. This can be used to find latest snapshot.
                Result = GetVolume(instance_id, Region, Profile,
                                   args.src_device, args.src_host)
                # result returns Volume and Device Name
                VolumeID = Result[0]
                DeviceID = Result[1]
            except Exception as ERR:
                print(ERR)
                print(" ERROR : Unable to get Snapshot for", args.src_host)
                exit(1)
                # List Snapshots and select latest by default
            Snapshot = listsnapshots(VolumeID, Region, Profile)
            SNAP_ID = GetLatestSnap(Snapshot)
        else:
            SNAP_ID = args.snap_id

        # At this stage must have ID of Snapshot to be used
        for VAR in ["SNAP_ID"]:
            TestVar(VAR)
        # Test to ensure that destination device does not exist.
        Check = CheckDeviceExist(Destinstance_id, Region, Profile,
                                 args.dest_device, args.dest_host)
        if Check == True:
            print("\n ERROR : ", args.dest_device, " exist on ",
                  args.dest_host, " Please remove disk and try  \n")
            exit(1)
        else:
            print(" INFO : Dest Device name ", args.dest_device,
                  "is available on ", args.dest_host)

        # Prompt confirmation
        print(" INFO : Following information found for processing")
        print(" Source      :", args.src_host, " Snapshot ID :", SNAP_ID)
        print(" Destination : ", args.dest_host, " Dest AZ :", DestAZone,
              " Dest Device:", args.dest_device)

        # Create new volume with Dest Region and matching type
        Respose = input("\n Proceed ? y/n :")
        if Respose == "y":

            # Create new volume from snapshot

            try:
                # Set Boto3 resource for handling device.
                ec2resource = dv.SetEC2Resource(Profile, Region)
                print(" INFO : Creating Volume from Snapshot ", SNAP_ID,
                      DestAZone, args.voltype)
                if args.volsize is None:
                    # Create volume same size as snapshot
                    NewVol = ec2resource.create_volume(
                        SnapshotId=SNAP_ID,
                        AvailabilityZone=DestAZone,
                        VolumeType=args.voltype)
                else:
                    # Create volume with specified size
                    print(" INFO : Creating new volume with size {}GB".format(
                        args.volsize))
                    NewVol = ec2resource.create_volume(
                        SnapshotId=SNAP_ID,
                        AvailabilityZone=DestAZone,
                        VolumeType=args.voltype,
                        Size=int(args.volsize))

                ec2client = dv.SetEC2Client(Profile, Region)
                waiter = ec2client.get_waiter('volume_available')
                waiter.wait(VolumeIds=[NewVol.id])
                print(" INFO : New Volume ", NewVol.id, "Created from ",
                      SNAP_ID, " and is Available")
            except:
                print(" ERROR : Failed to create Volume from Snap")
                # print NewVol, SNAP_ID, Destinstance_id
                exit(1)

            # Attach new vol and start instance.
            try:
                print(" INFO : Attaching Volume to Instance", args.dest_host,
                      Destinstance_id, args.dest_device, NewVol.id)
                ec2client.attach_volume(InstanceId=Destinstance_id,
                                        VolumeId=NewVol.id,
                                        Device=args.dest_device)
                print("\n SUCCESS : Disk attached to ", args.dest_host,
                      " Device:", args.dest_device, " \n")
            except Exception as ERR:
                print(ERR, "\n ERROR : Faild to attach Volume to instance",
                      args.dest_host)
                exit(1)

            exit(0)


#-----
    elif args.Task == "rmvol":
        # Tasks for removing and deleting unused volume
        # Ensure disk is unmounted and not in use by OS.
        Check = CheckDeviceExist(instance_id, Region, Profile, args.src_device,
                                 args.src_host)
        if Check == True:
            try:
                # Identify Disk information for Source Host. This can be used to find latest snapshot.
                Result = GetVolume(instance_id, Region, Profile,
                                   args.src_device, args.src_host)
                # result returns Volume and Device Name
                VolumeID = Result[0]
                DeviceID = Result[1]
            except Exception as ERR:
                print(ERR)
                print(" ERROR : Unable to get Volume ID for", args.src_host)
                exit(1)

            print("\n  ----------------------------------------------------")
            print("   Please ensure disk unmounted and VG removed on Host")
            print("  ----------------------------------------------------")
            print("\n WARN : Detach and delete volume ", args.src_device,
                  VolumeID, " from ", args.src_host, "?  \n")
            Respose = input("\n Proceed ? y/n :")

            if Respose == "y":
                # Set Boto3 resource for handling device.
                ec2resource = dv.SetEC2Resource(Profile, Region)
                ec2client = dv.SetEC2Client(Profile, Region)
                # Get Volume ID

                # Detach the volume and delete disk
                volume = ec2resource.Volume(VolumeID)
                try:
                    # Detach volume from the Instance and delete Volum.
                    volume.detach_from_instance(InstanceId=instance_id,
                                                Force=True)
                    waiter = ec2client.get_waiter('volume_available')
                    waiter.wait(VolumeIds=[VolumeID], )
                    print(" INFO : Volume Detached, deleting unused volume")
                    volume.delete()
                    print(" INFO : Volume Deleted")
                except Exception as ERR:
                    print(ERR)
                    print(" ERROR : Failed to remove Volume from ",
                          args.dest_host, DestVolumeID)
                    exit(1)

        else:
            print("\n ERROR : Dest Device name ", args.src_device,
                  " not found on ", args.src_host)

    elif args.Task == "snap":
        # Get  region info and pass to function.
        Result = ams.GetInstAWS(args.src_host)
        Region = Result[2]
        # Now ready to trigger Snapshot
        CreateSnapshot(Region, args.volume)

    else:
        print("\n Sorry I did not get the options.. :(")