---
sourceDocument: Zurich IT Service Management
sourceDocumentLink: https://www.servicenow.com/docs/r/pt-BR/zurich/it-service-management

 Release :

    - zurich

ft:locale :

    - pt-BR

ft:publication_title :

    - Zurich IT Service Management

ft:clusterId :

    - itsm

bundleId :

    - itsm

workflow :

    - Technology


---

# Imagem do Docker para ações personalizadas

# Implemente ações personalizadas para pipelines usando a imagem genérica do contêiner do Docker {#ariaid-title1}

* Versão de lançamento: Zurich
* 
* Atualizado 31 de jul. de 2025
* 
* ![](https://www.servicenow.com/docs/portal-asset/ico-clock) 17 min. de leitura

Use ServiceNow Ações personalizadas para coletar dados relacionados à criação de solicitação de mudança, verificação do sonar, registro de artefato e registro de pacote em seu pipeline com a ajuda do genérico Docker Imagem do contêiner.

Docker Imagem é um pacote de software que pode ser usado para executar uma aplicação. Esta imagem informa como um contêiner deve instanciar e quais componentes de software devem ser executados. Docker O contêiner é um ambiente virtual que combina o código da aplicação e todas as dependências necessárias para executar a aplicação. Para obter mais informações sobre Docker, consulte [Documentação do Docker](https://docs.docker.com/get-started/overview/).

## Variáveis ambientais para GitLab {#servicenow-custom-actions-for-gitlab__section_kd1_mfc_5cc}

Para configurar Docker As seguintes variáveis ambientais devem estar disponíveis em seu GitLab instância do seu projeto.

* SNOW_TOKEN: ServiceNow número do token. É uma variável mascarada e não será exibida nos trabalhos.
* SNOW_TOOLID: ServiceNow ID da ferramenta.
* SNOW_URL: ServiceNow URL da instância.

{#servicenow-custom-actions-for-gitlab__ul_nvc_2z5_yzb}Ao configurar um GitLab projeto, as variáveis ambientais são criadas para o projeto e os valores de variável configurados mais recentes são considerados. Se você for um cliente de upgrade, deverá reconfigurar o existente GitLab ou adicione manualmente as variáveis ambientais em seu GitLab instância. Para obter informações sobre como adicionar variáveis, consulte [Documentação do GitLab](https://docs.gitlab.com/ee/ci/variables/).

Ao adicionar a variável SNOW_TOKEN, você pode adquirir o token selecionando Token de cópia Botão no registro da ferramenta, localizado na tabela Ferramenta \[sn_devops_tool\].

As variáveis ambientais devem ser atualizadas com os valores disponíveis no pop-up Configurar webhooks manualmente na página de registro da ferramenta. Para obter detalhes sobre como exibir os detalhes da conexão, consulte [Configure webhooks a partir do registro da ferramenta](https://www.servicenow.com/docs/Ns5ErHkTHod2BtcgLtV3hA "Configure webhooks a partir do registro da ferramenta para enviar dados Velocidade de mudança para DevOps depois que sua ferramenta estiver conectada.") e. [Configure webhooks no GitLab manualmente](https://www.servicenow.com/docs/s_YEh2dUtb4ThwKwiG0V0g "Configure webhooks no GitLab para enviar notificações de trabalho, envio por push e problemas manualmente para DevOps aplicação.").

## Variáveis ambientais para GitHub Actions {#servicenow-custom-actions-for-gitlab__section_ihz_5fc_5cc}

Para configurar Docker Determinadas variáveis ambientais devem estar disponíveis em seu GitHub Actions instância.  
As seguintes variáveis de ambiente devem ser configuradas na instância de Ações do GitHub.  
Nota:  
As variáveis devem ser atualizadas com os valores disponíveis no pop-up Configurar webhooks manualmente na página de registro da ferramenta.

* SNOW_TOKEN: ServiceNow número do token. É uma variável mascarada e não será exibida nos trabalhos.
* SNOW_TOOLID: ServiceNow ID da ferramenta.
* SNOW_URL: ServiceNow URL da instância.

{#servicenow-custom-actions-for-gitlab__ul_jgd_xfc_5cc}  
Nota:  
Para obter informações sobre como adicionar variáveis em GitHub Actions, consulte [Documentação do GitHub](https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables).  
As seguintes variáveis de ambiente devem ser passadas no pipeline de ações do GitHub:  
Nota:  
Esses valores dessas variáveis são recuperados dinamicamente do GitHub e você não precisa configurá-los separadamente.  
* PIPELINE_ID: ID de execução do fluxo de trabalho de um repositório. Uso - PIPELINE_ID: github.run_id
* API_V4_url: URL do servidor GitHub. API_V4_url: github.server_url
* JOB_ID: ID de execução do fluxo de trabalho de um repositório. Uso - PIPELINE_ID: github.run_id
* PROJECT_PATH: Nome do fluxo de trabalho. PROJECT_PATH
* REPOSITORY_NAME: Nome do repositório. Uso - REPOSITÓRIO_NAME
* RUN_ATTEMPT: Número de tentativas de fluxo de trabalho. Uso - RUN_ATTEMPT: github.run_attempt
* PROJECT_TITLE: Nome do fluxo de trabalho. PROJECT_TITLE
* COMMIT_BRANCH: Nome da ramificação na qual o fluxo de trabalho está sendo executado. COMMIT_BRANCH
* WORKFLOW_NAME: Nome do fluxo de trabalho. Uso - WORKFLOW_NAME
{#servicenow-custom-actions-for-gitlab__ul_t5h_hgv_mdc}Quando você configura um repositório, as variáveis ambientais são criadas para o repositório e os valores de variável configurados mais recentes são considerados. Se você for um cliente de upgrade, deverá reconfigurar seus repositórios existentes ou adicionar manualmente as variáveis ambientais em sua instância.

## Variáveis ambientais para chicote {#servicenow-custom-actions-for-gitlab__section_z1h_klf_vdc}

Para configurar Docker Determinadas variáveis ambientais devem estar disponíveis em sua instância do Harness.  
As seguintes variáveis de ambiente devem ser configuradas na instância do Harness.  
Nota:  
As variáveis devem ser atualizadas com os valores disponíveis no pop-up Configurar webhooks manualmente na página de registro da ferramenta.

* SNOW_TOKEN: ServiceNow número do token. É uma variável mascarada e não será exibida nos trabalhos.
* SNOW_TOOLID: ServiceNow ID da ferramenta.
* SNOW_URL: ServiceNow URL da instância.
{#servicenow-custom-actions-for-gitlab__ul_abh_klf_vdc}

As seguintes variáveis de ambiente devem ser passadas em seu pipeline de chicote:  
* HARISH_STAGE_NAME: "

* HARISH_PIPELINE_NAME: ""project.identifier"/"project.identifier"/"pipeline.name\>"

{#servicenow-custom-actions-for-gitlab__ul_bbh_klf_vdc}Quando você configura um repositório, as variáveis ambientais são criadas para o repositório e os valores de variável configurados mais recentes são considerados. Se você for um cliente de upgrade, deverá reconfigurar seus repositórios existentes ou adicionar manualmente as variáveis ambientais em sua instância.

## ServiceNow Imagem do Docker {#servicenow-custom-actions-for-gitlab__section_tys_cbd_zzb}

Você deve passar por ServiceNow Imagem do Docker (servicenowdocker/sndevops:5,1.0) no pipeline antes de adicionar ações personalizadas ao pipeline. Você pode clonar o repositório público app-devops-gitlab localizado em <https://github.com/ServiceNow/app-devops-gitlab>E crie a imagem do Docker executando os seguintes comandos:

    docker build -t servicenowdocker/sndevops:5.1.0

    docker push servicenowdocker/sndevops:5.1.0

Você pode adicionar a imagem do Docker no início do arquivo .yml. Você não precisa adicioná-lo para cada trabalho separadamente.  
Nota:  
Se você quiser usar várias imagens, adicione-as nos níveis de trabalho.

Você também pode personalizar o. app-devops-gitlab Repositório público e crie sua própria imagem do Docker para passar no pipeline.

## ServiceNow Etapa de mudança do DevOps {#servicenow-custom-actions-for-gitlab__section_w34_zw5_yzb}

Adicione ServiceNow Mudança de DevOps Etapa personalizada no nível do trabalho para criar uma mudança em sua instância da ServiceNow. Por exemplo:


    stages:
      - DevOpsChangeApproval

    ServiceNow DevOps Change:
      stage: DevOpsChangeApproval
      image: servicenowdocker/sndevops:5.1.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\"}}"

Nota:  
Se você estiver usando a etapa Mudança do Docker e a etapa Quando: Mudança de instrução manual, certifique-se de adicioná-las em diferentes níveis de trabalho.

Você deve inserir os valores de entrada para esta ação personalizada como uma cadeia de caracteres formatada em JSON.  
* ChangeStepDetails : \[Opcional\] Ele contém o tempo limite e os detalhes do intervalo.
* intervalo : \[Opcional\] O tempo em segundos de espera entre a tentativa da API. O valor padrão é 100 segundos.
* tempo limite : \[Opcional\] O tempo máximo em segundos para aguardar até que a ação falhe. O valor padrão é 3600 segundos.  
  Nota:  
  Quando o valor do tempo limite está disponível aqui também em sua ferramenta, o valor do tempo limite anterior é considerado.
* atributos : \[Opcional\] Os detalhes do atributo da solicitação de mudança devem ser usados ao criar uma mudança em um ServiceNow instância. A solicitação de mudança é um objeto JSON cercado por chaves que contém pares de chave-valor separados por uma vírgula(,). Um par chave-valor consiste em uma chave e um valor separados por dois pontos (:). As chaves compatíveis no par chave-valor são short_description, description, assignment_group, implementation_plan, backout_plan, test_plan e assim por diante.
* ctx : \[Opcional\] Parâmetros de contexto adicionais no formato JSON. Detalhes da variável ambiental do GitHub que serão usados para criar a solicitação para a API de mudança do DevOps. Por exemplo,

      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 : \[Opcional\] Especifique se o pipeline deve aguardar a criação e aprovação da mudança. Por padrão, o pipeline aguardará a criação da mudança e sua aprovação.

{#servicenow-custom-actions-for-gitlab__ul_szf_4bd_zzb}  
Nota:  
O nome da etapa de mudança deve conter Mudança do ServiceNow DevOps palavra-chave, que é o nome do trabalho.

## ServiceNow Resultados do DevOps SonarScan {#servicenow-custom-actions-for-gitlab__section_osj_zw5_yzb}

Adicione ServiceNow Etapa personalizada dos resultados do SonarScan no nível do trabalho para criar um resumo do Sonar em sua instância da ServiceNow. Por exemplo:


    stages:
      - DevOpsSonarStage

    ServiceNow DevOps SonarScan Results:
      stage: DevOpsSonarStage
      image: servicenowdocker/sndevops:5.1.0
      script: 
        - sndevopscli create sonar -url 'https://sonarcloud.io' -projectKey 'devsystem2019_TestImportTest'

* url : \[Obrigatório\] Especifica o URL do sonar.
* ProjectKey : \[Obrigatório\] Especifica a chave do projeto Sonar.

{#servicenow-custom-actions-for-gitlab__ul_nrg_hbd_zzb}  
Nota:  
O nome da etapa do sonar deve ser igual ao nome do trabalho, que é Resultados do SonarScan do ServiceNow DevOps .  

Limitação
:   Ao criar resultados de resumo de qualidade de software, a variável de ambiente MERGE_REQUEST_SOURCE_BRANCH_NAME será usada para mesclar pipelines e DEFAULT_BRANCH será usada para pipelines de marcador porque a variável COMMIT_BRANCH não está disponível para mesclar ou marcar pipelines. Para obter mais informações, consulte [Documentação do GitLab](https://docs.gitlab.com/ee/ci/variables/predefined_variables.html).

## Registrar artefato {#servicenow-custom-actions-for-gitlab__section_dmt_zw5_yzb}

Adicione a etapa personalizada do artefato no nível do trabalho para registrar um artefato em sua instância da ServiceNow. Por exemplo:


    stages:
      - artifact

    artifact:
      stage: artifact
      image: servicenowdocker/sndevops:5.1.0
      script: 
        - sndevopscli create artifact -a "[{\"name\":\"Artifact-${JOB_NAME}\",\"repositoryName\":\"Repo\",\"version\":\"1.${JOB_ID}.0\"}]"
     
Você deve inserir os valores de entrada para esta ação personalizada como uma cadeia de caracteres formatada em JSON.

-a : \[Obrigatório\] Especifica os detalhes do artefato.

## Registrar pacote {#servicenow-custom-actions-for-gitlab__section_jnc_tx5_yzb}

Adicione a etapa personalizada do pacote no nível do trabalho para registrar um pacote em sua instância da ServiceNow. Por exemplo:


    stages:
      - package

    package:
      stage: package
      image: servicenowdocker/sndevops:5.1.0
      script: 
        - sndevopscli create package -n "Package2" -a "[{\"name\":\"Artifact-${JOB_NAME}\",\"repositoryName\":\"Repo\" ,\"version\":\"1.${JOB_ID}.0\"}]"

Você deve inserir os valores de entrada para esta ação personalizada como uma cadeia de caracteres formatada em JSON.

-n : \[Obrigatório\] Especifica o nome do pacote.

## Obter mudança {#servicenow-custom-actions-for-gitlab__section_h34_tyw_v1c}

Adicione no nível de trabalho para obter changeRequestNumber ServiceNow Instância com os changeDetails fornecidos para identificar a solicitação de mudança.  
Por exemplo:



    stages:
      - DevOpsGetChange

    ServiceNow DevOps Get Change:
      stage: DevOpsGetChange
      image: servicenowdocker/sndevops:5.1.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.

## Atualizar mudança {#servicenow-custom-actions-for-gitlab__section_efb_lyw_v1c}

Adicione no nível de trabalho para atualizar a mudança em ServiceNow Instância do changeRequestNumber fornecido como entrada junto com changeRequestDetails.  
Por exemplo:


    stages:
      - DevOpsUpdateChangeStage

    ServiceNow DevOps Update Change:
      stage: DevOpsUpdateChangeStage
      image: servicenowdocker/sndevops:5.1.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"}'

## Fechar mudança automaticamente {#servicenow-custom-actions-for-gitlab__section_adl_hzw_v1c}

Incorporar mudança de fechamento automático em ServiceNow instância. Para obter informações detalhadas sobre o fechamento automático, consulte [Configurando DevOps detalhes da solicitação de mudança no pipeline](https://www.servicenow.com/docs/4QxXXL_qibO_n4xBEQK~YA "Configure como as informações de fechamento, o estado de mudança e os campos de solicitação de mudança são atualizados de dentro de um pipeline na etapa de mudança do pipeline.").  
Por exemplo:


    stages:
      - changeapproval

    ServiceNow DevOps Change Step:
      stage: changeapproval
      image: servicenowdocker/sndevops:5.1.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

## Resultados da verificação de segurança {#servicenow-custom-actions-for-gitlab__section_bzb_zl2_zdc}

Adicione ServiceNow Etapa personalizada dos resultados da verificação de segurança do DevOps no nível do trabalho para recuperar os resultados da verificação de segurança. Por exemplo:

    stages:
      - DevOpsSecurityScanStageServiceNow 

    ServiceNow DevOps Security Scan Results:
      stage: DevOpsSecurityScanStageimage 
      image: servicenowdocker/sndevops:5.1.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.
     
## Amostra pipelines {#servicenow-custom-actions-for-gitlab__section_dlv_1zl_vcc}

## Pipeline GitLab de amostra {#servicenow-custom-actions-for-gitlab__example_clj_4xl_vcc}


    image: servicenowdocker/sndevops:5.1.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

## Pipeline de ações do GitHub de amostra {#servicenow-custom-actions-for-gitlab__example_udm_5xl_vcc}

    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:5.1.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:5.1.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:5.1.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:5.1.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:5.1.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\": \"\"}}"

## Pipeline de chicote de amostra {#servicenow-custom-actions-for-gitlab__example_sfn_rlf_vdc}

    # 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:5.1.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:5.1.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:5.1.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

Nota:  
Se você quiser adicionar os resultados da verificação do sonar e os resultados da verificação de segurança na mesma fase, você pode usar nomes de etapa diferentes para as ações personalizadas atualizando o valor padrão em sonar_step_names e. security_step_names campos na tabela sn_devops_tool_integration_configuration.

