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_ACCESS_KEY_ID"] os.environ["AWS_SECRET_ACCESS_KEY"] 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 http://pkg.jenkins-ci.org/redhat-stable/jenkins.repo rpm --import http://pkg.jenkins-ci.org/redhat-stable/jenkins-ci.org.key 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( ImageId='ami-7172b611', InstanceType='t2.micro', KeyName='AWS_Testing', MinCount=1, MaxCount=1, SecurityGroupIds=['Jenkins'], UserData=userdata )
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...") instance.wait_until_running() instance.reload() print((instance.id, instance.state, instance.public_dns_name, instance.public_ip_address))
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.