Deploying Jenkins with infrastructure as code (IaC)

An architecture diagram showing a plan for deploying Jenkins to a cloud server
25 min read
Published

Introduction

Many guides start by showing how to build an application locally, but entirely omit guidance for deploying that application to a production environment – often because each organization has unique needs/preferences for a production deployment.

In contrast, this initial guide will create a “walking skeleton” of a production-like Jenkins deployment. In more words, this guide will describe not only how to run Jenkins on your local machine, but also how to configure all the tooling required to provision a cloud server, deploy Jenkins on that server, and make the instance available to the world wide web.

As a result, by the end of this guide, you’ll have a working deployment pipeline for anyone on your team to create, enhance, and maintain a Jenkins instance. Future guides will showcase how to add more feature “muscle” to this “walking skeleton”.

Pre-Requisites

  • make: A tool for putting common CLI commands in a file.
  • docker: A tool for encapsulating software dependencies in a reproducible format.
  • A new SSH public/private key pair (e.g. via ssh-keygen)
  • A git repository, hosted remotely, with SSH access enabled.
  • An account/credentials for a cloud provider.

Run Jenkins Locally

Let’s start by seeing what Jenkins looks like locally. While there are many ways to install Jenkins, the simplest/fastest one is to run one of the official Jenkins images published on DockerHub.1

Bash
1docker run --rm --name jenkins --publish 8080:8080 jenkins/jenkins:lts-jdk21
2
3# Jenkins is now running at `http://localhost:8080`

Opening http://localhost:8080 shows the Jenkins setup page.

Jenkins setup page

As described on the setup page, you can obtain the initial admin password from the server log or by reading a file in the Docker container (e.g. docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword).

Feel free to explore the Jenkins UI for a little bit, but don’t get too attached because nothing is persisted.

Clean everything up with docker stop jenkins.

Configuring Deployment Tooling

Roadmap diagram

A local Jenkins server is fun to play around with, but it’s much more useful when deployed somewhere others can access.

Package Deployment Tools into a Docker Image

Deploying a server to a cloud service requires many additional tools beyond those listed in the pre-requisites. Fortunately, those tools can be packaged into a Docker image so that you don’t have to figure out how to install them on your local machine.2

