Use Terraform to deploy simple Jenkins on AWS

Use Terraform to deploy simple Jenkins on AWS

Continuous integration, continuous delivery, and continuous deployment. These concepts and terms can work together to automate the application lifecycle. In this regard, if you want to implement CI/CD, Jenkins may be the main tool for building a server to automate the process.

This article is a simple task of deploying Jenkins with AWS Amazon as IaaS. In order to fully understand, we will install Jenkins and its plugins, register users, set basic security rules, and finally insert a job as an example, so let us further elaborate on this idea.

prerequisites

  • EC2 instance in AWS Amazon to test this technical description.

  • Install terraform as an "infrastructure as code" tool.

Install Jenkins and its work

First, we need to watch this section, because this is the process where we can find out how to install Jenkins through the script bash, which is made as a general script and can be used on different CentOS Linux. This installation is divided into 5 parts, first we will install and start Jenkins, then we will register a default user and install basic plugins, and finally, register our best friend HelloWorld job, this will be a good example and a good start .

jenkins_user=$1
jenkins_password=$2
jenkins_address=http://localhost:8080

set -x

function installing()
{
    #Installing some necessary dependencies 
    sudo yum -y update
    sudo yum -y install wget java-1.8.0 nano 

    #Installing jenkins, instructions located in http://pkg.jenkins-ci.org/redhat/
    sudo wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins-ci.org/redhat/jenkins.repo
    sudo rpm --import https://pkg.jenkins.io/redhat/jenkins.io.key
    sudo yum install -y jenkins

    sleep 1
    echo "[INFO]  Jenkins was installed"
}

Please note that the plugins function in the bash script is necessary to install all the plug-ins recommended when logging in to Jenkins for the first time. This is part of customizing this tool and is necessary to register the default user. Loop to check if the Jenkins server is running, you can watch it at startup and plugin functions.

function plugins()
{
    #Installing jenkins plugins 
    java -jar jenkins-cli.jar -s "$jenkins_address" -auth $jenkins_user:$jenkins_password  install-plugin trilead-api
    java -jar jenkins-cli.jar -s "$jenkins_address" -auth $jenkins_user:$jenkins_password  install-plugin cloudbees-folder

    ... many more plugins ...

    java -jar jenkins-cli.jar -s "$jenkins_address" -auth $jenkins_user:$jenkins_password  install-plugin pam-auth 
    java -jar jenkins-cli.jar -s "$jenkins_address" -auth $jenkins_user:$jenkins_password  install-plugin ldap
    java -jar jenkins-cli.jar -s "$jenkins_address" -auth $jenkins_user:$jenkins_password  install-plugin email-ext 

    # Restart
    sudo systemctl restart jenkins &
    while (( 1 )); do
      echo "[INFO]   waiting for restart Jenkins on port [8080] ..."

      java -jar jenkins-cli.jar -s "$jenkins_address" -auth $jenkins_user:$jenkins_password  list-jobs
      if (( $? == 0 )); then
          break
      fi

      sleep 20
    done

    echo "[INFO]   Jenkins was restarted"
}

Do you remember the announcement to start the Jenkins server? If you don't want to see it again, you should implement the plug-in function.
Use Terraform to deploy simple Jenkins on AWS

The following is a simple task that introduces how to add a job in Jenkins through the Jenkins CLI, which is a Pipeline job with string parameters.

<?xml version='1.1' encoding='UTF-8'?>
<flow-definition plugin="[email protected]">
  <description></description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <hudson.model.ParametersDefinitionProperty>
      <parameterDefinitions>
        <hudson.model.StringParameterDefinition>
          <name>par_name</name>
          <description></description>
          <defaultValue>HelloWorld</defaultValue>
          <trim>false</trim>
        </hudson.model.StringParameterDefinition>
      </parameterDefinitions>
    </hudson.model.ParametersDefinitionProperty>
  </properties>
  <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="[email protected]">
    <script>pipeline {
    agent { label 'master' }
    stages {
        stage('build') {
            steps {
                echo "Hello World!"
            }
        }
    }
}</script>
    <sandbox>true</sandbox>
  </definition>
  <triggers/>
  <disabled>false</disabled>
</flow-definition>

Deploy Jenkins as a server

General variables are provided in this file. Please note that some attributes need to be replaced by AWS CLI variables that you configure. See more information in the AWS CLI Command Reference .

