Implémenter des actions personnalisées pour les pipelines utilisant une image de conteneur Docker générique
Utilisez les actions personnalisées ServiceNow pour collecter les données relatives à la création de demandes de changement, à l'analyse Sonar, à l'enregistrement d'artefacts et à l'enregistrement de packages dans votre pipeline à l'aide de l'image générique du conteneur Docker.
L'image Docker est un package logiciel qui vous permet d'exécuter une application. Cette image indique comment instancier un conteneur et détermine les composants logiciels devant être exécutés. Le conteneur Docker est un environnement virtuel qui combine le code de l'application et toutes les dépendances nécessaires à l'exécution de l'application. Pour plus d'informations sur Docker, consultez la documentation Docker.
Variables d'environnement pour GitLab
- SNOW_TOKEN : numéro de jeton ServiceNow. Cette variable est masquée et ne s'affiche pas dans les tâches.
- SNOW_TOOLID : ID de l'outil ServiceNow.
- SNOW_URL : URL de l'instance ServiceNow.
Lors de l'ajout de la variable SNOW_TOKEN, vous pouvez acquérir le jeton en sélectionnant le bouton Copier le jeton sur l'enregistrement de l'outil, situé dans la table Outil [sn_devops_tool].
Vous devez mettre à jour les variables d'environnement avec les valeurs disponibles dans la fenêtre contextuelle Configurer manuellement les webhooks sur la page d'enregistrement de l'outil. Pour plus d'informations sur le mode d'affichage des détails de connexion, consultez Configurer des webhooks à partir de l'enregistrement d'outil et Configurer manuellement des webhooks dans GitLab.
Variables d'environnement pour GitHub Actions
Pour configurer des images Docker, certaines variables d'environnement doivent être disponibles dans votre instance GitHub Actions.
- SNOW_TOKEN : numéro de jeton ServiceNow. Cette variable est masquée et ne s'affiche pas dans les tâches.
- SNOW_TOOLID : ID de l'outil ServiceNow.
- SNOW_URL : URL de l'instance ServiceNow.
- PIPELINE_ID : ID d’exécution du workflow d’un référentiel. Utilisation : PIPELINE_ID : ${{github.run_id }}
- API_V4_URL : URL du serveur GitHub. Utilisation : API_V4_URL : ${{ github.server_url }}
- JOB_ID : ID d’exécution du workflow d’un référentiel. Utilisation : PIPELINE_ID : ${{ github.run_id }}
- PROJECT_PATH : nom du workflow. Utilisation - PROJECT_PATH : ${{ github.repository }}/${{github.workflow}}
- REPOSITORY_NAME : nom du référentiel. Utilisation : REPOSITORY_NAME : ${{ github.repository }}
- RUN_ATTEMPT : nombre de tentatives de workflow. Utilisation : RUN_ATTEMPT : ${{ github.run_attempt }}
- PROJECT_TITLE : nom du workflow. Utilisation : PROJECT_TITLE : ${{ github.repository }}/${{github.workflow}}
- COMMIT_BRANCH : nom de la branche sur laquelle le workflow est en cours d’exécution. Utilisation : COMMIT_BRANCH : ${{ github.ref_name }}
- WORKFLOW_NAME : nom du workflow. Utilisation : WORKFLOW_NAME : ${{ github.workflow }}
Variables d'environnement pour Harness
Pour configurer des images Docker, certaines variables d'environnement doivent être disponibles dans votre instance Harness.
- SNOW_TOKEN : numéro de jeton ServiceNow. Cette variable est masquée et ne s'affiche pas dans les tâches.
- SNOW_TOOLID : ID de l'outil ServiceNow.
- SNOW_URL : URL de l'instance ServiceNow.
Vous devez transmettre les variables d'environnement suivantes dans votre pipeline Harness :
-
HARNESS_STAGE_NAME: "<+stage.identifier>"
-
HARNESS_PIPELINE_NAME: "<+org.identifier>/<+project.identifier>/<+pipeline.name>"
Image Docker ServiceNow
docker build -t servicenowdocker/sndevops:6.2.0docker push servicenowdocker/sndevops:6.2.0Vous pouvez également personnaliser le référentiel public app-devops-gitlab et créer votre propre image Docker à transmettre dans le pipeline.
Configuration de proxy
Si votre GitLab instance s’exécute derrière un serveur proxy ou si vous souhaitez acheminer les demandes via un proxy, vous devez configurer les paramètres du proxy à l’aide de variables d’environnement dans votre Docker déploiement.
- PROXY_ENDPOINT : # par exemple, http://localhost:7080 ou https://proxy.example.com:8080
- PROXY_USERNAME : # Facultatif : pour l’authentification de proxy
- PROXY_PASSWORD : # Facultatif : pour l’authentification de proxy
- PROXY_AUTH : # Facultatif : authentification alternative à l’aide de la clé API
- Nom d’utilisateur/mot de passe : utiliser PROXY_USERNAME et PROXY_PASSWORD
- Clé API : utiliser PROXY_AUTH
- Aucune authentification : ne pas définir les variables d’authentification
stages:
- package
package:
stage: package
image: servicenowdocker/sndevops:6.2.0
variables:
PROXY_ENDPOINT: "https://proxy.example.com:8080"
PROXY_USERNAME: "proxy_user"
PROXY_PASSWORD: "proxy_pass"
script:
- sndevopscli create package -n "package-name" -a '[{"name":"artifact-name","repositoryName":"artifact-repo-name","version":"1.3.0"}]'Étape de changement DevOps ServiceNow
stages:
- DevOpsChangeApproval
ServiceNow DevOps Change:
stage: DevOpsChangeApproval
image: servicenowdocker/sndevops:6.2.0
script:
- sndevopscli create change -p "{\"changeStepDetails\":{\"timeout\":3600,\"interval\":100},\"attributes\":{\"short_description\":\"Software Deployment\",\"description\":\"Software Deployment.\",\"assignment_group\":\"xxxxxxxxx\",\"implementation_plan\":\"Software update is tested and results can be found in Test Summaries Tab.\",\"backout_plan\":\"When software fails in production, the previous software release will be re-deployed.\",\"test_plan\":\"Testing if the software was successfully deployed or not\"}}"
Vous devez saisir les valeurs d'entrée pour cette action personnalisée sous la forme d'une chaîne au format JSON.
- changeStepDetails : [facultatif] contient les détails du délai d'expiration et de l'intervalle.
- interval : [facultatif] délai d'attente, en secondes, entre deux tentatives de l'API. La valeur par défaut est de 100 secondes.
- timeout : [facultatif] délai d'attente maximal, en secondes, avant l'échec de l'action. La valeur par défaut est de 3 600 secondes.Remarque :Lorsque la valeur du délai d’expiration est également disponible ici dans votre outil, la valeur du délai d’expiration précédant est prise en compte.
- attributes : [facultatif] les détails de l'attribut de demande de changement doivent être utilisés lors de la création d'un changement dans une instance ServiceNow. La demande de changement est un objet JSON placé entre accolades {} contenant des paires clé-valeur séparées par une virgule (,). Une paire clé-valeur se compose d'une clé et d'une valeur séparées par deux-points (:). Les clés prises en charge dans la paire clé-valeur sont les suivantes : short_description, description, assignment_group, implementation_plan, backout_plan, test_plan, etc.
- -ctx : [facultatif] paramètres de contexte supplémentaires au format JSON. Détails des variables d'environnement de GitHub qui seront utilisés pour générer la demande pour l'API de changement DevOps. Par exemple :
sndevopscli create change -ctx "{\"projectId\": \"123456\", \"attemptNumber\": \"${{ github.run_attempt }}\"}" -p "{\"changeStepDetails\": {\"timeout\":3600,\"interval\":100},\"autoCloseChange\":true,\"attributes\":{\"short_description\":\"G Venkata Automated Software Deployment\",\"description\":\"Automated Software Deployment.\",\"assignment_group\":\"a715cd759f2002002920bde8132e7018\",\"implementation_plan\":\"Software update is tested and results can be found in Test Summaries Tab.\",\"backout_plan\":\"When software fails in production, the previous software release will be re-deployed.\",\"test_plan\":\"Testing if the software was successfully deployed or not\"}}" - -w : [facultatif] indiquez si le pipeline doit attendre la création et l'approbation du changement. Par défaut, le pipeline attend la création du changement et son approbation.
- Porte de déploiement
- Cet attribut permet la transmission de données lors de la création d’une demande de changement à l’aide de
sndevopscli, tout en utilisant la fonctionnalité de tâche manuelle fournie par des outils tels que GitLab. Par exemple :stages: - DevOpsChangeApproval - deploy ServiceNow DevOps Change: stage: DevOpsChangeApproval image: servicenowdocker/sndevops:6.2.0 script: - sndevopscli create change -p '{"changeStepDetails":{"timeout":3600,"interval":100},"deploymentGateDetails":{"jobName":"sn-change-job"},"attributes":{"short_description":"Automated Software Deployment","description":"Automated Software Deployment.","implementation_plan":"Software update is tested and results can be found in Test Summaries Tab.","backout_plan":"When software fails in production, the previous software release will be re-deployed.","test_plan":"Testing if the software was successfully deployed or not"}}' sn-change-job: stage: deploy needs: job: ServiceNow DevOps Change when: manual allow_failure: false script: | echo sn-change-jobL’attribut facultatif deploymentGateDetails doit contenir un attribut jobName, qui contient le nom de la tâche manuelle en aval dans le pipeline.
Résultats de l'analyse SonarScan DevOps ServiceNow
stages:
- DevOpsSonarStage
ServiceNow DevOps SonarScan Results:
stage: DevOpsSonarStage
image: servicenowdocker/sndevops:6.2.0
script:
- sndevopscli create sonar -url 'https://sonarcloud.io' -projectKey 'devsystem2019_TestImportTest'
- url : [obligatoire] spécifie l'URL Sonar.
- projectKey : [obligatoire] spécifie la clé de projet Sonar.
- Limitation
- Lors de la création de résultats récapitulatifs de la qualité des logiciels, la variable d’environnement MERGE_REQUEST_SOURCE_BRANCH_NAME sera utilisée pour les pipelines de fusion, et DEFAULT_BRANCH sera utilisée pour les pipelines de balises, car la variable COMMIT_BRANCH n’est pas disponible pour les pipelines de fusion ou de balises. Pour plus d'informations, consultez la documentation GitLab.
Enregistrer l'artefact
stages:
- artifact
artifact:
stage: artifact
image: servicenowdocker/sndevops:6.2.0
script:
- sndevopscli create artifact -a "[{\"name\":\"Artifact-${JOB_NAME}\",\"repositoryName\":\"Repo\",\"version\":\"1.${JOB_ID}.0\"}]"
Vous devez saisir les valeurs d'entrée pour cette action personnalisée sous la forme d'une chaîne au format JSON.
-a : [Obligatoire] Cette valeur spécifie les détails de l’artefact.
Inscrire le package
stages:
- package
package:
stage: package
image: servicenowdocker/sndevops:6.2.0
script:
- sndevopscli create package -n "Package2" -a "[{\"name\":\"Artifact-${JOB_NAME}\",\"repositoryName\":\"Repo\" ,\"version\":\"1.${JOB_ID}.0\"}]"Vous devez saisir les valeurs d'entrée pour cette action personnalisée sous la forme d'une chaîne au format JSON.
-n : [obligatoire] spécifie le nom du package.
Obtenir un changement
Ajoutez au niveau de la tâche pour obtenir changeRequestNumber à partir de l'instance ServiceNow avec les détails de changement donnés pour identifier la demande de changement.
stages:
- DevOpsGetChange
ServiceNow DevOps Get Change:
stage: DevOpsGetChange
image: servicenowdocker/sndevops:6.2.0
script:
- sndevopscli get change -p "{\"buildNumber\":${CHG_JOB_ID},\"stageName\":\"ServiceNow DevOps Change Step\",\"pipelineName\":\"GitlabDockerGetAndUpdateChange\"}"
-p: It stands for changeDetails. The change details to be used for identifying change request in ServiceNow instance. The change details is a JSON object surrounded by curly braces {} containing key-value pair separated by a comma ,. A key-value pair consists of a key and a value separated by a colon :. The keys supported in key-value pair are buildNumber, pipelineName, stageName
buildNumber: [mandatory]
This specifies ID of the Job where we have created change request.
stageName: [mandatory]
This specifies the Job name where we have created change request..
pipelineName: [mandatory]
This specifies the pipeline name.
Outputs:
sndevopschg.json file created with content: {
"status": "SUCCESS",
"changeRequestNumber": "CHGXXXXX"
}
changeRequestNumber: Change Request Number found for the given change details
status: To know the status of the Change Request GET.
Mettre à jour le changement
Ajoutez au niveau de la tâche pour mettre à jour un changement dans l'instance ServiceNow pour le changeRequestNumber fourni comme entrée avec changeRequestDetails.
stages:
- DevOpsUpdateChangeStage
ServiceNow DevOps Update Change:
stage: DevOpsUpdateChangeStage
image: servicenowdocker/sndevops:6.2.0
script:
- sndevopscli update change -n 'CHGXXXXXX' -p "{\"short_description\":\"G Venkata12345 Automated Software Deployment\",\"description\":\"Automated Software Deployment.\",\"assignment_group\":\"XXXXX\",\"implementation_plan\":\"Software update is tested and results can be found in Test Summaries Tab.\",\"backout_plan\":\"When software fails in production, the previous software release will be re-deployed.\",\"test_plan\":\"Testing if the software was successfully deployed or not\"}"
-n [Not mandatory if we have sndevopschg.json in our pipeline yml]: It stands for changeRequestNumber. The change request number to identify a unique change request.
Precedence of choosing changeRequestNumber:
- changeRequestNumber mentioned in the pipeline yml
- changeRequestNumber stored in sndevopschg.json.
-p : It stands for changeDetails. The change details to be used for Updating the change request information identified by the specified change request number with the key-value pairs. The change details is a JSON object surrounded by curly braces {} containing key-value pair separated by a comma ,. A key-value pair consists of a key and a value separated by a colon :. The keys supported in key-value pair are short_description, state, description, work_notes ..so on
OR
- sndevopscli update change -p "{\"short_description\":\"Updated Automated Software Deployment\",\"description\":\"Automated Software Deployment.\",\"assignment_group\":\"XXXXXXXXXX\",\"implementation_plan\":\"Software update is tested and results can be found in Test Summaries Tab.\",\"backout_plan\":\"When software fails in production, the previous software release will be re-deployed.\",\"test_plan\":\"Testing if the software was successfully deployed or not\"}"
NOTE: State should be specified at last in case if you are update the state of change request.
- sndevopscli update change -p "{\"short_description\":\"Updated Automated Software Deployment\",\"description\":\"Automated Software Deployment.\",\"assignment_group\":\"XXXXXXXXXX\",\"implementation_plan\":\"Software update is tested and results can be found in Test Summaries Tab.\",\"backout_plan\":\"When software fails in production, the previous software release will be re-deployed.\",\"test_plan\":\"Testing if the software was successfully deployed or not\","state":"3"}'
Changement de fermeture automatique
Incorporez la fermeture automatique du changement dans l'instance ServiceNow. Pour des informations détaillées sur la fermeture automatique, consultez Configurer les détails de la demande de changement DevOps dans le pipeline.
stages:
- changeapproval
ServiceNow DevOps Change Step:
stage: changeapproval
image: servicenowdocker/sndevops:6.2.0
script:
- sndevopscli create change -p "{\"changeStepDetails\":{\"timeout\":3600,\"interval\":100},\"autoCloseChange\":true,\"attributes\":{\"short_description\":\"G Venkata Automated Software Deployment\",\"description\":\"Automated Software Deployment.\",\"assignment_group\":\"xxxxxxxx\",\"implementation_plan\":\"Software update is tested and results can be found in Test Summaries Tab.\",\"backout_plan\":\"When software fails in production, the previous software release will be re-deployed.\",\"test_plan\":\"Testing if the software was successfully deployed or not\"}}"
autoCloseChange: [optional] : Boolean value
Résultats de l'analyse de sécurité
stages:
- DevOpsSecurityScanStageServiceNow
ServiceNow DevOps Security Scan Results:
stage: DevOpsSecurityScanStageimage
image: servicenowdocker/sndevops:6.2.0
script:
- sndevopscli create securityScan -p "{\"pipelineInfo\":{\"buildNumber\":\"${PIPELINE_ID}\",\"pipelineExecutionUrl\":\"${PIPELINE_URL}\" },\"securityResultAttributes\":{ \"scanner\":\"Veracode\",\"applicationName\":\"PetStoreAPI-Github\",\"buildVersion\":\"\",\"securityToolId\":\"\"}}"
-p: [mandatory]It the payload of security result attributes. The payload will have attributes as follows:
buildNumber: PIPELINE_ID (mandatory)pipelineExecutionUrl: PIPELINE_URL (mandatory)scanner: Scanning tool and is required e.g. Checkmarx One.projectName/projectId: Name/Id of your Checkmarx One project and is required. This attribute is applicable only for Checkmarx One.applicationName: Name of your Veracode application and is required. This attribute is applicable only for Veracode.buildVersion": Veracode Scan name / build version and is optional. This attribute is applicable only for Veracode.scanId: Checkmarx One scan id and is optional. This attribute is applicable only for Checkmarx One.securityToolId: Security tool onboarded in ServiceNow (sys_id of the onboarded security tool) and is optional.
Exemples de pipelines
Exemple de pipeline GitLab
image: servicenowdocker/sndevops:6.2.0
stages:
- pre-build
- build
- sonar
- securityscan
- changeapproval
- getchange
- updatechange
- deploy
Pre-Build:
stage: pre-build
script:
- echo $JOB_NAME
Artifact and Package:
stage: build
script:
- sndevopscli create artifact -a "[{\"name\":\"Artifact-${JOB_NAME}\",\"repositoryName\":\"TestRepo\",\"version\":\"1.${RUNNER_ID}.0\"}]"
- sndevopscli create package -n "Test_Package" -a "[{\"name\":\"Artifact-${JOB_NAME}\",\"repositoryName\":\"TestRepo\",\"version\":\"1.${RUNNER_ID}.0\"}]"
ServiceNow DevOps SonarScan Results:
stage: sonar
script:
- sndevopscli create sonar -url 'https://sonarcloud.io' -projectKey 'xxxxxxx'
ServiceNow DevOps Security Scan Results:
stage: securityscan
script:
- sndevopscli create securityScan -p "{\"pipelineInfo\":{\"buildNumber\":\"${JOB_ID}\", \"stageName\":\"ServiceNow DevOps Security Scan Results\",\"taskExecutionUrl\":\"${JOB_URL}\" },\"securityResultAttributes\":{ \"scanner\":\"Veracode\",\"applicationName\":\"PetStoreAPI-Github\",\"buildVersion\":\"\",\"securityToolId\":\"\"}}"
ServiceNow DevOps Change Step:
stage: changeapproval
variables:
CHG_JOB_ID: $JOB_ID
script:
- echo "CHG_JOB_ID=$CHG_JOB_ID" >> generated_job_id.env
- sndevopscli create change -p "{\"changeStepDetails\":{\"timeout\":3600,\"interval\":100},\"autoCloseChange\":true,\"attributes\":{\"short_description\":\"G Venkata Automated Software Deployment\",\"description\":\"Automated Software Deployment.\",\"assignment_group\":\"a715cd759f2002002920bde8132e7018\",\"implementation_plan\":\"Software update is tested and results can be found in Test Summaries Tab.\",\"backout_plan\":\"When software fails in production, the previous software release will be re-deployed.\",\"test_plan\":\"Testing if the software was successfully deployed or not\"}}"
- sndevopscli get change #If we are placing get change cli command in the same job where we are creating change then no need to mention the changeDetails.
artifacts:
paths:
- generated_job_id.env
DevOps Get Change:
stage: getchange
script:
- source generated_job_id.env
- sndevopscli get change -p "{\"buildNumber\":${CHG_JOB_ID},\"stageName\":\"ServiceNow DevOps Change Step\",\"pipelineName\":\"SmrutiTestDemoProject\"}"
artifacts:
paths:
- sndevopschg.json
dependencies:
- ServiceNow DevOps Change Step
DevOps Update Change:
stage: updatechange
script:
#- sndevopscli update change -n 'CHGXXXX' -p "{\"short_description\":\"Automated Software Deployment\",\"description\":\"Automated Software Deployment.\",\"assignment_group\":\"xxxxxxx\",\"implementation_plan\":\"Software update is tested and results can be found in Test Summaries Tab.\",\"backout_plan\":\"When software fails in production, the previous software release will be re-deployed.\",\"test_plan\":\"Testing if the software was successfully deployed or not\"}"
- sndevopscli update change -p "{\"short_description\":\"Updated Automated Software Deployment\",\"description\":\"Automated Software Deployment.\",\"assignment_group\":\"xxxxxxx\",\"implementation_plan\":\"Software update is tested and results can be found in Test Summaries Tab.\",\"backout_plan\":\"When software fails in production, the previous software release will be re-deployed.\",\"test_plan\":\"Testing if the software was successfully deployed or not\"}"
dependencies:
- DevOps Get Change
Deploy Job:
stage: deploy
script:
- echo $JOB_NAME
Exemple de pipeline Actions GitHub
name: GithubAction
on:
push:
branches: ["main"]
pull_request:
branches: ["main"]
permissions:
contents: read
env:
SNOW_URL: ${{ secrets.SNOW_URL }}
SNOW_TOKEN: ${{ secrets.SNOW_TOKEN }}
SNOW_TOOLID: ${{ secrets.SNOW_TOOLID }}
# These are the optional env variables
#PIPELINE_ID: ${{ github.run_id }}
#API_V4_URL: ${{ github.server_url }}
#JOB_ID: ${{ github.run_id }}
#PROJECT_PATH: ${{ github.job }}
#REPOSITORY_NAME: ${{ github.repository }}
#RUN_ATTEMPT: ${{ github.run_attempt }}
#PROJECT_TITLE: ${{ github.repository }}/${{github.workflow}}
#COMMIT_BRANCH: ${{ github.ref_name }}
#WORKFLOW_NAME: ${{ github.workflow }}
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Set up JDK 17
run: |
echo 'hello'
ServiceNowDevOpsChange:
runs-on: ubuntu-latest
needs: build
container:
image: servicenowdocker/sndevops:6.2.0
env:
JOB_NAME: "ServiceNowDevOpsChange"
steps:
- name: create change
run: |
sndevopscli create change -p "{\"changeStepDetails\":{\"timeout\":3600,\"interval\":10},\"autoCloseChange\":true,\"attributes\":{\"short_description\":\"G Venkata Automated Software Deployment\",\"description\":\"Automated Software Deployment.\",\"assignment_group\":\"a715cd759f2002002920bde8132e7018\",\"implementation_plan\":\"Software update is tested and results can be found in Test Summaries Tab.\",\"backout_plan\":\"When software fails in production, the previous software release will be re-deployed.\",\"test_plan\":\"Testing if the software was successfully deployed or not\"}}"
ServiceNowUpdateDevOpsChange:
runs-on: ubuntu-latest
needs: ServiceNowDevOpsChange
container:
image: servicenowdocker/sndevops:6.2.0
env:
JOB_NAME: "ServiceNowDevOpsChange"
steps:
- name: update change
run: |
sndevopscli update change -p "{\"short_description\":\"Updated Automated Software Deployment\",\"description\":\"Automated Software Deployment.\",\"assignment_group\":\"a715cd759f2002002920bde8132e7018\",\"implementation_plan\":\"Software update is tested and results can be found in Test Summaries Tab.\",\"backout_plan\":\"When software fails in production, the previous software release will be re-deployed.\",\"test_plan\":\"Testing if the software was successfully deployed or not\"}"
ArtifactAndPackage:
runs-on: ubuntu-latest
needs: build
container:
image: servicenowdocker/sndevops:6.2.0
env:
JOB_NAME: "ArtifactAndPackage"
steps:
- name: create artifact
run: |
sndevopscli create artifact -a "[{\"name\": \"com:customactiondemo\",\"version\": \"1.${{ github.run_number }}\",\"semanticVersion\": \"1.${{ github.run_number }}.0\",\"repositoryName\": \"${{ github.repository }}\"}]"
sndevopscli create package -n "Test_Package" -a "[{\"name\": \"com:customactiondemo\",\"version\": \"1.${{ github.run_number }}\",\"semanticVersion\": \"1.${{ github.run_number }}.0\",\"repositoryName\": \"${{ github.repository }}\"}]"
ServiceNowDevOpsSonarScanResults:
name: ServiceNowDevOpsSonarScanResults
needs: ArtifactAndPackage
runs-on: ubuntu-latest
container:
image: servicenowdocker/sndevops:6.2.0
env:
JOB_NAME: "ServiceNowDevOpsSonarScanResults"
steps:
- name: devops soanr results
run: |
sndevopscli create sonar -url 'https://sonarcloud.io' -projectKey 'xxxxxxx'
ServiceNowDevOpsSecurityScan:
name: ServiceNowDevOpsSecurityScan
runs-on: ubuntu-latest
needs: build
container:
image: servicenowdocker/sndevops:6.2.0
steps:
- name: security scan
run: |
sndevopscli create securityScan -p "{ \"pipelineInfo\": { \"runId\": \"${{ github.run_id }}\", \"runNumber\": \"${{ github.run_number }}\", \"runAttempt\": \"${{ github.run_attempt }}\", \"job\": \"ServiceNowDevOpsSecurityScan\", \"workflow\": \"${{ github.workflow }}\", \"repository\": \"${{github.repository}}\" }, \"securityResultAttributes\": { \"scanner\": \"Veracode\", \"applicationName\": \"PetStoreAPI-Github\",\"buildVersion\": \"\", \"securityToolId\": \"\"}}"
Exemple de pipeline Harness
# This is an example pipeline, and your pipeline and container configurations may vary from the setup shown here.
# Refer to the pipeline stages for Security, Software, and Change configurations.
# Using this YAML file directly will not work as it contains several Harness-specific configurations; check the Command section present for container steps.
pipeline:
name: Example pipeline
identifier: Example_pipeline
projectIdentifier: Example_project
orgIdentifier: ExampleOrg
tags: {}
stages:
- stage:
name: Build
identifier: Build
description: ""
type: Custom
spec:
execution:
steps:
- step:
type: ShellScript
name: ShellScript_1
identifier: ShellScript_1
spec:
shell: Bash
executionTarget: {}
source:
type: Inline
spec:
script: echo "Building.."
environmentVariables: []
outputVariables: []
timeout: 10m
tags: {}
- stage:
name: ServiceNow DevOps Sonar Scan Results
identifier: ServiceNow_DevOps_Sonar_Scan_Results
description: ""
type: Custom
spec:
execution:
steps:
- step:
type: Container
name: Sonar container
identifier: Sonar_container
spec:
connectorRef: docker_connector # harness docker connector
image: servicenowdocker/sndevops:6.2.0
command: |-
export SNOW_URL="<+variable.SNOW_URL>"
export SNOW_TOOLID="<+variable.SNOW_TOOLID>"
export SNOW_TOKEN="<+variable.SNOW_TOKEN>"
export HARNESS_STAGE_NAME="<+stage.identifier>"
export HARNESS_PIPELINE_NAME="<+org.identifier>/<+project.identifier>/<+pipeline.name>"
export COMMIT_BRANCH="main"
sndevopscli create sonar -url 'https://sonarcloud.io' -projectKey 'SONAR_PROJECT_KEY' -branch "main"
shell: Sh
infrastructure:
type: KubernetesDirect
spec:
connectorRef: KUBE_CONNECTOR # harness kubernates connector
namespace: harness-delegate-ng
resources:
limits:
cpu: "0.5"
memory: 500Mi
annotations: {}
labels: {}
containerSecurityContext:
capabilities:
drop: []
add: []
nodeSelector: {}
reports:
type: JUnit
spec:
paths: []
outputVariables: []
envVariables: {}
timeout: 1h
tags: {}
- stage:
name: ServiceNow DevOps Security Scan Results
identifier: ServiceNow_DevOps_Security_Scan_Results
description: ""
type: Custom
spec:
execution:
steps:
- step:
type: Container
name: security
identifier: security
spec:
connectorRef: docker_connector # harness docker connector
image: servicenowdocker/sndevops:6.2.0
command: |-
export SNOW_URL="<+variable.SNOW_URL>"
export SNOW_TOOLID="<+variable.SNOW_TOOLID>"
export SNOW_TOKEN="<+variable.SNOW_TOKEN>"
sndevopscli create securityScan -p \
"{\"pipelineInfo\":{
\"buildNumber\":\"<+stage.nodeExecutionId>\",
\"taskExecutionUrl\":\"<+pipeline.executionUrl>?stage=<+stage.nodeExecutionId>\",
\"orchestrationPipeline\":\"<+org.identifier>/<+project.identifier>/<+pipeline.name>\"
},
\"securityResultAttributes\":{
\"scanner\":\"Veracode\",
\"applicationName\":\"VeraDemo-10\"
}
}"
shell: Sh
infrastructure:
type: KubernetesDirect
spec:
connectorRef: KUBE_CONNECTOR # harness kubernates connector
namespace: harness-delegate-ng
resources:
limits:
cpu: "0.5"
memory: 500Mi
annotations: {}
labels: {}
containerSecurityContext:
capabilities:
drop: []
add: []
nodeSelector: {}
reports:
type: JUnit
spec:
paths: []
outputVariables: []
envVariables: {}
timeout: 1h
tags: {}
- stage:
name: Deploy
identifier: Deploy
description: ""
type: Deployment
spec:
deploymentType: Kubernetes
service:
serviceRef: service
environment:
environmentRef: Dev
deployToAll: false
infrastructureDefinitions:
- identifier: Infra
execution:
steps:
- step:
type: Container
name: ServiceNow change
identifier: ServiceNow_change
spec:
connectorRef: docker_connector # harness docker connector
image: servicenowdocker/sndevops:6.2.0
command: |-
# set mandetory variables. These can be set from Environment variable section of Optional configuration as well.
export HARNESS_STAGE_NAME="<+stage.identifier>"
export SNOW_URL="<+variable.SNOW_URL>"
export SNOW_TOOLID="<+variable.SNOW_TOOLID>"
export SNOW_TOKEN="<+variable.SNOW_TOKEN>"
# "sndevopscli create change" command notifies ServiceNow DevOps to create a change.
# Ensure to update "upstreamStage" accordingly. Example, if you have 3 stages Test, Change and Deploy in your pipeline, then you must update as "upstreamStage": "<+pipeline.stages.Test.nodeExecutionId>". Note that if your change stage is the first stage, you can remove this line.
sndevopscli create change -ctx \
"{
\"pipelineExecutionUrl\":\"<+pipeline.executionUrl>\",
\"stageIdentifier\": \"<+stage.identifier>\",
\"stageNodeExecutionId\": \"<+stage.nodeExecutionId>\",
\"pipelineName\": \"<+pipeline.name>\",
\"upstreamStage\": \"<+pipeline.stages.ServiceNow_DevOps_Security_Scan_Results.nodeExecutionId>\"
}" -p \
"{
\"changeStepDetails\":
{
\"timeout\":3600,
\"interval\":100
},
\"autoCloseChange\":true,
\"attributes\":{
\"chg_model\":\"adffaa9e4370211072b7f6be5bb8f2ed\",
\"short_description\":\"Software Deployment\",
\"description\":\"Automated Software Deployment.\",
\"implementation_plan\":\"Software update is tested and results can be found in Test Summaries Tab.\",
\"backout_plan\":\"When software fails in production, the previous software release will be re-deployed.\",
\"test_plan\":\"Testing if the software was successfully deployed or not\"
}
}"
shell: Sh
infrastructure:
type: KubernetesDirect
spec:
connectorRef: KUBE_CONNECTOR # harness kubernates connector
namespace: harness-delegate-ng
resources:
limits:
cpu: "0.5"
memory: 500Mi
annotations: {}
labels: {}
containerSecurityContext:
capabilities:
drop: []
add: []
nodeSelector: {}
reports:
type: JUnit
spec:
paths: []
outputVariables: []
envVariables: {}
timeout: 1h
- step:
type: ShellScript
name: ShellScript_1
identifier: ShellScript_1
spec:
shell: Bash
executionTarget: {}
source:
type: Inline
spec:
script: echo "Deploying.."
environmentVariables: []
outputVariables: []
timeout: 10m
rollbackSteps: []
tags: {}
failureStrategies:
- onFailure:
errors:
- AllErrors
action:
type: StageRollback
properties:
ci:
codebase:
connectorRef: CONNECTOR
repoName: REPO_NAME
build: <+input>
sparseCheckout: []
notificationRules:
- name: devopsbugbashwp5
identifier: devopsbugbashwp5
pipelineEvents:
- type: AllEvents
notificationMethod:
type: Webhook
spec:
webhookUrl: https://{instance_url}/api/sn_devops/v2/devops/tool/orchestration?toolId={tool sys id}&projectId={project sys id}&ni.nolog.token={token}
enabled: true