Friday, 4 March 2022

Setting Up Cd Pipeline for Terraform

 

  • Go back to Jenkins and select your terraform pipeline and click  Configure
  • Scroll down to Pipeline and click on the drop down to select Pipeline Script From SCM
  • Enter credentials for Bitbucket, Leave the Branch master as the default, Make sure script path is Jenkinsfile
  • Right click on Pipeline Syntax and open in a new tab. 
  • Choose Checkout from Version Control in the Sample Step field
  • Enter Bitbucket Repository URL and Credentials, leave the branches blank
  • Click GENERATE PIPELINE SCRIPT, copy credentialsId and url (This is required for Jenkinsfile script)



Create Workspace for Terraform Pipeline
  • Open File Explorer, navigate to Desktop and create a folder cd_pipeline

  • Once folder has been created, open Visual Code Studio and add folder to workspace







  • Open a New Terminal
  • Run the command before cloning repo: git init
  • Navigate to terraform-pipeline repo in Bitbucket
  • Clone the repo with SSH or HTTPS
  • Create a new file main.tf and copy the below code in yellow color



















provider "aws" {
region = var.region
version = "~> 2.0"
}
resource "aws_instance" "ec2" {
user_data   = base64encode(file("deploy.sh"))
ami = "ami-0782e9ee97725263d"   ##Change AMI to meet OS requirement as needed.
root_block_device {
    volume_type           = "gp2"
    volume_size           = 200
    delete_on_termination = true
    encrypted             = true
  }
tags = {
Name = "u2-${var.environment}-${var.application}"
CreatedBy = var.launched_by
Application = var.application
OS = var.os
Environment = var.environment
}
instance_type = var.instance_type
key_name = "Enter_KEYPAIR_Name_Here"
vpc_security_group_ids = [aws_security_group.ec2_SecurityGroups.id]
}
output "ec2_ip" {
value = [aws_instance.ec2.*.private_ip]
}
output "ec2_ip_public" {
value = [aws_instance.ec2.*.public_ip]
}
output "ec2_name" {
value = [aws_instance.ec2.*.tags.Name]
}
output "ec2_instance_id" {
value = aws_instance.ec2.*.id


  • Create a new file security.tf and copy the below code in yellow color

resource "aws_security_group" "ec2_SecurityGroups" {
name = "u2-${var.environment}-sg-${var.application}"
description = "EC2 SG"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
     from_port   = 8081
to_port     = 8081
protocol    = "tcp"
cidr_blocks = ["0.0.0.0/0"]
   }
ingress {
     from_port   = 8082
to_port     = 8082
protocol    = "tcp"
cidr_blocks = ["0.0.0.0/0"]
   }
   ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
#Allow all outbound
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}

  • Create a new file variable.tf and copy the below code in yellow color. 

variable region {
  type        = string
  default = "us-east-2"
}
variable "instance_type" {}
variable "application" {}
variable "environment" {}
############## tags
variable os {
  type        = string
  default = "Ubuntu"
}
variable launched_by {
  type        = string
  default = "USER"
}
############## end tags


Bash Script to Deploy Artifactory

  • Create a new file deploy.sh and copy the below code in yellow color. 
#!/bin/bash
set -x

exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1 

echo ""
echo "........................................"
echo "Installation of application"
echo "........................................"
echo "Today's date: `date`"
echo "........................................"
echo ""
sudo pip install awscli
sudo apt-get install -y unzip
sudo apt update
sudo apt dist-upgrade
sudo apt autoremove
sudo apt update
sudo apt-get install openjdk-8-jdk openjdk-8-doc
java -version
sudo apt install wget software-properties-common
sudo wget -qO - https://api.bintray.com/orgs/jfrog/keys/gpg/public.key | sudo apt-key add - 
sudo add-apt-repository "deb [arch=amd64] https://jfrog.bintray.com/artifactory-debs $(lsb_release -cs) main"
sudo apt update
sudo apt install jfrog-artifactory-oss
sudo systemctl stop artifactory.service
sudo systemctl start artifactory.service
sudo systemctl enable artifactory.service
sudo systemctl status artifactory.service
echo ""
echo "........................................"
echo "Installation of application"
echo "........................................"
echo "Today's date: `date`"
echo "........................................"
echo ""




  • Create a new file Jenkinsfile and copy the below code in yellow color. 



pipeline {
    agent{ label '!master' }
    parameters {
        string(name: 'AppName', defaultValue: 'Enter App Name', description: 'Name of application', )
        choice(choices: ['master', 'dev', 'qa', 'prod'], description: 'Select lifecycle to Deploy', name: 'Branch')
        choice(choices: ['t2.micro', 't2.small', 't2.medium'], description: 'Select Instance Size', name: 'InstanceSize')
        booleanParam(name: 'autoApprove', defaultValue: false, description: 'Automatically run apply after generating plan?')
    }


     environment {
        AWS_ACCESS_KEY_ID     = credentials('AWS_ACCESS_KEY_ID')
        AWS_SECRET_ACCESS_KEY = credentials('AWS_SECRET_ACCESS_KEY')
        TF_VAR_instance_type = "${params.InstanceSize}"
        TF_VAR_environment = "${params.Branch}"
        TF_VAR_application = "${params.AppName}"
    }
// 

    stages {
      stage('checkout') {
        steps {
            echo "Pulling changes from the branch ${params.Branch}"
            git credentialsId: 'paste-credentialsId-here', url: 'paste-url-here' , branch: "${params.Branch}"
        }
      }

        stage('terraform plan') {
            steps {
                sh "pwd ; terraform init -input=true"
                sh "terraform plan -input=true -out tfplan"
                sh 'terraform show -no-color tfplan > tfplan.txt'
}
            }
        
        stage('terraform apply approval') {
           when {
               not {
                   equals expected: true, actual: params.autoApprove
               }
           }

           steps {
               script {
                    def plan = readFile 'tfplan.txt'
                    input message: "Do you want to apply the plan?",
                    parameters: [text(name: 'Plan', description: 'Please review the plan', defaultValue: plan)]
               }
           }
       }

        stage('terraform apply') {
            steps {
                sh "terraform apply -input=true tfplan"
            }
        }
        
        stage('terraform destroy approval') {
            steps {
                input 'Run terraform destroy?'
            }
        }
        stage('terraform destroy') {
            steps {
                sh 'terraform destroy -force'
            }
        }
    }

  }

  • Commit and push code changes to Repo with the following:
    • In Vscode, navigate to Source Code Icon on the right tabs on the side
    • Enter commit message
    • Click the + icon to stage changes 

    • Push changes by clicking on the ðŸ”„0 ⬇️ 1 ⬆️ as shown below

Run Pipeline Job

  • Go to terraform-pipeline on Jenkins and run build 
Note: The pipeline job will fail the first time to capture the parameters in Jenkinsfile

  • The next time you run a build you should see as shown below





  • Enter Artifactory in the AppName field
  • Select a Branch/Lifecycle to deploy server
  • Choose t2.small or t2.medium for Artifactory server.
  • Go to Console Output to track progress
Note: You can abort the destroy step and rerun the step by installing Blue Ocean Plugin on Jenkins to delete the resources created.

No comments:

Post a Comment

How to upgrade Maven

  java.lang.IllegalStateException I had installed maven in my ubuntu using command  apt install maven This installed maven in path /usr/shar...