variable "region" {
  default  = "us-east-1"
  description = "AWS region"
}

variable "access_key" {
  default  = "HEREYOURACCESSKEY"
  description = "AWS credentials file path"
}

variable "secret_key" {
  default  = "HEREYOURSECRETKEY"
  description = "AWS credentials file path"
}

variable "jenkins_user_name" {
  description = "jenkins"
  default = "jenkins"
}

variable "jenkins_user_password" {
  description = "jenkins"
  default = "jenkins"
}

variable "jenkins_name" {
  description = "Jenkins name"
  default = "jenkins"
}

variable "jenkins_instance_type" {
  default = "t2.micro"
}

variable "jenkins_key_name" {
  default = "key-pair"
  description = "SSH key located in tyour AWS account."
}

variable "amis" {
  description = "ami to spawn."
  default = { 
    us-east-1 = "ami-0c94855ba95c71c99"
  }
}

There are several properties that need to be set:

access_key and secret_key : used as access keys to verify command requests.

jenkins_key_name : The name of the key pair file, which will help connect to our instance via ssh. If you need to create a key pair, please enter your AWS account through the processing procedure in the My Security Credentials section. Note that in this example, we used key-pair.pem located in the Template folder of the project, replacing this file and its name in the project with your credentials.

amis : This attribute can be a list and has an AMI instance ID that can be easily found in Amazon Machine Instances. If you want to change this AMI instance, please pay attention to whether the AMI is installed and systemctl is installed, because Amazon Linux does not support systemclt or services The command is based on its CentOS/RHEL-based version, so in order to avoid spending a lot of time searching for an AMI instance that has been configured with his systemctl, please try to use the AMI instance configured in this project.

resource "aws_instance" "jenkins" {
  instance_type = "${var.jenkins_instance_type}"
  security_groups = ["${aws_security_group.security_group_jenkins.name}"]
  ami = "${lookup(var.amis, var.region)}"
  key_name = "${var.jenkins_key_name}"

  # Add jenkins server startup
  provisioner "file" {
    connection {
      user = "ec2-user"
      host = "${aws_instance.jenkins.public_ip}"
      timeout = "1m"
      private_key = "${file("templates/${var.jenkins_key_name}.pem")}"
    }
    source = "templates/jenkins_startup.sh"
    destination = "/home/ec2-user/jenkins_startup.sh"
  }

  # Add jenkins job
  provisioner "file" {
    connection {
      user = "ec2-user"
      host = "${aws_instance.jenkins.public_ip}"
      timeout = "1m"
      private_key = "${file("templates/${var.jenkins_key_name}.pem")}"
    }
    source = "templates/jobmaster.xml"
    destination = "/home/ec2-user/jobmaster.xml"
  }

  provisioner "remote-exec" {
    connection {
      user = "ec2-user"
      host = "${aws_instance.jenkins.public_ip}"
      timeout = "1m"
      private_key = "${file("templates/${var.jenkins_key_name}.pem")}"
    }
    inline = [
      "chmod +x /home/ec2-user/jenkins*.sh",
      "/home/ec2-user/jenkins_startup.sh ${var.jenkins_user_name} ${var.jenkins_user_password}"
    ]
  }
}

Once all the properties are configured, please execute the command line terraform init to initialize the working folder, execute the terraform plan to monitor all deployment plans, once the check is completed, please execute the command line terraform to apply for the deployment infrastructure.

Enter Jenkins

It can be found in the AWS Management Console , click on the "Instance" section, and then a new instance should be created as follows.

Use Terraform to deploy simple Jenkins on AWS

Copy the public DNS, and type this value in the browser, and then type port 8080 (as shown in the image), remembering that all available ports are in the security group section of the main.tf file. The user and password are configured as attributes in the variables.tf file, so in this case, our user and password are "Jenkins".

Use Terraform to deploy simple Jenkins on AWS

in conclusion

Simple and practical, if you want to browse this code, please click in this repository. Perhaps, you have seen many installations about Jenkins, but I have used this bash and installation method in many installations. It makes these basic activities very easy: registering users, registering basic tasks and installing plugins. Hope this contribution is helpful to you.

Script library address: https://github.com/moballiachi/cicd-jenkins.git

Practical course: DevOps pipeline practice https://edu.51cto.com/sd/36f6e

Guess you like

Origin blog.51cto.com/11064706/2544016