Saturday, 27 February 2016

// // Leave a Comment

Script To Install And Setup AWS CLI

Script To Install And Setup AWS CLI

or

How to setup AWS CLI
or

Easy way to Install AWS CLI

AWS CLI is the command line interface utility to access and control AWS services via command line. AWS has a very good documentation on how to get started with AWS CLI, but here in this post let's use a simple bash script to install and setup and also make some aliases to control AWS services like start/stop instances.

Create a file aws_setup.sh

touch aws_setup.sh

Now give executable permission to the file

sudo chmod +x aws_setup.sh

Now copy and paste the following content in the file.

#!/bin/bash

echo "Installing aws-cli..."
curl "https://s3.amazonaws.com/aws-cli/awscli-bundle.zip" -o "awscli-bundle.zip"
unzip awscli-bundle.zip
sudo ./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws
sudo rm awscli-bundle.zip

# Configure AWS-CLI
echo "Configuring aws-cli..."
if [ ! -d ~/.aws ]
then
    mkdir -p ~/.aws
fi

# Set credentials for AWS
echo "[default]
aws_access_key_id=XXXXXXXXXXXX
aws_secret_access_key=XXXXXXXXXXXXXXXX
region=ap-southeast-1" > ~/.aws/credentials

 

# export AWS credential variables in .bash_profile file
echo "export AWS_ACCESS_KEY_ID='XXXXXXXXXXXX'">>~/.bash_profile
echo "export AWS_SECRET_ACCESS_KEY='XXXXXXXXXXXXXXXX'">>~/.bash_profile

# Make aliases for useful commands
echo "Making aliases for useful commands..."
echo "alias e='exit'">>~/.bash_profile
echo "alias start-myserver='aws ec2 start-instances --instance-ids i-xxxxxxx --region ap-southeast-1'">>~/.bash_profile
echo "alias stop-myserver='aws ec2 stop-instances --instance-ids i-xxxxxx --region ap-southeast-1'">>~/.bash_profile

source ~/.bash_profile
echo "Installation Done..."

# Instructions
echo "***********How to use AWS-CLI***********"
echo "To start myserver: start-myserver"
echo "To stop myserver: stop-myserver"

Here, you need to put the values of aws_access_key_id and aws_secret_access_key. We are setting up these variable in credentials file as in case if the bash shell variables are not available than the credential can be read from this file. You also need to put the instance id of myserver. We are creating aliases like start-myserver in .bash_profile so that we don't need to run the long command to start-stop the instance.

We have only included two command, you can create more aliases to ease your work.
To run the script, run the following command


./aws_setup.sh

We are done installing and setting up the AWS CLI. You can now run the aliases command and check if the instances are starting/stopping.
You can also use Ansible to start/stop the instance. Here is a post on how to do it.

0 comments:

Post a Comment