Part 4: Jenkins Pipeline

Now for the grand finale, the Jenkins Pipeline.

For the jenkins piece, we will be running jenkins locally and pulling from Git. So push it all up there now.
git add .
git commit -m "Devops Project"
git push origin master
Fire up jenkins and log in.
 
Create a new job and select "Pipeline" (call it something intuitive)
 
Now, I have a Jenkinsfile in my repo that is arbitrary. I keep it there to show off, as well as make edits easily when I need to. We are ultimately going to past it into Jenkins, so its up to you if you want to include it or not.
 
Take a moment to review it. Note the following:
 
  1. It has params at the top
  2. it checks my repo using Jenkins credentials that I supplied in my instance. These are SSH credentials (private key is in jenkins, public key is in Github). I have covered this in other videos.
  3. The Terraform stage has an if/else statement for apply or destroy
  4. Ansible has a retry block in case the connection doesn't work on first try (to avoid the error penalty). Also, note that it uses the -i to reference our Dynamic inventory.
 
Jenkinsfile
pipeline {
  agent any
  parameters {
    choice(
        name: 'Action',
        choices: "apply\ndestroy",
        description: 'Apply or Destroy the instance' )
  }
  stages {

    stage('Checkout') {
        steps {
            git branch: 'master', credentialsId: 'Github', url: 'git@github.com:ScottyFullStack/nginx-jenkins-ansible-terraform.git'
        }
    }

    stage('Terraform') {
      steps {
        script {
          if (params.Action == "apply") {
            sh 'terraform init terraform/static-site'
            sh 'terraform apply -var "name=hello" -var "group=web" -var "region=us-east-1" -var "profile=scottyfullstack" --auto-approve terraform/static-site'
          } 
          else {
            sh 'terraform destroy -var "name=hello" -var "group=web" -var "region=us-east-1" -var "profile=scottyfullstack" --auto-approve terraform/static-site'
          }
        }
      }
    }

    stage('Ansible') {
      steps {
        retry(count: 5) {
          sh 'ansible-playbook -i /etc/ansible/aws_ec2.yaml ansible/static-site/site.yaml'
        }
      }
    }
  }
}

 

Scroll down to the bottom where it says "Pipeline" and paste in the Jenkinsfile script. Save it and reload.
Try Building it with parameters and see how it goes!
You should be able to see each stage complete:
 

 
When you are done standing it up you can navigate to your EC2 url and verify it works.
 
You should see the ssl warning when using https
 

 
 
You can verify your SSL info as well by clicking the "Not Secure" at the top left.
 
Click through it and see your static site:
 

 
When you are done, You can head back to Jenkins, select "Destroy" and run it! Your verify your instance is terminated and run it for them as many times as they want!

Comments

Popular posts from this blog

Terraform

Scrum Master Interview help - Bootcamp

Kubernetes