Setting up Jenkins on an AWS EC2 instance using a user data script
- February 23, 2024
What is an AWS EC2 instance?
Amazon Elastic Compute Cloud (EC2) is a cloud-based web service providing secure and scalable computing resources. Users can rent virtual servers, adjust capacity as needed, configure security and networking, and manage storage. EC2 enables flexible scaling to meet changing demands, minimizing the need for precise traffic forecasts.
What is a user data script?
The user data script is the easiest and most commonly used method for providing instructions to an instance upon launch. When launching an instance in Amazon EC2, you can include user data to automate configuration tasks and execute scripts after the instance starts.
Step 1:
Log in to AWS, navigate to the Services menu and search for EC2. After selecting EC2, click on Launch Instance to proceed.
Step 2:
Enter the name of your server, such as “Jenkins server,” and select the Amazon Machine Image (AMI) that contains the operating system, application server and applications. I’m using the “ubuntu” AMI.
Step 3:
Select an Instance type; I’m using t2.micro.
Step 4:
Now, choose a key pair or create a new one.
Step 5:
For network settings, you can either leave them as they are or choose the VPC and subnets according to your preference.
Step 6:
Modify the security group settings to permit HTTP traffic from the internet on port 8080, as Jenkins typically operates on this port. Additionally, enable SSH traffic on port 22 from any source. Choose the desired storage capacity for your system, with 8 GB being within the free tier limits.
Step 7:
Expand the advanced details section, scroll to the end and apply the following user data script for installing Jenkins during the instance launch. Review the instance details and click Launch to initiate the instance.
#!/bin/bash
sudo apt update -y
sudo apt install openjdk-11-jdk -y
curl -fsSL https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo \ tee /usr/share/keyrings/jenkins-keyring.asc > /dev/null
echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] \ https://pkg.jenkins.io/debian-stable binary/ | sudo tee \ /etc/apt/sources.list.d/jenkins.list > /dev/null
sudo apt-get update
sudo apt-get install jenkins -y
The process may take a few minutes. Once the instance is successfully launched, you’ll be able to see it.
Step 8:
Copy the Public IPv4 address and then go to your preferred browser and search with “Public IPv4 address:8080.”
Step 9:
Connect to your instance from the terminal and switch to the root user using the sudo su command.
Run the cat /var/lib/jenkins/secrets/initialAdminPassword command in your terminal to retrieve the initial administrator password from the EC2 instance’s file system and unlock Jenkins.
Finally, start using Jenkins.
Happy Learning!
— By Ayush Maggo