Using Python to Automate Jenkins Install on AWS EC2 Instance

One of the main goals for a DevOps professional is automation. This week I was given a “simple” task, I was supposed to write a script that would login to AWS, create an instance, and install Jenkins.

Why would I want to do all that work when there are GUIs to assist with this process?

Automation is the key, when you may be faced with repetitive tasks automation just makes sense.

For the purpose of this tutorial is is assumed that you already have an AWS account, SecretKey, SecretAccessID, a security group policy already set up to accept incoming on port 8080, Python 2.7, and Boto3 installed.

import os

import boto3

First we need to make our calls. Creating an instance requires the os module and Boto modules, I decided to utilize boto3.

# note, later I made these system environment calls so they
# aren't accidentally published in a public repository.
os.environ["AWS_DEFAULT_REGION"] = "us-west-2"

This sets the access key, secret key and default region. You can change the region to wherever you need.

userdata = """#!/bin/bash
yum update -y
wget -O /etc/yum.repos.d/jenkins.repo
rpm --import
yum install jenkins -y
service jenkins start
chkconfig jenkins on


Now we pass our #!bash script through userdata. We start by updating yum. The next two lines are adding the Jenkins repository. Next we install Jenkins. Finally we start Jenkins as a service.
Important note: any commands sent that will require user input need to include the input. Ex: yum requires -y

ec2 = boto3.resource('ec2')
instances = ec2.create_instances(

Now we need to define our instance to be created. You may use a different AMI, KeyName, SecurityGroup.

for instance in instances:
 print("Waiting until running...")
 print((, instance.state, instance.public_dns_name,

Now we put everything together and return information about our instance.

Put everything together and test it out. Don’t forget to SSH into the instance and get the Jenkins default password.

The next task given to me is to set up an ELK Stack… Stay tuned.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s