How to Stop and Start Ec2 instance using Jenkins

Jenkins is an open-source Continuous Integration tool. However, it’s not limited to Continuous Integration alone. Jenkins is supported by a large number of plugins that enhance its capability. The Jenkins tool is written in Java and so are its plugins. The tool has a minimalistic GUI that can be improved using specific plugins if required.

In this post, you will learn how to Stop and Start the AWS Ec2 instance from Jenkins.

Creating IAM user and Policy

1. Create an IAM User with Access and Secret Key.

2. Create an IAM policy:

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"ec2:StartInstances",
"ec2:StopInstances"
],
"Resource": "*"
}
]
}

3. Assing IAM policy to IAM user.

Configure IAM access and secrete in Jenkins server

1. Configure IAM Access and Secret in Jenkins Server.

2. Install package on Ubuntu Server:

$ sudo apt-get install awscli
# sudo su – jenkins
$ aws configure

Create Jenkins Job

At a higher level, a typical Jenkins job contains a unique name, a description, parameters, build steps, and post-build actions.

1. Create Jenkins Job to start and Stop Ec2 instance.

2. Create a parameterized build to pass the EC2 Instance ID and EC2 State name in Start or Stop.

3. Create a Shell script in Build Step.

Write Shell script in Shell Excute

if [ "$State" = "Start" ]
then
  aws ec2 start-instances --instance-ids $InstanceID
  echo Instance $InstanceID Started
elif [ "$State" = "Stop" ]
then
  aws ec2 stop-instances --instance-ids $InstanceID
  echo Instance $InstanceID Stopped
fi

Start Jenkins Build

A Jenkins build (not to be confused with a software build) can be anything from a simple Windows batch command to a complex Perl script.

Now Start your Jenkins Build to Stop and Start Ec2 Instance.

Related Post