AWS - Day 4 - AWS CLI Useful Scripts



John Rankin @ August 21, 2018

So I definetely don't want to go login through my web browser to get the state of my machine to view my Instances... or to even create an instance... so I've created some scripts ...

 

Here is a terminal script I've written in python for printing out all your instance states ...  but it does the job.  Even gave it some color coding :)

 

#!/usr/bin/python

import json,os,sys
import subprocess
from termcolor import colored
from tabulate import tabulate

output = json.loads(subprocess.check_output("aws ec2 describe-instances", shell=True))

my_list = []
for res in output['Reservations']:
    for item in res['Instances']:
        inst_id = item['InstanceId']
        state = colored(item['State']['Name'],'green') if (item['State']['Name'] == 'running') else colored(item['State']['Name'],'red')
        inst_type = item['InstanceType']
        region  = item['Placement']["AvailabilityZone"]
        try:
            ip_addr = item['PublicIpAddress']
            security_group = item['SecurityGroups'][0]['GroupName']
            dns  = item['PublicDnsName']
        except:
            ip_addr = ""
            dns = ""
            security_group = ""
        my_list.append([inst_id, state, inst_type, ip_addr, region, security_group ,dns])

print tabulate(my_list, headers=['InstanceID', 'State', 'InstType', 'IP Address' , 'Region', 'SecurityGroup', 'DNS' ])

 

Creating Instances via Command Line

Before we do this:  we need to create a Security Group.  If we do not create a security group, and just create an instance, PORT 22 will not be accessible by the node.

aws ec2 create-security-group --group-name EC2SecurityGroup --description "Security Group for EC2 instances to allow port 22"
aws ec2 authorize-security-group-ingress --group-name EC2SecurityGroup --protocol tcp --port 22 --cidr 0.0.0.0/0
aws ec2 describe-security-groups --group-names EC2SecurityGroup

Once that is done, we will use EC2SecurityGroup for the security group option on creation.

Create EC2 Instances Script
I've created a script where it takes in argument that represents how many EC2 instances that will spin up.   It is using the t2.micro instance type, and a standard image (ami-6cd6f714) , and the EC2 gets assigned to the security group we've created.

#!/bin/bash

count=$1

if [[ -z $count ]] ; then echo "No Count number specified..exiting"; exit ; fi
aws ec2 run-instances --image-id ami-6cd6f714 --instance-type t2.micro --key-name MyKeyPair --security-groups EC2SecurityGroup --count $count

 

 S3 Scripts:

List your buckets:

rek_buckets_list

#!/usr/bin/python

import json,os,sys
import subprocess
from termcolor import colored
from tabulate import tabulate

output = json.loads(subprocess.check_output("aws s3api list-buckets", shell=True))

my_list = []
for item in output['Buckets']:
    name = colored(item['Name'],'green')
   # state = colored(item['State']['Name'],'green') if (item['State']['Name'] == 'running') else colored(item['State']['Name'],'red')
    creation_date = item['CreationDate']
    my_list.append([name,creation_date ])

print tabulate(my_list, headers=['Name', 'CreationDate' ])



List the Contents of your Bucket.. It takes in a cli argument, of your bucket name.

rek_buckets_contents

#!/usr/bin/python

import json,os,sys
import subprocess
from termcolor import colored
from tabulate import tabulate


if len(sys.argv) != 2:
    sys.exit()

output = json.loads(subprocess.check_output("aws s3api list-objects --bucket=" + sys.argv[1], shell=True))

my_list = []
for item in output['Contents']:
    filename = colored(item['Key'],'green')
    size = item['Size']
    owner = colored(item['Owner']['DisplayName'],'yellow')
    storageClass = item['StorageClass']
    lastModified = item['LastModified']
    my_list.append([filename,size,owner,storageClass,lastModified ])

print tabulate(my_list, headers=['Filename','Size', 'Owner', 'StorageClass', 'LastModified' ])



 

 

 

 

 

 

 

 

Most Recent Posts


Bitwise XOR-exclusive OR

Read This
May 10, 2023

0-1 Knapsack

Read This
May 10, 2023

K-Way Merge

Read This
May 10, 2023

Subsets

Read This
May 10, 2023

Backtracking

Read This
May 10, 2023

Greedy Algorithm

Read This
May 10, 2023

Trie

Read This
May 10, 2023

Depth-First Search-DFS

Read This
May 10, 2023

Breadth-First Search-BFS

Read This
May 10, 2023

Binary Search Tree-BST

Read This
May 10, 2023

Top K Elements

Read This
May 10, 2023

Binary Search Pattern

Read This
May 10, 2023

Cyclic Sort pattern

Read This
May 10, 2023

Merge Intervals

Read This
May 10, 2023

Day 7 - DynamoDB - and Working with 2 Services - Lambda

Read This
August 25, 2018

Day 6 - Lambda - Creating an API

Read This
August 23, 2018

AWS - Day 5 - S3 - Simple Storage Service

Read This
August 22, 2018

AWS - Day 4 - AWS CLI Useful Scripts

Read This
August 21, 2018

AWS - Day 3 - Create Container from another container

Read This
August 20, 2018

Day 2 - Docker Intro

Read This
August 17, 2018

AWS - Day1 - Tutorial - Launching my first Docker Container

Read This
August 16, 2018

AWS - Day 1 - Signing up and testing out their tutorials

Read This
August 16, 2018

Dynamic Programming - Edit Distance

Read This
December 19, 2016

Dynamic Programming - Fibonacci

Read This
December 19, 2016