Showing posts with label AEM Deployment. Show all posts
Showing posts with label AEM Deployment. Show all posts

January 5, 2021
Estimated Post Reading Time ~

Continuous Delivery on Adobe AEM

I get asked a lot what I think about various topics on Adobe AEM. Many large companies are now attempting to implement a solution on Adobe AEM, and Continuous Delivery is one of the topics that keeps coming up. Unlike many typical features of AEM, there is not much guidance in the documentation about how to implement Continuous Delivery yet I believe AEM is very much suitable for it. So I wanted to share my thoughts on this topic hoping it might help someone in their implementation of AEM.

What is Continuous Delivery?
I understand Continuous Delivery as an IT process of continuously releasing pieces of content or functionality, from inception at a whiteboard to release to production, without downtime, often fully automated. This is in contrast to the typical enterprise IT process that requires many manual steps, the involvement of many people, and a typical release cycle of one to two weeks.

Continuous Delivery is often associated with an Agile development process, as it allows us to deliver small pieces of production quality functionality, frequently. And I don't just mean iterative delivery such as in fortnightly iterations, but multiple releases per day.

These additional requirements on the IT processes - frequency, quality, no downtime - also spread beyond the processes, on the architecture, IT infrastructure, development processes and tooling, quality processes, and company culture.

Continuous Delivery on Adobe AEM

The architecture of Adobe AEM as the platform leverages itself particularly well to Continuous Delivery because of OSGi and JCR.

OSGi modularity
OSGi allows the development and deployment of individual modules (bundles). OSGi is an SOA within a single Java process, and it allows you to be as granular with your deployment units as you need. You can go Micro Services, deploying individual service implementations at once, or bundle the whole subsystem. But either way, you get a straightforward (almost) no-downtime deployment mechanism via bundles, which also supports easy rollback.

Flexible modularity also means the ability to develop functionality independently so your developers can work on multiple work streams in parallel. And because you can deploy as big or as small units as you need, it works well with Agile development processes where the scope of a deployable task could be a single component or a service.

Deploying to JCR
In Adobe AEM, JCR typically stores the components, templates, and front-end artifacts in the form of objects with metadata, and these are deployed via packages. The neat thing about those is that they are typically static files or scripts, plus metadata, which doesn't require any restart. So they come into effect immediately after being updated, and you can update any piece of JCR at any time - whether it is one component, or the whole website (called Projects in AEM) - and it takes milliseconds to seconds. As the result, you can continuously evolve JCR, on the fly, without any downtime, deploying multiple features in parallel to production. And to mitigate the risks, simple rollback mechanisms such as deploying the previous version of a package, or creating a reverse package, can be used.

Because AEM architecture is so simple - a single application component is a single instance and a single Java process, in non-clustered cases the deployment only touches a single instance. Apart from caching, very little can go out-of-sync or wrong - the artifacts are either in JCR and active, or they are not. Even in clustering scenarios, the deployment to a cluster of production Publish instance (the riskiest scenario) is often done via replication which is aware of clustering and ensures all Publish instances are in sync.

Feature switches
Feature switches are a mechanism that allows instantaneous change of system behavior without redeployment. Typically Feature switches are used to control risky or incomplete features, and for a/b testing of functionality, and because of that they can be used to reduce the risks of deploying features at a rapid pace.

Consider the scenario when during a day, 5 features were implemented and deployed by different developers. 4 of them work fine, and 1 does not work. If you were to deal with the situation in a typical source-controlled environment, you'd have to make a reverse commit for the broken commit, test and redeploy. But with Feature switches, you can simply disable the broken functionality until the time when it's fixed.

Feature switches can be implemented on both OSGi service properties and JCR properties as they can be controlled by HTTP requests.

Caching
Caching is the only thing that requires careful planning and sometimes additional work. As Adobe AEM is designed to be heavily cached (the guideline is 90%), any changes to underlying resources need to be propagated to the caching layers. There is no all-matching solution, however, Adobe AEM has enough mechanisms (such as flush URLs, JCR update triggers, replication URLs), all accessible via HTTP requests, which allow the caching state to be controlled automatically as part of the deployment process.

Deployment Process
AEM has a set of Maven archetypes and plugins which make it easy to build and deploy the code to environments. You can also include all the design artifacts, components, and even default content. This allows us to keep the single source of truth for all instances in all development environments in a source repository, and build new instances in existing or new environments via a maven build.

Backup and Restore
In AEM, the backup operation is simply "xcopy" of the application folder, and restore is just copying it somewhere else, and running there. Because of that, it's very easy to replicate or bootstrap AEM instances on-demand, so you can comfortably manage dozens of instances and environments at the same time.

Also, because these operations are so simple, they can be automated, so it's easy to support scenarios where environments need to be rebuilt or replicated. For example, creating DR Author or Publish instance after deployment, or restoring environments after data center failure.

So why no Continuous Delivery?
Considering how simple AEM architecture is, how straightforward and safe the deployment operations are, and how many tools and mechanisms AEM has in order to support deployments, it would be surprising if organizations did not implement Continuous Delivery on AEM. Of course, Continuous Integration and Deployment are not the only things that need to be implemented to achieve Continuous Delivery, but the remaining things are more to do with the organization's development and quality processes. And at least AEM is providing a great technological foundation in order to achieve smooth Continuous Delivery.


By aem4beginner

Continuous Delivery with Jenkins and AEM

Introduction
We all know CI - Continuous Integration and the next step is: CD - Continuous Delivery. Which is a combination of many steps to automate the build, test, release, and deploy process.