deploy/Dockerfile
Dockerfile
 1############################################################
 2##  Tools required to run a deployment
 3############################################################
 4FROM python:3.13-slim
 5
 6## Install `curl`
 7RUN apt update \
 8    && apt install -y --no-install-recommends curl ca-certificates \
 9    && rm -rf /var/lib/apt/lists/*
10
11## Install `ssh` client
12RUN apt update \
13    && apt install -y --no-install-recommends openssh-client \
14    && rm -rf /var/lib/apt/lists/*
15
16## Install `tofu` as `terraform`
17RUN curl -L --output /tmp/tofu.deb https://github.com/opentofu/opentofu/releases/download/v1.9.0/tofu_1.9.0_amd64.deb \
18    && apt install /tmp/tofu.deb \
19    && mv $(which tofu) /usr/bin/terraform
20
21## Install `terraform-backend-git`
22RUN curl -L --output /tmp/terraform-backend-git https://github.com/plumber-cd/terraform-backend-git/releases/download/v0.1.6/terraform-backend-git-linux-amd64 \ 
23    && chmod +x /tmp/terraform-backend-git \
24    && mv /tmp/terraform-backend-git /usr/bin/terraform-backend-git
25
26## Install `ansible`
27RUN apt update \
28    && apt install -y python3-pip \
29    && rm -rf /var/lib/apt/lists/*
30RUN pip install --upgrade pip \
31    && pip install ansible==11.2.0 \
32    && pip cache purge
33# Install common `ansible` dependencies`
34#  - `rsync` (required by ansible.posix.synchronize)
35RUN apt update \
36    && apt install -y rsync \
37    && rm -rf /var/lib/apt/lists/*
38
39## Create a lower-privilege user for runtime
40RUN useradd -m ubuntu
41USER ubuntu
42WORKDIR /home/ubuntu
43
44CMD [ "tail", "-f", "/dev/null" ]

The Toolbox

curl - Make HTTP requests from the command line.

openssh-client - Secure connections to other computers/servers.

OpenTofu - Enables “Infrastructure as Code”, i.e. provisioning cloud infrastructure from version-controllable config files.

terraform-backend-git - Enables storing the sensitive Terraform “state files” (explained later on) in a Git repository.

Ansible - Enables configuring applications on other computers (e.g. cloud servers provisioned via Terraform).

Build and Run the Deployment Tools Image

Create a Makefile with the following contents.

Makefile
make
1.PHONY: *
2
3build-deploy-image:
4	cd deploy && docker build --tag deploy .
5
6info: build-deploy-image
7	docker run --rm --name deploy deploy ansible --version
8	docker run --rm --name deploy deploy terraform --version
9	docker run --rm --name deploy deploy terraform-backend-git --help

Now run make info to build the Docker image and see each key tool’s version information printed to the console.

Example output of `make info`
 1$ make info
 2
 3docker run --rm --name deploy deploy ansible --version
 4
 5ansible [core 2.18.4]
 6  config file = None
 7  configured module search path = ['/home/ubuntu/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
 8  ansible python module location = /usr/local/lib/python3.13/site-packages/ansible
 9  ansible collection location = /home/ubuntu/.ansible/collections:/usr/share/ansible/collections
10  executable location = /usr/local/bin/ansible
11  python version = 3.13.2 (main, Apr  8 2025, 01:41:36) [GCC 12.2.0] (/usr/local/bin/python3.13)
12  jinja version = 3.1.6
13  libyaml = True
14
15docker run --rm --name deploy deploy terraform --version
16
17OpenTofu v1.9.0
18on linux_amd64
19
20docker run --rm --name deploy deploy terraform-backend-git --help
21
22Terraform HTTP backend implementation that uses Git as storage
23
24Usage:
25  terraform-backend-git [flags]
26  terraform-backend-git [command]
27
28Available Commands:
29  completion  Generate the autocompletion script for the specified shell
30  docs        Generate docs
31  git         Start backend in Git storage mode and execute the wrapper
32  help        Help about any command
33  stop        Stop the currently running backend
34  version     Print version
35
36Flags:
37  -l, --access-logs      Log HTTP requests to the console
38  -a, --address string   Specify the listen address (default "127.0.0.1:6061")
39  -c, --config string    config file (default is terraform-backend-git.hcl)
40  -h, --help             help for terraform-backend-git
41
42Use "terraform-backend-git [command] --help" for more information about a command.

Provisioning a Blank Cloud Server

Roadmap diagram

With deployment tools installed, let’s provision a blank cloud server!

Store Terraform State in a Git Repository

First, we need a place to store the Terraform State files, which record a snapshot of the infrastructure managed by Terraform and are a critical part of Terraform’s operation.

State files should be stored in a shared location so that any team member can run deployments. They also need to be guarded by appropriate tools to “lock” the state so that only one deployment can happen at a time. Finally, they need to be stored securely, since they can contain plaintext credentials.

While you can pay for a commercial service to store your Terraform state (e.g. Hashicorp’s own offering), this guide will use the private GitHub repository you created in the pre-requisites.3

To do this, create a script that invokes terraform-backend-git to point to your private GitHub repository. (You may also have to chmod +x the file to make it executable)

deploy/terraform.sh
Bash
 1#!/usr/bin/env bash
 2cd "$(dirname "$0")"
 3
 4TERRAFORM_BACKEND_GIT="terraform-backend-git"
 5REPOSITORY="[email protected]:YOUR_USERNAME/tofu-states.git"
 6SERVICE_NAME="jenkins"
 7ARGS=${@: 1}
 8
 9with_git_backend() {
10    # source: https://github.com/plumber-cd/terraform-backend-git#wrapper-mode
11    $TERRAFORM_BACKEND_GIT git \
12        --repository "$REPOSITORY" \
13        --ref main \
14        --state "$SERVICE_NAME/tofu.tfstate" \
15        "$@"
16}
17
18COMMAND="with_git_backend terraform $ARGS"
19echo "Running: $COMMAND"
20$COMMAND

Make sure to change the value of the REPOSITORY variable to the SSH endpoint for your private GitHub repository.

Also, save the private key portion of your GitHub SSH key to creds/github_key

creds/github_key
text
1-----BEGIN OPENSSH PRIVATE KEY-----
2... redacted ...
3-----END OPENSSH PRIVATE KEY-----

Additionally, to improve security, create a file containing the SSH fingerprints of GitHub’s servers to defeat man-in-the-middle attacks.

deploy/ssh_known_hosts
text
1# GitHub.com
2# https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/githubs-ssh-key-fingerprints
3github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl
4github.com ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEmKSENjQEezOmxkZMy7opKgwFB9nkt5YRrYMjNuG5N87uRgg6CLrbo5wAdT/y6v0mKV0U2w0WZ2YB/++Tpockg=
5github.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCj7ndNxQowgcQnjshcLrqPEiiphnt+VTTvDP6mHBL9j1aNUkY4Ue1gvwnGLVlOhGeYrnZaMgRK6+PKCUXaDbC7qtbW8gIkhL7aGCsOr/C56SJMy/BCZfxd1nWzAOxSDPgVsmerOBYfNqltV9/hWCqBywINIR+5dIg6JTJ72pcEpEjcYgXkE2YEFXV1JHnsKgbLWNlhScqb2UmyRkQyytRLtL+38TGxkxCflmO+5Z8CSSNY7GidjMIZ7Q4zMjA2n1nGrlTDkzwDCsw+wqFPGQA179cnfGWOWRVruj16z6XyvxvjJwbz0wQZ75XK5tKSb7FNyeIEs4TT4jk+S4dhPeAUC5y+bDYirYgM4GC7uEnztnZyaVWQ7B381AK4Qdrwt51ZqExKbQpTUNn+EjqoTwvqNj4kqx5QUCI0ThS/YkOxJCXmPUWZbhjpCg56i+2aB6CmK2JGhn57K5mj0MNdBXA4/WnwH6XoPWJzK5Nyu2zB3nAZp+S5hpQs+p1vN1/wsjk=

And add that file to the deployment docker image.

deploy/Dockerfile
diff
1 WORKDIR /home/ubuntu
2
3+## Add SSH known_hosts
4+RUN mkdir -p /home/ubuntu/.ssh
5+COPY ./ssh_known_hosts /home/ubuntu/.ssh/known_hosts
6
7 CMD [ "tail", "-f", "/dev/null" ]

Next, update the Makefile to reference this new script, the GitHub SSH key, and the SSH fingerprints when running the deployment image.45

Makefile
sh
 1# ... earlier portion of the Makefile
 2
 3define deployer
 4docker run --rm --name deploy -it \
 5	--volume ./deploy/creds/github_key:/home/ubuntu/.ssh/id_rsa \
 6	--volume ./deploy/:/home/ubuntu/deploy \
 7	deploy
 8endef
 9
10jenkins: build-deploy-image
11	$(deployer) ./deploy/terraform.sh init
12	$(deployer) ./deploy/terraform.sh apply
13
14jenkins-destroy: build-deploy-image
15	$(deployer) ./deploy/terraform.sh destroy

Create the Cloud Server via Terraform

Now that we have a secure location to store the Terraform state, we can begin writing the code to provision our infrastructure.6

Create the file deploy/terraform.providers.tf and add the dependency on your cloud provider – here AWS – and any required global configuration for that provider.

deploy/terraform.providers.tf
HCL
 1terraform {
 2  required_providers {
 3    aws = {
 4      source  = "hashicorp/aws"
 5      version = "~> 5.0"
 6    }
 7  }
 8}
 9
10provider "aws" {
11  region = "us-west-2"
12}

For AWS, we need to look up the VPC (“Virtual Private Cloud”) where our server should be deployed. For this guide, we’ll use the default VPC that Amazon auto-creates in every new account. Create a new file to store these data lookups.

deploy/terraform.data.tf
HCL
1# Data (lookup from live infrastructure)
2data "aws_vpc" "default" {
3  default = true
4}

We also need an AMI (“Amazon Machine Image”) id to use as the base VM (“virtual machine”) for our new server. We’ll lookup the latest available Ubuntu 24.04 LTS.

deploy/terraform.data.tf
HCL
 1data "aws_ami" "ubuntu" {
 2  # This block is adapted from the docs:
 3  # https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance.html
 4  most_recent = true
 5  owners      = ["amazon"]
 6  # owners = ["099720109477"] # Canonical - not free tier eligible
 7
 8  filter {
 9    name   = "name"
10    ## How to find the AMI name? Ask the AWS CLI...
11    # docker run --rm -it -v ~/.aws:/path/to/.aws --entrypoint bash amazon/aws-cli
12    # aws ec2 describe-images --region us-west-2 --filters "Name=name, Values=*ubuntu-*-24.04-amd64-server-*" | grep \"Name
13    values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-*-24.04-amd64-server-*"]
14  }
15
16  filter {
17    name   = "virtualization-type"
18    values = ["hvm"]
19  }
20}

Now let’s create another file, deploy/terraform.server.tf for our server provisioning code. Add the configuration block to create a new EC2 server instance. Here we’ll use a t3.micro sized server with 8 GB of storage to stay within AWS’s free tier. We’ll also enable the user_data_replace_on_change option to make it easier to recreate the server instance later on in the guide.

deploy/terraform.server.tf
HCL
 1resource "aws_instance" "server" {
 2  ami             = data.aws_ami.ubuntu.id
 3  instance_type   = "t3.micro"
 4  root_block_device {
 5    volume_size = 8 # GiB
 6    volume_type = "gp3"
 7  }
 8  tags = {
 9    Name = "jenkins"
10  }
11  user_data_replace_on_change = true
12  lifecycle {
13    create_before_destroy = true
14  }
15}

We also need to ensure our deployment tools image has access to the AWS credentials created in the Pre-requisites.

Create the file creds/aws with the credentials

creds/aws
text
1[default]
2aws_access_key_id = YOUR_ACCESS_KEY_ID
3aws_secret_access_key = YOUR_SECRET_ACCESS_KEY

And mount that file into the deployment tools container.

Makefile
diff
1 define deployer
2 docker run --rm --name deploy -it \
3+	--volume ./deploy/creds/aws:/home/ubuntu/.aws/credentials \
4 	--volume ./deploy/creds/github_key:/home/ubuntu/.ssh/id_rsa \
5 	--volume ./deploy/:/home/ubuntu/deploy \
6 	deploy
7 endef

Now you can run make jenkins, and after a few minutes your AWS console will show a new EC2 server!

Server diagram

Enable HTTP and TLS Connections to the Cloud Server

Roadmap diagram The newly created EC2 server is currently unable to execute any workloads – it only has a stock OS and, by default all network traffic in and out of the server is blocked. Let’s connect to the internet!

Start by creating a new security group to hold the firewall rules.

deploy/terraform.server.firewall.tf
HCL
1resource "aws_security_group" "jenkins" {
2  name        = "jenkins"
3  description = "Firewall rules for the Jenkins server"
4  vpc_id      = data.aws_vpc.default.id
5  tags        = { Terraform = true }
6}

Start by allowing standard network traffic – ports 80 and 443 – through the firewall. We’ll use a locals block to concisely define the ports to avoid excessive repetition of the larger ingress and egress rule blocks.

deploy/terraform.server.firewall.tf
HCL
 1locals {
 2  allowed_inbound = [
 3    { port = 80, description = "HTTP" },
 4    { port = 443, description = "TLS" },
 5  ]
 6  allowed_outbound = [
 7    { port = 80, description = "HTTP" },
 8    { port = 443, description = "TLS" },
 9  ]
10}
11
12resource "aws_vpc_security_group_ingress_rule" "allow_ipv4" {
13  count             = length(local.allowed_inbound)
14  description       = local.allowed_inbound[count.index].description
15  security_group_id = aws_security_group.jenkins.id
16  cidr_ipv4         = "0.0.0.0/0"
17  ip_protocol       = "tcp"
18  from_port         = local.allowed_inbound[count.index].port
19  to_port           = local.allowed_inbound[count.index].port
20}
21
22resource "aws_vpc_security_group_ingress_rule" "allow_ipv6" {
23  count             = length(local.allowed_inbound)
24  description       = local.allowed_inbound[count.index].description
25  security_group_id = aws_security_group.jenkins.id
26  cidr_ipv6         = "::/0"
27  ip_protocol       = "tcp"
28  from_port         = local.allowed_inbound[count.index].port
29  to_port           = local.allowed_inbound[count.index].port
30}
31
32resource "aws_vpc_security_group_egress_rule" "allow_ipv4" {
33  count             = length(local.allowed_outbound)
34  description       = local.allowed_outbound[count.index].description
35  security_group_id = aws_security_group.jenkins.id
36  cidr_ipv4         =  "0.0.0.0/0"
37  ip_protocol       = "tcp"
38  from_port         = local.allowed_outbound[count.index].port
39  to_port           = local.allowed_outbound[count.index].port
40}
41
42resource "aws_vpc_security_group_egress_rule" "allow_ipv6" {
43  count             = length(local.allowed_outbound)
44  description       = local.allowed_outbound[count.index].description
45  security_group_id = aws_security_group.jenkins.id
46  cidr_ipv6         =  "::/0"
47  ip_protocol       = "tcp"
48  from_port         = local.allowed_outbound[count.index].port
49  to_port           = local.allowed_outbound[count.index].port
50}

Finally, link the security_group to the server so the firewall rules take effect.

deploy/terraform.server.tf
diff
 1 resource "aws_instance" "server" {
 2   ami             = data.aws_ami.ubuntu.id
 3   instance_type   = "t3.micro"
 4+  vpc_security_group_ids = [aws_security_group.jenkins.id]
 5   root_block_device {
 6     volume_size = 8 # GiB
 7     volume_type = "gp3"
 8   }
 9   tags = {
10     Name = "jenkins"
11   }
12   user_data_replace_on_change = true
13 }

After rerunning make jenkins you should see the firewall rules listed in the EC2 server’s Security tab.

Firewall rules

Enable SSH Connections to the Cloud Server

Roadmap diagram The server also needs to support SSH access so that, later on, Ansible can connect to and configure the server.

Add firewall rules to allow incoming SSH traffic.

deploy/terraform.server.firewall.tf
HCL
 1resource "aws_vpc_security_group_ingress_rule" "allow_ssh_ipv4" {
 2  description       = "SSH"
 3  security_group_id = aws_security_group.jenkins.id
 4  cidr_ipv4         = "0.0.0.0/0"  # WARNING: Wide open SSH
 5  ip_protocol       = "tcp"
 6  from_port         = 22
 7  to_port           = 22
 8}
 9
10resource "aws_vpc_security_group_ingress_rule" "allow_ssh_ipv6" {
11  description       = "SSH"
12  security_group_id = aws_security_group.jenkins.id
13  cidr_ipv6         = "::/0"   # WARNING: Wide open SSH
14  ip_protocol       = "tcp"
15  from_port         = 22
16  to_port           = 22
17}

Allowing inbound traffic on port 22 from 0.0.0.0/0 means anyone in the world can attempt to SSH into your server. While that setting is useful in a public guide like this one, you should restrict that down much further, e.g. your.ip.addr.ess/32, for a polished production deployment.

Place the new SSH key pair from the pre-requisites into the creds folder.

deploy/creds/cloud_server_key.pub
text
1ssh-rsa ... redacted ... user@hostname
deploy/creds/cloud_server_key
text
1-----BEGIN OPENSSH PRIVATE KEY-----
2... redacted ...
3-----END OPENSSH PRIVATE KEY-----

Add a local_file block to access the public key’s contents within Terraform.

deploy/terraform.data.tf
HCL
1data "local_file" "ssh-public-key" {
2  filename = "./creds/cloud_server_key.pub"
3}

Add a server boot script that will install the public key as an authorized SSH key. For AWS EC2 servers, that is accomplished by adding a user_data script.

deploy/terraform.server.tf
diff
 1 resource "aws_instance" "server" {
 2   ami             = data.aws_ami.ubuntu.id
 3   instance_type   = "t3.micro"
 4   vpc_security_group_ids = [aws_security_group.jenkins.id]
 5   root_block_device {
 6     volume_size = 8 # GiB
 7     volume_type = "gp3"
 8   }
 9   tags = {
10     Name = "jenkins"
11   }
12   user_data_replace_on_change = true
13+  user_data                   = <<-SERVER_INIT_SCRIPT
14+    #!/bin/bash
15+    echo "${data.local_file.ssh-public-key.content}" > /home/ubuntu/.ssh/authorized_keys
16+  SERVER_INIT_SCRIPT
17   lifecycle {
18     create_before_destroy = true
19   }
20 }

Finally, let’s require Terraform to validate that the server is accessible over SSH.

Add a terraform_data block with a provisioner to execute a simple echo command on the cloud server via SSH.

deploy/terraform.server.tf
HCL
 1resource "terraform_data" "server-configuration" {
 2  input = {
 3    "id" = aws_instance.server.id
 4    "public_ip" = aws_instance.server.public_ip
 5  }
 6  triggers_replace = [
 7    aws_instance.server.id,
 8    timestamp(),  # Trigger provisioner re-runs on every Terraform `apply`
 9  ]
10  lifecycle {
11    create_before_destroy = true
12  }
13  provisioner "remote-exec" {  # Ensure SSH is ready
14    connection {
15      host = aws_instance.server.public_ip
16      user = "ubuntu"
17      private_key = file("./creds/cloud_server_key")
18    }
19    inline = ["echo 'Instance is now reachable via SSH!'"]
20  }
21}

Now, when you run make jenkins, Terraform will both create the cloud server and ensure that it is accessible via SSH!

Output of `make jenkins`
Bash
 1$ make jenkins
 2... (truncated Terraform output)
 3
 4terraform_data.server-configuration: Provisioning with 'remote-exec'...
 5terraform_data.server-configuration (remote-exec): Connecting to remote host via SSH...
 6terraform_data.server-configuration (remote-exec):   Host: xxx.xxx.xxx.xxx
 7terraform_data.server-configuration (remote-exec):   User: ubuntu
 8terraform_data.server-configuration (remote-exec):   Password: false
 9terraform_data.server-configuration (remote-exec):   Private key: true
10terraform_data.server-configuration (remote-exec):   Certificate: false
11terraform_data.server-configuration (remote-exec):   SSH Agent: false
12terraform_data.server-configuration (remote-exec):   Checking Host Key: false
13terraform_data.server-configuration (remote-exec):   Target Platform: unix
14terraform_data.server-configuration (remote-exec): Connected!
15terraform_data.server-configuration (remote-exec): Instance is now reachable via SSH!

Deploying Jenkins to the Cloud Server

Now that the cloud server has shiny SSH access, let’s setup Ansible to configure the server.

Hello Ansible

Roadmap diagram Create an Ansible playbook that pings the remote server to test Ansible’s connectivity.

deploy/ansible.playbook.yaml
YAML
1- name: Test Ansible Connection
2  hosts: all
3  tasks:
4    - name: Ping the cloud server
5      ansible.builtin.ping:

Add a second provisioner to the terraform_data block that invokes Ansible to run the playbook against the cloud server.7

deploy/terraform.server.tf
diff
 1 resource "terraform_data" "server-configuration" {
 2   input = {
 3     "id" = aws_instance.server.id
 4     "public_ip" = aws_instance.server.public_ip
 5   }
 6   triggers_replace = [
 7     aws_instance.server.id,
 8     timestamp(),  # Trigger provisioner re-runs on every Terraform `apply`
 9   ]
10   lifecycle {
11     create_before_destroy = true
12   }
13   provisioner "remote-exec" {  # Ensure SSH is ready before running Ansible
14     connection {
15       host = aws_instance.server.public_ip
16       user = "ubuntu"
17       private_key = file("./creds/cloud_server_key")
18     }
19     inline = ["echo 'Instance is now reachable via SSH!'"]
20   }
21+  provisioner "local-exec" {  # Run Ansible to configure the server
22+    environment = {
23+      "SSH_PRIVATE_KEY_PATH" = "./creds/cloud_server_key"
24+    }
25+    # NOTE: Prefer `--ssh-extra-args` over `ANSIBLE_HOST_KEY_CHECKING`
26+    # - Requires Ansible to validate known hosts (e.g. GitHub).
27+    # - Allows Ansible to connect to newly provisioned servers.
28+    # NOTE: Pass `--inventory` as a comma-separated list instead of a
29+    # file since only one server is targeted.
30+    command = <<-SERVER_CONFIG_SCRIPT
31+      echo "Running Ansible from directory $(pwd)"
32+      ansible-playbook \
33+        --verbose \
34+        --user=ubuntu \
35+        --private-key=$SSH_PRIVATE_KEY_PATH \
36+        --ssh-extra-args='-o StrictHostKeyChecking=accept-new' \
37+        --become \
38+        --inventory='${aws_instance.server.public_ip},' \
39+        ansible.playbook.yaml
40+    SERVER_CONFIG_SCRIPT
41+  }
42 }

Now re-running make jenkins should show Ansible connecting to and pinging the cloud server.

Output of `make jenkins`
Bash
1$ make jenkins
2... (truncated output)
3
4terraform_data.server-configuration (local-exec): TASK [Ping the cloud server] ***************************************************
5terraform_data.server-configuration (local-exec): ok: [xxx.xxx.xxx.xxx] => {"changed": false, "ping": "pong"}
6
7terraform_data.server-configuration (local-exec): PLAY RECAP *********************************************************************
8
9... (truncated output)

Configuring the Cloud Server as a Jenkins instance

Roadmap diagram Now, we can configure Ansible to install Jenkins!

Use Ansible to Install Docker on the Cloud Server

First, we need Ansible to install Docker on the cloud server. We’ll use some third-party Ansible modules to handle this task.

Create an Ansible requirements file to list the third-party dependencies.

deploy/ansible.requirements.yaml
YAML
1roles:
2  - src: geerlingguy.pip
3    version: 3.1.0
4  - src: geerlingguy.docker
5    version: 7.4.5

Update the Terraform provisioner to install the Ansible requirements before running the playbook.

deploy/terraform.server.tf
diff
 1 resource "terraform_data" "server-configuration" {
 2   ...
 3   provisioner "local-exec" {  # Run Ansible to configure the server
 4     environment = {
 5       "SSH_PRIVATE_KEY_PATH" = "./creds/cloud_server_key"
 6     }
 7     # NOTE: Prefer `--ssh-extra-args` over `ANSIBLE_HOST_KEY_CHECKING`
 8     # - Requires Ansible to validate known hosts (e.g. GitHub).
 9     # - Allows Ansible to connect to newly provisioned servers.
10     # NOTE: Pass `--inventory` as a comma-separated list instead of a
11     # file since only one server is targeted.
12     command = <<-SERVER_CONFIG_SCRIPT
13+	  echo "Installing Ansible Requirements"
14+     ansible-galaxy install --role-file ansible.requirements.yaml
15       echo "Running Ansible from directory $(pwd)"
16       ansible-playbook \
17         --verbose \
18         --user=ubuntu \
19         --private-key=$SSH_PRIVATE_KEY_PATH \
20         --ssh-extra-args='-o StrictHostKeyChecking=accept-new' \
21         --become \
22         --inventory='${aws_instance.server.public_ip},' \
23         ansible.playbook.yaml
24     SERVER_CONFIG_SCRIPT
25   }
26 }

Update the playbook to install pip then docker.

deploy/ansible.playbook.yaml
YAML
 1- name: Install pip
 2  hosts: all
 3  tasks:
 4    - name: Ensure `pip` is installed
 5      ansible.builtin.apt:
 6        name: python3-pip
 7        state: present
 8        update_cache: true
 9
10- name: Install Docker
11  hosts: all
12  vars:
13    pip_install_packages:
14      - name: docker
15        version: 7.1.0
16  roles:
17    - role: geerlingguy.pip
18    - role: geerlingguy.docker

Run a Jenkins Container on the Cloud Server

Add a playbook step to boot a Jenkins docker container

deploy/ansible.playbook.yaml
YAML
 1- name: Start Jenkins
 2  hosts: all
 3  tasks:
 4    - name: Start Jenkins Container
 5      community.docker.docker_container:
 6        name: "jenkins"
 7        image: jenkins/jenkins:lts-jdk21
 8        ports:
 9          - "80:8080"
10        state: started
11        recreate: true
12        restart_policy: unless-stopped

Now, re-run make jenkins, and once everything completes, visit your cloud server’s IP address in your browser to see a running Jenkins instance!

The working Jenkins deployment

You can obtain the password by using SSH to read the deployed Docker container’s logs

Bash
1ssh -i deploy/creds/cloud_server_key [email protected] \
2	sudo docker logs jenkins

OR by reading the initialAdminPassword file from the deployed Docker container.

Bash
1ssh -i deploy/creds/cloud_server_key [email protected] \
2	sudo docker exec jenkins \
3		cat /var/jenkins_home/secrets/initialAdminPassword

But, again, don’t get too attached to this server as it will be automatically replaced whenever a newer OS image is available (e.g. with security updates). To prepare Jenkins for initial production loads, we have to persist the Jenkins state (i.e. jenkins_home) outside of the cloud server.

Persisting the jenkins_home Directory

The jenkins_home directory contains all the key Jenkins state: users, sessions, job configurations, job build histories, plugins, etc. We want to store that state outside of the cloud server so we can update/replace the cloud server as needed (e.g. to fix security vulnerabilities)

Create a Network File Share

Roadmap diagram We’ll start by configuring a network file share (e.g. a hard drive you connect to over the internet). For AWS, use the Elastic File Share (EFS) service.

deploy/terraform.nfs.tf
HCL
1resource "aws_efs_file_system" "jenkins-efs" {
2  tags = {
3    Name      = "jenkins-efs"
4    Terraform = true
5  }
6  encrypted = true
7}

For AWS, we don’t need to specify an exact storage amount – the “elastic” branding reflects how the storage expands automatically as needed. The free tier allows up to 5GB.

Allow Traffic to the Network File Share from the Cloud Server

Roadmap diagram The NFS share also needs firewall rules to allow incoming traffic.

Create a new security group for the NFS that allows incoming traffic on port 2049 (the only port AWS EFS listens on).

deploy/terraform.nfs.firewall.tf
HCL
 1resource "aws_security_group" "nfs" {
 2  name        = "nfs"
 3  description = "Allow incoming NFS traffic (e.g. for Amazon EFS)"
 4  vpc_id      = data.aws_vpc.default.id
 5  tags        = { Terraform = true }
 6}
 7
 8resource "aws_vpc_security_group_ingress_rule" "allow_nfs_from_jenkins" {
 9  security_group_id = aws_security_group.nfs.id
10  referenced_security_group_id = aws_security_group.jenkins.id
11  ip_protocol       = "tcp"
12  from_port         = 2049
13  to_port           = 2049
14}

Notice that the ingress_rule only allows traffic from servers with the jenkins security group – that protects against unwanted access and preserves connectivity even when the Jenkins cloud server’s IP changes (e.g. upon server replacement or the addition of more servers).

The NFS also needs a network mount target, i.e. a network interface that other servers can contact to connect to the file share.

In AWS, we need to first look up all the subnets on our default VPC.

deploy/terraform.data.tf
diff
 1 data "aws_vpc" "default" {
 2   default = true
 3 }
 4
 5+data "aws_subnets" "default" {
 6+  filter {
 7+    name   = "vpc-id"
 8+    values = [data.aws_vpc.default.id]
 9+  }
10+  filter {
11+    name   = "default-for-az"
12+    values = ["true"]
13+  }
14+}

Then create a mount target within each subnet.8

deploy/terraform.nfs.tf
diff
 1 resource "aws_efs_file_system" "jenkins-efs" {
 2   tags = {
 3     Name      = "jenkins-efs"
 4     Terraform = true
 5   }
 6   encrypted = true
 7 }
 8
 9+resource "aws_efs_mount_target" "jenkins-efs" {
10+  count          = length(data.aws_subnets.default.ids)
11+  file_system_id = aws_efs_file_system.jenkins-efs.id
12+  subnet_id      = data.aws_subnets.default.ids[count.index]
13+  security_groups = [
14+    aws_security_group.nfs.id,
15+  ]
16+}

Mount the Network File Share to the Cloud Server

Roadmap diagram Now that the NFS allows incoming connections, let’s configure the cloud server to connect to the file share.

Start by allowing outbound traffic to the NFS.

deploy/terraform.server.firewall.tf
diff
 1 # ...
 2
 3 locals {
 4   allowed_inbound = [
 5     { port = 80, description = "HTTP" },
 6     { port = 443, description = "TLS" },
 7   ]
 8   allowed_outbound = [
 9     { port = 80, description = "HTTP" },
10     { port = 443, description = "TLS" },
11+    { port = 2049, description = "NFS" },
12   ]
13 }
14
15 # ...

Pass the NFS’s DNS name to Ansible as an environment variable.

deploy/terraform.server.tf
diff
1  provisioner "local-exec" {  # Run Ansible to configure the server
2    environment = {
3      "SSH_PRIVATE_KEY_PATH" = "./creds/cloud_server_key"
4+      "JENKINS_NFS_MOUNT_DNS_NAME" = aws_efs_file_system.jenkins-efs.dns_name
5    }
6    # ...
7  }

Also, update the terraform_data block that runs Ansible to have an explicit dependency on the NFS mount targets. Otherwise, Terraform may try to run Ansible to connect to the NFS before the mount targets have been provisioned, which would result in a failed mount.

deploy/terraform.server.tf
diff
1 resource "terraform_data" "server-configuration" {
2   input = {
3     "id" = aws_instance.server.id
4     "public_ip" = aws_instance.server.public_ip
5+    "nfs_mounts" = aws_efs_mount_target.jenkins-efs.*.id
6   }
7   # ...

Then instruct Ansible to mount the NFS to the cloud server.

deploy/ansible.playbook.yaml
YAML
 1- name: Install Docker
 2  # ...
 3
 4- name: Mount Network File System
 5  hosts: all
 6  tasks:
 7    - name: Ensure `mount` is installed
 8      ansible.builtin.apt:
 9        name: nfs-common
10        state: present
11    - name: Create NFS mount point
12      ansible.builtin.file:
13        path: /mnt/nfs
14        state: directory
15        owner: ubuntu
16        group: ubuntu
17        mode: '0755'
18    - name: Mount NFS
19      ansible.posix.mount:
20        src: "{{ lookup('ansible.builtin.env', 'JENKINS_NFS_MOUNT_DNS_NAME') }}:/"
21        path: /mnt/nfs
22        fstype: nfs4
23        opts: "nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2"
24        state: mounted
25
26- name: Start Jenkins
27  # ...

Persist jenkins_home inside the Network File Share

Roadmap diagram Now that the cloud server has access to the NFS storage, let’s persist the jenkins_home directory inside it.

Create a jenkins_home directory within the NFS.

deploy/ansible.playbook.yaml
YAML
 1- name: Mount Network File System
 2  hosts: all
 3  tasks:
 4    # ... all other tasks
 5    - name: Create `jenkins_home` directory
 6      ansible.builtin.file:
 7        path: /mnt/nfs/jenkins_home
 8        state: directory
 9        owner: ubuntu
10        group: ubuntu
11        mode: '0755'

Finally, mount the NFS’s jenkins_home into the Jenkins container

deploy/ansible.playbook.yaml
diff
 1    - name: Start Jenkins Container
 2      community.docker.docker_container:
 3        name: "jenkins"
 4        image: jenkins/jenkins:lts-jdk21
 5        ports:
 6          - "80:8080"
 7+       volumes:
 8+         - /mnt/nfs/jenkins_home:/var/jenkins_home
 9        state: started
10        recreate: true
11        restart_policy: unless-stopped

Now, with one last make jenkins, you’ll have a working Jenkins server backed by a reliable deployment pipeline.

Conclusion/Next Steps

At this point, you can log into the Jenkins server and begin setting it up through the UI to install plugins, configure jobs, credentials, etc. It’s also possible to manage all this configuration through code (to be continued in a future guide).

You’ll also want to configure HTTPS before using this Jenkins server for production workloads. Use your preferred service to obtain a (sub)domain and enable HTTPS. I like buying domains through Cloudflare and using Let’s Encrypt to obtain a free HTTPS certificate. If you want to stay within the AWS ecosystem, you can buy a domain in Route 53 and configure HTTPS with the help of the AWS Certificate Manager (ACM).

I hope you found this guide helpful and informative. Please reach out to share something you learned or to ask a question if anything was unclear.

If you were following this guide just to explore cloud development and/or Jenkins deployment, consider running make jenkins-destroy to permanently delete all Jenkins data and infrastructure (e.g. to keep the cloud organized and avoid unnecessary costs).

Footnotes


  1. The Bash command runs the latest stable Jenkins image – indicated by lts which stands for Long Term Support. The Jenkins server runs inside the Docker container on port 8080 which is then published to port 8080 on your machine (i.e. external-port:internal-port). The --rm flag tells Docker to clean everything up automatically after stopping the container.

    See the docs for docker run to learn more. ↩︎

  2. Of course, you could install all these tools locally, but choosing to use a Docker image also means that team members and CI environments can run deployments using the exact same environment. ↩︎

  3. Using a private git repository for your Terraform state gives you more ownership over the sensitive state files. Additionally, it allows you to run deployments at any time, whereas a commercial provider might have an outage.

    But, a private git repository also needs to be protected by appropriate access controls. Feel free to make a different choice for your state management than recommended by this guide. ↩︎

  4. These updates include mounting in the entire deploy folder containing the terraform.sh script. Later in the guide we’ll add more deployment scripts to the deploy folder so they will be included in this volume automatically.

    The github_key is mounted to the default SSH private key location so that terraform-backend-git can find it automatically.

    Additionally, the Makefile defines a new jenkins target that, after completing this guide, will deploy the Jenkins server. It also adds a jenkins-destroy target which will remove all Jenkins-related cloud infrastructure (e.g. to clean up/save costs if you’re following this guide as an experiment/tutorial). ↩︎

  5. You could place the github_key somewhere else, on your machine and/or within the container. If you make such a change, add a Docker environment variable called SSH_PRIVATE_KEY containing the absolute path to the GitHub SSH private key within the container. ↩︎

  6. This portion of the guide will focus on provisioning an EC2 server instance on AWS. If you want to deploy to a different cloud provider you can search the OpenTofu Registry or the Terraform Registry for modules/documentation that support your preferred cloud provider. ↩︎

  7. Provisioners are run sequentially, so the remote-exec will ensure the cloud server is accessible via SSH before the local-exec’s callout to Ansible attempts the connection.

    The environment subblock defines environment variables that are available to the command. In this case, we are referencing the private counterpart of the SSH key added to the cloud server.

    ansible-playbook instructs Ansible to run the specified playbook, here ansible.playbook.yaml. We provide an in-line inventory with the IP address of our new cloud server, which Ansible connects to over SSH as --user=ubuntu authenticated with the given --private-key. We configure SSH to accept-new servers since ours is brand new, and thus we don’t know its SSH fingerprint. ↩︎

  8. The count key tells Terraform to create multiple records and acts like an iterator allowing us to index each of the subnet_ids. ↩︎