Try this ....
import time
import boto3
ec2 = boto3.client('ec2')
response = ec2.describe_instances()
instance_dict = {}
count = 1
print(' {0:3} {1:30s} {2:15s} {3:15s} {4:15s} {5:10s}'.format("S No. ", "NAME", "INSTANCE ID", "IP ADDRESS",'AvailabilityZone', "STATE"))
print('----------------------------------------------------------------------------------------------------------------- \n')
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
if instance['State']['Name'] == "running":
if instance.__contains__("Tags"):
print(' {0:3} {1:30s} {2:15s} {3:15s} {4:15s} {5:10s}'.format(
count, instance["Tags"][0]["Value"], instance["InstanceId"],
instance["PublicIpAddress"], instance['Placement']['AvailabilityZone'], "RUNNING"))
instance_dict[count] = instance["InstanceId"],instance['Placement']['AvailabilityZone']
count += 1
else:
print(' {0:3} {1:30s} {2:15s} {3:15s} {4:15s} {5:10s}'.format(
count, "No Name", instance["InstanceId"], instance["PublicIpAddress"],instance['Placement']['AvailabilityZone'], "RUNNING"))
instance_dict[count] = instance["InstanceId"],instance['Placement']['AvailabilityZone']
count += 1
elif instance['State']['Name'] == "stopped":
if instance.__contains__("Tags"):
print(' {0:3} {1:30s} {2:15s} {3:15s} {4:15s} {5:10s}'.format(
count, instance["Tags"][0]["Value"], instance["InstanceId"], "No IP ADDRESS", instance['Placement']['AvailabilityZone'],
"STOPPED"))
instance_dict[count] = instance["InstanceId"],instance['Placement']['AvailabilityZone']
count += 1
else:
print(' {0:3} {1:30s} {2:15s} {3:15s} {4:15s} {5:10s}'.format(
count, "No Name", instance["InstanceId"], "No IP ADDRESS", instance['Placement']['AvailabilityZone'], "STOPPED"))
instance_dict[count] = instance["InstanceId"],instance['Placement']['AvailabilityZone']
count += 1
print()
iId = int(input('On which instance you want to add Volume : '))
az = instance_dict[iId][1]
size = input("Enter Size of Volume (default: 10): ")
response= ec2.create_volume(
AvailabilityZone=az,
Encrypted=False,
#Iops=100,
#KmsKeyId='string',
Size=int(size),
#SnapshotId='string',
VolumeType='gp2', #standard'|'io1'|'gp2'|'sc1'|'st1',
DryRun=False)
print("Volume ID : ", response['VolumeId'])
time.sleep(10)
response= ec2.attach_volume(Device="/dev/sdc", InstanceId=instance_dict[iId][0], VolumeId=response['VolumeId'])
print("State : ",response['State'])