How to Stop and Start Ec2 instance using Jenkins


In this tutorial you will learn how to Stop and Start AWS Ec2 instance from Jenkins

Steps:1Create an IAM User with Acess and Secret Key

Steps:2Create an IAM policy


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


Step: 3Assing IAM policy to IAM user

Steps: 4Configure IAM Access and Secret in Jenkins Server
Install package on Ubuntu Server
$ sudo apt-get install awscli
# sudo su – jenkins
$ aws configure

Steps: 5Create Jenkins Job to start and Stop Ec2 instance
Create a parameterized build to pass the Ec2 Instance id and Ec2 State name in Start or Stop



Step: 6 Create Write 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

Steps: 7 Now Start your Jenkins Build to Stop and Start Ec2 Instance 



0 Comments