Hey JunDevOps, Have a look these scripts:
1. To create an ec2 instance using python, you need to have the programmatic access. Use the following script to create an ec2 instance:
reservations = conn.get_all_instances(instance_ids=[sys.argv[1]])
instances = [i for r in reservations for i in r.instances]
for i in instances:
#provide the key pair to create the instance
key_name = i.key_name
# Provide security group id the instance should have
security_group = i.groups[0].id
# provide the instance type
instance_type = i.instance_type
print "Now Spinning New Instance"
# provide the subnet id
subnet_name = i.subnet_id
# Finally create the instance
reserve = conn.run_instances(image_id=ami_id,key_name=key_name,instance_type=instance_type,security_group_ids=[security_group],subnet_id=subnet_name)
2. Script to create a security group with your specifications:
import boto3
from botocore.exceptions import ClientError
ec2 = boto3.client('ec2')
# Get all VPC's
response = ec2.describe_vpcs()
vpc_id = response.get('Vpcs', [{}])[0].get('VpcId', '')
# Get VPC Ids
try:
# Create a security group and store it in response
response = ec2.create_security_group(GroupName='SECURITY_GROUP_NAME',
Description='DESCRIPTION',
VpcId=vpc_id)
# get security id from response
security_group_id = response['GroupId']
print('Security Group Created %s in vpc %s.' % (security_group_id, vpc_id))
# configure your security rules
data = ec2.authorize_security_group_ingress(
GroupId=security_group_id,
IpPermissions=[
{'IpProtocol': 'tcp',
'FromPort': 80, #allows incoming traffic port 80
'ToPort': 80, #Allows port forwarding to port 80
'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, #Ip ranges to be functional
{'IpProtocol': 'tcp', #protocol to be used
'FromPort': 22, # Allow incoming traffic from port 22
'ToPort': 22, # Allow traffic to be reached at port 22
'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}
])
print('Ingress Successfully Set %s' % data) # Print the configuration
except ClientError as e:
print(e)
3. Create EBS Volume and attach it to the instance
#### Create a volume ####
# create_volume(size, zone, snapshot=None, volume_type=None, iops=None)
# Very straight forward way to create volume. First argument - size, 2nd - region, 3rd - type
vol = conn.create_volume(1, "us-west-1c", "magnetic")
print 'Volume Id: ', vol.id #Prints volume id once its created
# attach volume and print the volume details. You pass volume id, instance id to which you wish to attach #the volume and
result = conn.attach_volume (vol.id, instance.id, "/dev/sdf")
print 'Attach Volume Result: ', result
4. Connect via ssh
import boto3
import botocore
import paramiko
# Get the key pair, save it in key
key = paramiko.RSAKey.from_private_key_file(path/to/mykey.pem)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect/ssh to an instance
try:
# Here 'ubuntu' is user name and 'instance_ip' is public IP of EC2
client.connect(hostname=instance_ip, username="ubuntu", pkey=key)
# Execute a command(cmd) after connecting/ssh to an instance
stdin, stdout, stderr = client.exec_command(cmd)
print stdout.read()
# close the client connection once the job is done
client.close()
break
except Exception, e:
print e