Wednesday, May 27, 2020

start and stop ec2 instances using python

First of all install aws cli and python bot3 library:


  939  pip3 install awscli boto3

Create a User and get AWS access ID and Secret Key:

1. Launch the Identity Access Management Console(IAM) in AWS

2. Click users on the navigation menu on the left of the screen

3. Click on ADD USER in the popup window

4. In the new window, provide a user name and chosse the 'Programmatic Access' access type, and click next

5. To set the permissions, choose 'Attach Existing Policies Directly' and in the Policy Filter type 'AmazonEC2FullAccess', you can choose any permission level, but in this example I'll click on the checkbox next to 'AmazonEC2FullAccess' and then click the 'next' button. 

6. Finally, review the user and permission levels, and click on the 'Create User' button. 

The next page will show your keys  i.e  access key id and secret access key. download the csv files and save it

configure AWS configure Locally:
 Now we can configure out python scripting environment:

aws configure

AWS access key ID[]: acess key id
AWS Secret Acess Key[]: secret
Default region name[]:  us-east
Default output format[]: json

Verify the configuration
  942  cat ~/.aws/config
  943  cat ~/.aws/credentials

Now since configuration is done, let's check if these credentials work well with AWS CLI tools :

  944  aws ec2 describe-instances


The output will be a json file describing instances


--- The next step would be to generate a key pair for ec2 instance:


import boto3
import os
from os import path

def create_keypair():
  if (path.exists("ec2-key.pem")):
    print("The private key is already present")
  else:
    ec2 = boto3.resource('ec2')

    #create a file to store the key locally    outfile = open('ec2-key.pem', 'w')
ls
    #use boto to create a key pair    key_pair = ec2.create_key_pair(KeyName='ec2-key')

    #store key on the file    KeyPair =  str(key_pair.key_material)
    print(KeyPair)
    outfile.write(KeyPair)
    os.chmod("ec2-key.pem", 400)

if __name__ == "__main__":
  create_keypair()



It doesn't create a key pair but also stores on your local as well..
Now give appropriate permission to it

chmod 400 ec2-key.pem