There are some options we can choose from such as Jenkins or the GitLab Integration (https://stackoverflow.com/questions/37429453/gitlab-ci-vs-jenkins).

We use Jenkins Pipelines (https://jenkins.io/doc/book/pipeline/) because I discovered the GitLab integration too late and at that time the Jenkins process was already finished. Otherwise, I would strongly recommend trying the GitLab integration to prevent the "Jenkins Plugin Hell". (Another alternative is https://de.atlassian.com/software/bamboo)

Basics
The goal is to see the CD process as part of the code and not as a separate part of development. Because of this reason, the process is described in script files that are committed to GIT.

Now we have the advantage that we don't need to edit the Jenkins-Job-Configuration every time we need to change the process. If we have a new server we can (theoretically) easily start our CD process without creating new jobs on the new server.

In the case of Jenkins, we need to store a "Jenkinsfile" under the root directory of our project. This Jenkinsfile can be written in the Jenkins-Pipeline language or in groovy or a mix of both.

Requirements
Jenkins needs to be at least at version 2 (because we need the Jenkins Pipeline)    
Following Plugins are needed to get the example Jenkinsfile running          
In the Jenkins "Global Tool Configuration" maven needs to be defined:

Example Jenkinsfile
Following steps are executed   
  1. Update the project/maven/pom version    
  2. Create a GIT-Tag with the new version    
  3. Push the new version to the branch
  4. Upload the artifact to the Nexus Repository
  5. Commit the new version to the child/develop branch
  6. Deploy the new version to the AEM Author and Publish instance
The complete file

#!groovy​

node {

    def version
    def webAppTarget = "xxx"
    def sourceBranch = "develop"
    def releaseBranch = "quality-assurance"
    def nexusBaseRepoUrl = "http://xxx"
    def repositoryUrl = "http://xxx"
    def gitCredentialsId = "xxx"
    def nexusRepositoryId = "xxx"
    def configFileId = "xxx"
    def mvnHome = tool 'M3'

    def updateQAVersion = {
        def split = version.split('\\.')
        //always remove "-SNAPSHOT"
        split[2] = split[2].split('-SNAPSHOT')[0]
        //increment the middle number of version by 1
        split[1] = Integer.parseInt(split[1]) + 1
        //reset the last number to 0
        split[2] = 0
        version = split.join('.')
    }

    //FIXME: use SSH-Agent
   //FIXME: use SSH-Agent

sh "git config --replace-all credential.helper cache"
sh "git config --global --replace-all user.email gituser@xxx.de; git config --global --replace-all user.name gituser"

configFileProvider([configFile(fileId: "${configFileId}", variable: "MAVEN_SETTINGS")]) {

    stage('Clean') {
        deleteDir()
    }

    dir('qa') {
        stage('Checkout QA') {
                echo 'Load from GIT'
                git url: "${repositoryUrl}", credentialsId: "${gitCredentialsId}", branch: "${releaseBranch}"
       }

            stage('Increment QA version') {
                version = sh(returnStdout: true, script: "${mvnHome}/bin/mvn -q -N org.codehaus.mojo:exec-maven-plugin:1.3.1:exec -Dexec.executable='echo' -Dexec.args='\${project.version}'").toString().trim()
                echo 'Old Version:'
                echo version
                updateQAVersion()
                echo 'New Version:'
                echo version
            }

            stage('Set new QA version') {
                echo 'Clean Maven'
                sh "${mvnHome}/bin/mvn -B clean -s '$MAVEN_SETTINGS'"

                echo 'Set new version'
                sh "${mvnHome}/bin/mvn -B versions:set -DnewVersion=${version}"
            }

            stage('QA Build') {
                echo 'Execute maven build'
                sh "${mvnHome}/bin/mvn -B install -s '$MAVEN_SETTINGS'"
            }

            stage('Push new QA version') {
                echo 'Commit and push branch'
                sh "git commit -am \"New release candidate ${version}\""
                sh "git push origin ${releaseBranch}"
            }

            stage('Push new tag') {
                echo 'Tag and push'
                sh "git tag -a ${version} -m 'release tag'"
                sh "git push origin ${version}"
            }

            stage('QA artifact deploy') {
                echo 'Deploy artifact to Nexus repository'
                try {
                    sh "${mvnHome}/bin/mvn deploy:deploy-file -DpomFile=pom.xml -DrepositoryId=${nexusRepositoryId} -Durl=${nexusBaseRepoUrl} -Dfile=${webAppTarget}/target/${webAppTarget}-${version}.zip -Dpackaging=zip -s '$MAVEN_SETTINGS'"
                } catch (ex) {
                    println("Artifact could not be deployed to the nexus!")
                    println(ex.getMessage())
                }
            }

            stage('Deploy AEM Author') {
                echo 'deploy on author'
                withCredentials([usernamePassword(credentialsId: '6a613b0f-631b-453a-9f34-6a69e8676877', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
                    sh "curl -u ${USERNAME}:${PASSWORD} -F file=@\"${webAppTarget}/target/${webAppTarget}-${version}.zip\" -F force=true -F install=true http://doom.eggs.local:64592/crx/packmgr/service.jsp"
                }
            }

            stage('Deploy AEM Publish') {
                echo 'deploy on publish'
                withCredentials([usernamePassword(credentialsId: '3a25eefc-d446-4793-a621-9f15e4774126', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
                    sh "curl -u ${USERNAME}:${PASSWORD} -F file=@\"${webAppTarget}/target/${webAppTarget}-${version}.zip\" -F force=true -F install=true http://doom.eggs.local:64594/crx/packmgr/service.jsp"
                }
            }
        }

        dir('develop') {
            stage('Checkout develop') {
                echo 'Load from GIT'
                git url: "${repositoryUrl}", credentialsId: "${gitCredentialsId}", branch: "${sourceBranch}"
            }

            stage('Set new develop version') {
                echo 'Clean Maven'
                sh "${mvnHome}/bin/mvn -B clean -s '$MAVEN_SETTINGS'"

                echo 'Set new version'
                sh "${mvnHome}/bin/mvn -B versions:set -DnewVersion=${version}-SNAPSHOT"
            }

            stage('Develop Build') {
                echo 'Execute maven build'
                sh "${mvnHome}/bin/mvn -B install -s '$MAVEN_SETTINGS'"
            }

            stage('Push new develop version') {
                echo 'Commit and push branch'
                sh "git commit -am \"New QA release candidate ${version}\""
                sh "git push origin ${sourceBranch}"
            }
        }
    }

}

Step by step explanation
Code Snippet #1

#!groovy

Our pipeline script is a groovy script (declarative) so we annotate this file as groovy for our development environment.

Code Snippet #2
node {

With the node, we declare this script as a scripted pipeline (see declarative pipeline for comparison)

Code Snippet #3
def version
    def webAppTarget = "xxx"
    def sourceBranch = "develop"
    def releaseBranch = "quality-assurance"
    def nexusBaseRepoUrl = "http://xxx"
    def repositoryUrl = "http://xxx"
    def gitCredentialsId = "xxx"
    def nexusRepositoryId = "xxx"
    def configFileId = "xxx"
    def mvnHome = tool 'M3'

    def updateQAVersion = {
        def split = version.split('\\.')
        //always remove "-SNAPSHOT"
        split[2] = split[2].split('-SNAPSHOT')[0]
        //increment the middle number of version by 1
        split[1] = Integer.parseInt(split[1]) + 1
        //reset the last number to 0
        split[2] = 0
        version = split.join('.')
    }

Some variables like the branch names and the credential-ids that are used to log into GIT. And a function updateQAVersion that removes the "-SNAPSHOT" and increments the middle number (2.1.12-SNAPSHOT → 2.2.0)

Code Snippet #4
//FIXME: use SSH-Agent

sh "git config --replace-all credential.helper cache"
sh "git config --global --replace-all user.email gituser@xxx.de; git config --global --replace-all user.name gituser"

configFileProvider([configFile(fileId: "${configFileId}", variable: "MAVEN_SETTINGS")]) {

    stage('Clean') {
        deleteDir()
    }

    dir('qa') {
        stage('Checkout QA') {
                echo 'Load from GIT'
                git url: "${repositoryUrl}", credentialsId: "${gitCredentialsId}", branch: "${releaseBranch}"
       }
Set the git credentials with the help of the credential.helper. Clean the directory for a fresh checkout.

The first stage (Jenkins Pipelines are grouped by stages) which will load the project sources with the help of the Jenkins Credentials Plugin (https://wiki.jenkins.io/display/JENKINS/Credentials+Plugin)

With dir('qa') we set the workspace/location (because we use two separate branches in this script) 

Code Snippet #5
stage('Increment QA version') {
    version = sh(returnStdout: true, script: "${mvnHome}/bin/mvn -q -N org.codehaus.mojo:exec-maven-plugin:1.3.1:exec -Dexec.executable='echo' -Dexec.args='\${project.version}'").toString().trim()
    echo 'Old Version:'
    echo version
    updateQAVersion()
    echo 'New Version:'
    echo version
}

stage('Set new QA version') {
    echo 'Clean Maven'
    sh "${mvnHome}/bin/mvn -B clean -s '$MAVEN_SETTINGS'"

    echo 'Set new version'
    sh "${mvnHome}/bin/mvn -B versions:set -DnewVersion=${version}"
}

stage('QA Build') {
    echo 'Execute maven build'
    sh "${mvnHome}/bin/mvn -B install -s '$MAVEN_SETTINGS'"
}

Now we use the exec-maven-plugin to read the project version from the pom.xml. We set "returnStdout" to return the terminal output and place it into the "version" variable.

Then we use our function "updateQAVersion()" to get the next version and update our pom-files with the "versions:set" goal of maven.

After that, we build the project to get the build package.

Code Snippet #6
stage('Push new QA version') {
    echo 'Commit and push branch'
    sh "git commit -am \"New release candidate ${version}\""
    sh "git push origin ${releaseBranch}"
}

stage('Push new tag') {
    echo 'Tag and push'
    sh "git tag -a ${version} -m 'release tag'"
    sh "git push origin ${version}"
}

The next stage is used to push the project with the changed version to the branch and create a tag. This only works because we set the "credential.helper cache". The get() function of groovy/pipeline does not support push (see Code Snippet #4)

Code Snippet #7
stage('QA artifact deploy') {
    echo 'Deploy artifact to Nexus repository'
    try {
        sh "${mvnHome}/bin/mvn deploy:deploy-file -DpomFile=pom.xml -DrepositoryId=${nexusRepositoryId} -Durl=${nexusBaseRepoUrl} -Dfile=${webAppTarget}/target/${webAppTarget}-${version}.zip -Dpackaging=zip -s '$MAVEN_SETTINGS'"
    } catch (ex) {
        println("Artifact could not be deployed to the nexus!")
        println(ex.getMessage())
    }
}

This stage deploys the created artifact (a .zip-file) to our Nexus Repository with the help of the maven command line command deploy:deploy-file. The configFileProvider is once again a Jenkins-Plugin which provides us with the maven settings.xml in which the credentials for the Nexus are defined.

Code Snippet #8
stage('Deploy AEM Author') {
    echo 'deploy on author'
    withCredentials([usernamePassword(credentialsId: 'xxx', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
        sh "curl -u ${USERNAME}:${PASSWORD} -F file=@\"${webAppTarget}/target/${webAppTarget}-${version}.zip\" -F force=true -F install=true http://xxx/crx/packmgr/service.jsp"
    }
}

stage('Deploy AEM Publish') {
    echo 'deploy on publish'
    withCredentials([usernamePassword(credentialsId: 'xxx', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
        sh "curl -u ${USERNAME}:${PASSWORD} -F file=@\"${webAppTarget}/target/${webAppTarget}-${version}.zip\" -F force=true -F install=true http://xxx/crx/packmgr/service.jsp"
    }
}

Now in the AEM-Deploy stage, we call curl commands and deploys it to the AEM-Servers.

Code Snippet #9
dir('develop') {
    stage('Checkout develop') {
        echo 'Load from GIT'
        git url: "${repositoryUrl}", credentialsId: "${gitCredentialsId}", branch: "${sourceBranch}"
    }

    stage('Set new develop version') {
        echo 'Clean Maven'
        sh "${mvnHome}/bin/mvn -B clean -s '$MAVEN_SETTINGS'"

        echo 'Set new version'
        sh "${mvnHome}/bin/mvn -B versions:set -DnewVersion=${version}-SNAPSHOT"
    }

    stage('Develop Build') {
        echo 'Execute maven build'
        sh "${mvnHome}/bin/mvn -B install -s '$MAVEN_SETTINGS'"
    }

    stage('Push new develop version') {
        echo 'Commit and push branch'
        sh "git commit -am \"New QA release candidate ${version}\""
        sh "git push origin ${sourceBranch}"
    }
}

Because we changed the version from "1.2.12" to "1.3.0" in the qa-branch we want to change the version in the develop-branch too. In the develop-branch, we add the "-SNAPSHOT" to the new version.

Conclusion
We have a functioning release process, from incrementing the maven/project version, creating tags, deploying to the nexus repository until we deploy it to the AEM-Instances. Even other branches can be updated. We have full control and are very flexible.

This saves a lot of work for developers.

But this process is not perfect    
  • The error handling is none existing (can be optimized)    
  • We need a separate Jenkins-Trigger-Job that calls the pipeline or else the pipeline calls itself after it commits to the branch. (We would need to implement something like ci-skip into our pipeline)
  • We need to configure a lot of credentials and maven settings in Jenkins


By aem4beginner

January 4, 2021
Estimated Post Reading Time ~

Build automation with Gradle

As all the world knows, inside CI/CD exists an automated building. This concept is so important in DevOps because here you build your package and run automate tests (depends on the result if you are continuous or abort the next phases). I know that already there is a lot of documentation about this topic, but I will write about my concerns and opinions.

Gradle works with a few CI tools, such as Jenkins, Travis, and TeamCity. Its ideal for a lot of languages, even, it can be extended by plugins (developed mainly by the community). Another feature that I like is its simplicity. All commands and use are logical, so, you no need a lot of memory in your head to remember how it works and extend its functionality.

Installation in RedHat/Centos/Fedora distributions
Firstly, you need to install a JDK, for me, OpenJDK is the best option because It is into the repositories.

sudo [yum|dnf] install unzip java-1.8.0-openjdk -y

Create the home directory for Gradle.
sudo mkdir /opt/gradle
sudo chown gradleuser: /opt/gradle

Download the binary from the official site.
wget -O ~/gradle-6.5-bin.zip https://services.gradle.org/distributions/gradle-6.5-bin.zip

Uncompress the archive file.
unzip -d /opt/gradle/ gradle-6.5-bin.zip
sudo vi /etc/profile.d/gradle.sh

Add this variable declaration in the afore-mentioned file.
export GRADLE_HOME=/opt/gradle/gradle-6.5export PATH=$PATH:$GRADLE_HOME/bin

Logout from your current session and login again.

Test your installation.
gradle --version

Output

Gradle Basics
You have to put it into your project directory. So, once there, you must initialize with the following command. Be free to put where you want, surely you will discover a better way.

cd $MYPROJECTDIRECTORY/
gradle init

After that, some files would be generated.


The file named build.gradle must contain all tasks to build our packages. In this example as the project does not exist yet, I will not build a package, I just only show how to use this file. In the next posts, I will use real examples.

I write two tasks and both just print a message.


Then, I test them../gradlew myTask


Second test../gradlew mySecondTask


Surely at one moment, we will structure our build having dependencies inside the file between tasks.


The last line of the picture is where I have declared my dependency. “mySecondTask depends on myTask”. We will see.



By aem4beginner

Continuous Integration and Continuous Delivery with CA API Gateway and Jenkins


Many companies are modernising their systems as part of the mobilisation and digitisation of the business. DevOps concepts are being employed to increase the delivery velocity of modern applications to the business. With DevOps, it is critical to automate all aspects of deploying new software features. The time required for manual steps adds up and defeats DevOps goals. In the example below, we have automated API and policy management to speed deployment, introduce continuous integration concepts, and place API artifacts under source code management.

In an effort towards modernisation of the API and the organization moving towards Agile from the traditional waterfall, DevOps is becoming essential in making sure the development and operations team work towards a common goal. Achieving continuous integration and delivery is key and is aided by multiple tools in the market. As each organization builds APIs for easy consumption and monetisation, continuous integration and delivery is an integral part of the solution to enable fast to market.

The following steps depict how you can achieve continuous integration and delivery for CA API Gateway, which is widely used across multiple industries for exposing APIs and more importantly to secure the APIs:


1. Develop a policy in policy manager
2. Export a Policy: Export the policy XML using a headless java utility called Gateway Migration Utility, available from CA, and check in the artifacts
  • Create an argFile.properties with the below arguments
    • host – host name of the gateway from which the policy has to be exported
    • port – Port number to connect to the gateway
    • username – username to connect to the gateway
    • password – encoded password of the gateway
    • format – specify as a single file if the export is for policy file or folder for a folder
    • dest= policy XML name for storing the XML
    • serviceName= Actual Policy name in the gateway
    • encryptionPassphrase – Passphrase for encryption
3. Before export, validate the connection to the gateway is successful using the gateway migration utility command below
  • GatewayMigrationUtility.sh browse -z argFile.properties -r –showIds – this should list all the policies running in the gateway.
4. Migrate out the policy from the gateway by using the gateway utility command below
  • GatewayMigrationUtility.sh migrateOut –argFile argFile.properties
5. Externalise the variable with the values from the exported policy XML using the below command
  • GatewayMigrationUtility.sh template –bundle policyAPI.xml –template policyTemplate-.properties – This will create the template properties file with the key/value pair having variable names and corresponding values, and the values in the file can be modified with specific environment properties.
6. Create a Mapping file for the mappings. These are used to specify the action to be used for a given type and the srcId when importing to different environments.
  • Copy the mappings section from the bundle file
  • Save the mappings as policyAPIMappings.xml
  • Modify the properties for the type as required
7. Check in the policy XML, Mappings XML, argFile properties file, and template property files to the code repository

8. Import a Policy: Configure Jenkins to poll the files for the policy from the code repository


9. Package the artifacts (policy XML, mappings XML, argFile, and template properties file ) to artifactory or any build file storage

10. Configure SSH to send the files over to the build server and execute the migrate in command as below



11. Configure the test cases for the policy as a test suite to execute the test cases after the migration to the target gateway and publish the results

Note: The above example uses credentials (username/password) of the gateway to import and export the policy out of the gateway. You can do this using the certs as a mechanism to import /export the policy.

Reference: CA API Gateway Documentation
It is necessary to automate deployment for all components to optimize the velocity of software innovation. In the example above we have eliminated a manual step associated with API deployment.


By aem4beginner

Automation of Package Deployment in AEM

SYNOPSIS:

Following is the guide to Download, Install, Replicate AEM Package and Flush the Dispatcher Cache. The Job can be achieved in several different ways, and there is always room for improvement. In this tutorial we shall download the package from lower environments and install the downloaded package to a different environment.

This Tutorial is an advancement to the following blog AEM-Download,Install,Replicate.

Tools Used:

  • Powershell
  • cURL
  • Windows 10 Enterprise
  • Jenkins

Prerequisites:
ACS Commons Package, make sure the package is available on the Author instance where the package is being installed, Script utilizes the acs commons dispatcher flush component to trigger the dispatcher flush agent under the Replication — agents on author.
Compatibility — Check package compatibility with the following at Compatibility chart and Download the respective package
Download — Package can be downloaded from Download–ACS Commons 3.19.0
ACS Commons Installation Guide
Jenkins Plugins used

  1. Parameterized Build Plugin
  2. Cloudbees Credentials Plugin
  3. Credentials Binding Plugin
  4. Powershell Plugin

Guide:
STEP-01: Agents on Author — Target Host

Configuring the Dispatcher flush agent of the Target Host machine, and ACS Commons dispatcher flush component on Target Host.
Replication Agents on Author
  1. Go to the miscadmin URL
  2. From the left sidebar menu select Replication
  3. Under the Replication, select Agents on Author
  4. From the Main Menu, Double-Click Dispatcher Flush Agent
Dispatcher Flush Agent
  1. Go to Dispatcher Flush Agent URL
  2. Click Edit, to configure Dispatcher
Dispatcher Flush Settings TAB
  1. Go to SETTINGS tab
  2. Name the Dispatcher flush Agent
  3. Enable Flush Agent
Dispatcher Flush Agent — Transport TAB
  1. Go to Transport TAB
  2. Add the URI for the Dispatcher instance
Dispatcher Flush Agent — Triggers TAB
  1. Go to the Triggers TAB
  2. Enable the on/off time Boundary value for page
  3. Finally Save all settings by clicking OK.
STEP – 02: ACS Commons — Dispatcher Flush
Using the acs commons package, we shall trigger the dispatcher flush agent and the path to flush using dispatcher flush agent
ACS Commons — Dispatcher Flush
  1. Go to acs commons dispatcher flush url
  2. Select Acs Commons from the left sidebar
  3. Select Dispatcher Flush under ACS Commons
  4. Click New on the main dispatcher flush page
Dispatcher Flush Agent — Template
  1. Add Title to the agent
  2. Select the dispatcher flush Template
  3. Finally, Click create
ACS Commons — Custom Dispatcher Flush
  1. Select the newly created flush agent ‘sd-disp-flush’
  2. Double Click on the Flush agent to configure
Flush Agent — Configuration
  1. Verify the Name of the Agent
  2. This is the Dispatcher Flush Agent from Agents on Author (from previous step)
  3. Click on EDIT, to configure the flush agent
Cache Flush Method
Select whether to delete or invalidate cache
Paths to flush
  1. Click on Add Item, to add path to be flushed
  2. Select the appropriate path to form the list
  3. Repeat step-2 to add additional paths
  4. When done adding paths, click OK to save configuration
STEP-03: Powershell Script For Automation
  1. Declaring required Parameters and variables
param( [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$CURLEXE = "C:\tools\curl76\bin\curl.exe", [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$AEMENV = "PROD", [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$packageName = "$ENV:Enter_Package_Name", [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$CQ_USER = "$ENV:SDUsernameUAT", [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$CQ_PASSD = "$ENV:SDPasswordUAT", [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$CQ_PASSI = "$ENV:SDpasswordPRD", [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$HOSTNAMED = "192.168.2.7", [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$HOSTNAMEI = "192.168.2.9", [parameter(Mandatory=$False,ValueFromPipeline=$False)][Int]$AEMPORTD = 4502, [parameter(Mandatory=$False,ValueFromPipeline=$False)][Int]$AEMPORTI = 4502, [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$packURL = "http://${HOSTNAMED}:${AEMPORTD}/crx/packmgr/list.jsp", [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$packData = (cmd.exe /c $CURLEXE -u "${CQ_USER}:${CQ_PASSD}" "${packURL}" 2>$null), [parameter(Mandatory=$False,ValueFromPipeline=$False)]$psData = ( $packData | ConvertFrom-JSON ), [parameter(Mandatory=$False,ValueFromPipeline=$False)][String[]]$packDName = @(($psData.results | ? { $_.Name -eq "$packageName"}).downloadName), [parameter(Mandatory=$False,ValueFromPipeline=$False)][String[]]$GroupData = @(($psData.results | ? { $_.Name -eq "$packageName" }).group), [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$GroupName = ($GroupData[($GroupData.length)-1]), [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$PKGNAME = $packDName[($packDName.length)-1], [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$PKGPATH = "${PKGNAME}", [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$ValidationURL = "http://${HOSTNAMEI}:${AEMPORTI}/crx/packmgr/index.jsp#/etc/packages/${GroupName}/${PKGNAME}", [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$DCURL = "http://${HOSTNAMED}:${AEMPORTD}/etc/packages/${GroupName}/${PKGNAME}", [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$ICURL = "http://${HOSTNAMEI}:${AEMPORTI}/crx/packmgr/service.jsp", [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$RCURL = "http://${HOSTNAMEI}:${AEMPORTI}/crx/packmgr/service/script.html/etc/packages/${GroupName}/${PKGNAME}?cmd=replicate", [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$DFLUSH = "http://${HOSTNAMEI}:${AEMPORTI}/etc/acs-commons/dispatcher-flush/sd-disp-flush/_jcr_content/configuration.flush.html" )

2. Function Block — Begin{}
Begin {
        # Stopping the job if it encounters error 
        $ErrorActionPreference  = 'Stop'
        $ScriptName       =   $MyInvocation.MyCommand.Name
        # Clear-Host
        Write-Host -F Green  " "
        Write-Host -F Green  "****************************************************************" 
        Write-Host -F Green  "Starting $AEMENV Deploy Process at [$([DateTime]::Now)]."  
        Write-Host -F Green  "***************************************************************" 
        Write-Host -F Green  " " 
        Write-Host -F Green  "Script Name:                  $ScriptName"
        Write-Host -F Green  "Environment:                  $AEMENV"
        Write-Host -F Green  "Download Host Details:        $HOSTNAMED, $AEMPORTD"
        Write-Host -F Green  "Install Host Details:         $HOSTNAMEI, $AEMPORTI"
        Write-Host -F Green  "Package Name:                 $PKGNAME"
        Write-Host -F Green  "Package Group:                $GroupName"
        Write-Host -F Green  " " 
        Write-Host -F Green  "**************************************************************" 
        Write-Host -F Green  " "
    }

Custom Code to Check if Group Name contains spaces  and replace them with HTML URL encoding — PROCESS{} Block

if ($GroupName -like "* *") {

    $DCURL  =   ($DCURL).Replace(' ','%20')

    $ICURL  =   ($ICURL).Replace(' ','%20')

    $RCURL  =   ($RCURL).Replace(' ','%20')

    $DFLUSH =   ($DFLUSH).Replace(' ','%20')

    $ValidationURL =    ($ValidationURL).Replace(' ','%20')

}

Custom code block to check if the Installation Host is using http or https and based on that change the URL

if ($AEMPORTI -eq '5443') {

    $ICURL  =   ($ICURL).Replace('http','https')

    $RCURL  =   ($RCURL).Replace('http','https')

    $DFLUSH =   ($DFLUSH).Replace('http','https')

    $ValidationURL = ($ValidationURL).Replace('http','https')

}

Custom code to Download the package

# Downlaod Package --BEGIN

Write-Host " "

Write-Host -F Green ">>>> Downloading Package $PKGNAME from $HOSTNAMED"

Write-Host -F Green " "

cmd.exe /c $CURLEXE -u "${CQ_USER}:${CQ_PASSD}" "${DCURL}" --Output "${PKGPATH}"

if ($?) {

    $DwnEC = "True"

    Write-Host -F Green " "

    Write-Host -F Green ">>>> Package Downlaod Complete"

    Write-Host -F Green " "

}else {

    Write-Host -F Green " "

    Write-Host -F RED ">>>> Package Downlaod Failed"

    Write-Host -F Green " "

}

Custom code to upload and install the downloaded package, the upload and installation will only commence if the package download is successful.

# Download package --END

if ($DwnEC -eq "True") {

    # Installing the Package --BEGIN

    Write-Host -F Green " "

    Write-Host -F Green ">>>> Installing $PKGNAME Package on $HOSTNAMEI"

    Write-Host -F Green " "

    if ($AEMPORTI -eq 5443) {

        cmd.exe /c $CURLEXE -ku "${CQ_USER}:${CQ_PASSD}" -F file=@"${PKGPATH}" -F name="${packageName}" -F force=true -F install=true "${ICURL}" | Out-Null

    }else {

        cmd.exe /c $CURLEXE -u "${CQ_USER}:${CQ_PASSD}" -F file=@"${PKGPATH}" -F name="${packageName}" -F force=true -F install=true "${ICURL}" | Out-Null

    }

    if ($?) {

        $INSTEC = "True"

        Write-Host -F Green " "

        Write-Host -F Green ">>>> Package Installation Complete"

        Write-Host -F Green " "

    }else {

        Write-Host -F Green " "

        Write-Host -F RED ">>>> Package Installation Failed"

        Write-Host -F Green " "

    }

    # Package Installation --END

}

Following is the entire script to download the package, upload and install, replicate the package and finally clear the dispatcher cache

param(

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$CURLEXE          =   "C:\tools\curl76\bin\curl.exe",

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$AEMENV           =   "PROD",

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$packageName      =   "$ENV:Enter_Package_Name",

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$CQ_USER          =   "$ENV:SDUsernameUAT",

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$CQ_PASSD         =   "$ENV:SDPasswordUAT",

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$CQ_PASSI         =   "$ENV:SDpasswordPRD",

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$HOSTNAMED        =   "192.168.2.7",

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$HOSTNAMEI        =   "192.168.2.9",

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][Int]$AEMPORTD            =   4502,

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][Int]$AEMPORTI            =   4502,

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$packURL          =   "http://${HOSTNAMED}:${AEMPORTD}/crx/packmgr/list.jsp",

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$packData         =   (cmd.exe /c $CURLEXE -u "${CQ_USER}:${CQ_PASSD}" "${packURL}" 2>$null),

     [parameter(Mandatory=$False,ValueFromPipeline=$False)]$psData                   =   ( $packData | ConvertFrom-JSON ),

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String[]]$packDName      =   @(($psData.results | ? { $_.Name -eq "$packageName"}).downloadName),

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String[]]$GroupData      =   @(($psData.results | ? { $_.Name -eq "$packageName" }).group),

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$GroupName        =   ($GroupData[($GroupData.length)-1]),

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$PKGNAME          =   $packDName[($packDName.length)-1],

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$PKGPATH          =   "${PKGNAME}",

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$ValidationURL    =   "http://${HOSTNAMEI}:${AEMPORTI}/crx/packmgr/index.jsp#/etc/packages/${GroupName}/${PKGNAME}",

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$DCURL            =   "http://${HOSTNAMED}:${AEMPORTD}/etc/packages/${GroupName}/${PKGNAME}",

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$ICURL            =   "http://${HOSTNAMEI}:${AEMPORTI}/crx/packmgr/service.jsp",

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$RCURL            =   "http://${HOSTNAMEI}:${AEMPORTI}/crx/packmgr/service/script.html/etc/packages/${GroupName}/${PKGNAME}?cmd=replicate",

     [parameter(Mandatory=$False,ValueFromPipeline=$False)][String]$DFLUSH           =   "http://${HOSTNAMEI}:${AEMPORTI}/etc/acs-commons/dispatcher-flush/sd-disp-flush/_jcr_content/configuration.flush.html"

)


Function SDProdDeploy {

    Begin {

        # Stopping the job if it encounters error 

        $ErrorActionPreference  = 'Stop'

        $ScriptName       =   $MyInvocation.MyCommand.Name

        # Clear-Host

        Write-Host -F Green  " "

        Write-Host -F Green  "***************************************************************" 

        Write-Host -F Green  "Starting $AEMENV Deploy Process at [$([DateTime]::Now)]."  

        Write-Host -F Green  "*************************************************************" 

        Write-Host -F Green  " " 

        Write-Host -F Green  "Script Name:                  $ScriptName"

        Write-Host -F Green  "Environment:                  $AEMENV"

        Write-Host -F Green  "Download Host Details:        $HOSTNAMED, $AEMPORTD"

        Write-Host -F Green  "Install Host Details:         $HOSTNAMEI, $AEMPORTI"

        Write-Host -F Green  "Package Name:                 $PKGNAME"

        Write-Host -F Green  "Package Group:                $GroupName"

        Write-Host -F Green  " " 

        Write-Host -F Green  "**************************************************************" 

        Write-Host -F Green  " "

    }

    Process {

        if ($packDName -ne $null) {


            # Check if group name contains spaces

            if ($GroupName -like "* *") {

                $DCURL  =   ($DCURL).Replace(' ','%20')

                $ICURL  =   ($ICURL).Replace(' ','%20')

                $RCURL  =   ($RCURL).Replace(' ','%20')

                $DFLUSH =   ($DFLUSH).Replace(' ','%20')

                $ValidationURL =    ($ValidationURL).Replace(' ','%20')

            }

            if ($AEMPORTI -eq '5443') {

                $ICURL  =   ($ICURL).Replace('http','https')

                $RCURL  =   ($RCURL).Replace('http','https')

                $DFLUSH =   ($DFLUSH).Replace('http','https')

                $ValidationURL = ($ValidationURL).Replace('http','https')

            }

            # Downlaod Package --BEGIN

            Write-Host " "

            Write-Host -F Green ">>>> Downloading Package $PKGNAME from $HOSTNAMED"

            Write-Host -F Green " "

            cmd.exe /c $CURLEXE -u "${CQ_USER}:${CQ_PASSD}" "${DCURL}" --Output "${PKGPATH}"

            if ($?) {

                $DwnEC = "True"

                Write-Host -F Green " "

                Write-Host -F Green ">>>> Package Downlaod Complete"

                Write-Host -F Green " "

            }else {

                Write-Host -F Green " "

                Write-Host -F RED ">>>> Package Downlaod Failed"

                Write-Host -F Green " "

            }

            # Download package --END

            if ($DwnEC -eq "True") {

                # Installing the Package --BEGIN

                Write-Host -F Green " "

                Write-Host -F Green ">>>> Installing $PKGNAME Package on $HOSTNAMEI"

                Write-Host -F Green " "

                if ($AEMPORTI -eq 5443) {

                    cmd.exe /c $CURLEXE -ku "${CQ_USER}:${CQ_PASSD}" -F file=@"${PKGPATH}" -F name="${packageName}" -F force=true -F install=true "${ICURL}" | Out-Null

                }else {

                    cmd.exe /c $CURLEXE -u "${CQ_USER}:${CQ_PASSD}" -F file=@"${PKGPATH}" -F name="${packageName}" -F force=true -F install=true "${ICURL}" | Out-Null

                }

                if ($?) {

                    $INSTEC = "True"

                    Write-Host -F Green " "

                    Write-Host -F Green ">>>> Package Installation Complete"

                    Write-Host -F Green " "

                }else {

                    Write-Host -F Green " "

                    Write-Host -F RED ">>>> Package Installation Failed"

                    Write-Host -F Green " "

                }

                # Package Installation --END

            }

            if ($INSTEC -eq "True") {

                # Replicate Package --BEGIN

                Write-Host -F Green " "

                Write-Host -F Green ">>>> Replicating Package $PKGNAME on $HOSTNAMEI"

                Write-Host -F Green " "

                if ($AEMPORTI -eq 5443) {

                    cmd.exe /c $CURLEXE -ku "${CQ_USER}:${CQ_PASSI}" -X POST $RCURL | Out-Null

                }else {

                    cmd.exe /c $CURLEXE -u "${CQ_USER}:${CQ_PASSI}" -X POST $RCURL | Out-Null

                }

                if ($?) {

                    $REPEC = "True"

                    Write-Host -F Green " "

                    Write-Host -F Green ">>>> Package Replication Complete"

                    Write-Host -F Green " "

                }else {

                    Write-Host -F Green " "

                    Write-Host -F RED ">>>> Package Replication Failed"

                    Write-Host -F Green " "

                }

                # Package Replication --END

            }

            if ($REPEC -eq "True") {

                # Flush Dispatcher using ACS Commons --BEGIN

                Write-Host -F Green " "

                Write-Host -F Green ">>>> Flushing Dispatcher Cache"

                Write-Host -F Green " "

                if ($AEMPORTI -eq 5443) {

                    cmd.exe /c $CURLEXE -ku "${CQ_USER}:${CQ_PASSI}" -X POST $DFLUSH | Out-Null

                }else {

                    cmd.exe /c $CURLEXE -u "${CQ_USER}:${CQ_PASSI}" -X POST $DFLUSH | Out-Null

                }

                if ($?) {

                    Write-Host -F Green " "

                    Write-Host -F Green ">>>> Dispatcher Flush Complete"

                    Write-Host -F Green " "

                }else {

                    Write-Host -F Green " "

                    Write-Host -F RED ">>>> Dispatcher Flush Failed"

                    Write-Host -F Green " "

                }

            }

        }else {

            Write-Host -F Red ">>>>"   Package Name: ($packageName).toupper()   "-- Not Found."

        }

    }

   End {

     If ($?) {

       Write-Host -F Green ""

       Write-Host -F Green ">>>> Verification URL"

       Write-Host -F Green "Install Host URL: $ValidationURL"

       Write-Host -F Green ""

       Write-Host -F Green "**************************************************************"

       Write-Host -F Green "Finished processing at [$([DateTime]::Now)]."

       Write-Host -F Green "*************************************************************"

       Write-Host -F Green ""

     }

  }

}

SDProdDeploy


STEP-04: Automating the Package deployment using Jenkins and Powershell
Following is the process, where package name is given as input to the build job on Jenkins. Then based on the package name, script will parse through AEM [Download Host], if found, will gather DownloadName, Groupname of the package.
Project Description
  1. Go to General TAB
  2. Add the project description
Housekeeping
  1. Select the House keeping strategy for the project
  2. Mention the number of days to keep the builds
  3. Mention max number of builds to keep
Extensible Choice Parameter
We shall use the extensible choice parameter, if not already install, got to plugin manager and install the plugin, see prerequisites
  1. Select the Extensible choice parameter
  2. Name of the Variable in the Script
  3. Describe the Variable
  4. Select the Textarea Choice parameter
  5. Add the choices as shown in the above figure
  6. Select the option, which would be displayed as the default choice
  7. Enable Editable option, to manually add package name, if package is not listed on the list
  8. Parameter to display all of selected choices
Bindings — AEM username and password
Use the credentials bindings parameter to enter the credentials for AEM instances
  1. Enable bindings by selecting Use secrets option under Build Environment
  2. Binding parameter
  3. Use the separated option
  4. Declare username variable
  5. Declare password variable
  6. Choose the credentials from credentials list to assign them to above variables
Build — Windows Powershell
Select Build Step
Add windows powershell from the list
Add the powershell script from STEP-03
Post-Build Action — Clean Workspace
Clean up the workspace after building the project
Building Project
  1. Select “Build with Parameters“
  2. click on the Textarea, Can manually enter package name here if not in list
  3. Select the desired package from the list
B
Build Output
  1. Console output of the Build
  2. Describes the Environment, AEM hosts, Port numbers, Package name and Group
  3. Information about the package being downloaded
  4. Information about the package being uploaded and installed
  5. Information about the package being Replicated
  6. Information about the flushing dispatcher cache
  7. Link/URL to the deployed AEM instance to verify the Deployment
  8. Workspace cleanup
Source:
https://skydevops.co.in/2019/02/17/aem-automation-package-deployment/


By aem4beginner