A simple example of using Terraform
to provision Jenkins
(CI/CD) using its official Docker
image in a Docker
container on an AWS
EC2
instance.
Going beyond this example, it would be important to structure the Terraform
files and think carefully about where secrets were stored.
- Ensure you have a valid
AWS
account, including anaccess_key
andsecret_key
for a user with permissions to create the necessary resources.
If you don't have anAWS
account you can sign up to the Free Tier here: https://aws.amazon.com/free/
Export youraccess_key
andsecret_key
:
export AWS_ACCESS_KEY_ID="access_key"
export AWS_SECRET_ACCESS_KEY="<secret_key>"
-
Download
Terraform
if you don't already have it installed:
https://www.terraform.io/intro/getting-started/install.html -
Populate
terraform.tfvars
with relevant values, usingterraform.tfvars.example
as an example. -
Create a
key pair
for use on theAWS
EC2
instances and put thepublic
/private
keys in.private/aws-key.pem.pub
/.private/aws-key.pem
. -
Use
Terraform
to check how the services will be provisioned:
terraform plan
- Provision using
Terraform
:
terraform apply
- Check the output of the provision and access the server via SSH and/or your web browser.
## Provision output...
...
Apply complete! Resources: 11 added, 0 changed, 0 destroyed.
Outputs:
aws_instance-ci-public_dns = <hostname>.compute-1.amazonaws.com
aws_platform-name = okappy-global-us-east-1
...
## Access server via SSH and Docker
ssh -i .private/aws-key.pem ubuntu@<hostname>.compute.amazonaws.com
sudo docker ps
sudo docker exec -it <container-id> bash
## Access server via HTTP
lynx http://<hostname>.compute.amazonaws.com:8080/
-
Complete Jenkins setup by finding the
/var/jenkins_home/secrets/initialAdminPassword
file via SSH and entering the contents in the HTTP interface (the HTTP interface should prompt you to do this). Then follow the instructions provided, installing standard plugins and creating the first admin account. -
Try out Jenkins, by adding a
Multibranch Pipeline
job such as: https://github.com/zhibek/behat-example.git
This job type relies on theJenkinsfile
inside thegit
repo, therefore no additional config is required in theJenkins
UI. -
If there is a need to re-stage the server at any point,
taint
and re-apply
viaTerraform
:
terraform taint aws_instance.ci
terraform apply