---
title: "Integration with Jenkins"
canonical: "https://docs.getxray.app/space/XRAY/301501616/Integration%20with%20Jenkins"
format: markdown
---
![image](media://8774b7d6-8e02-43ea-a1b2-e1b921e654c8)

> Macro (toc)

# Overview

Xray enables easy integration with Jenkins through the "Xray for JIRA Jenkins Plugin", providing the means for successful Continuous Integration by allowing users to report automated testing results.

# Release Notes


> Macro (children)

# Installation

The installation is made manually. For more information on how to install add-ons, please refer to [how to install add-ons](https://jenkins.io/doc/book/managing/plugins/).


> ℹ️ **Requirements**
> ℹ️ 
> ℹ️ The Jenkins baseline for this app is v2.138.4 and it may not work properly with previous versions.

##   
Manual Installation


> ℹ️ **Download the latest version of the Jenkins Plugin**
> ℹ️ 
> ℹ️ You may download the latest version of the Jenkins plugin from the latest [Release Notes](https://getxraydocs.atlassian.net/wiki/spaces/XRAY/pages/301403889).


If you have the actual `xray-connector.hpi` file,

1. Go to the Update Center of Jenkins in Manage Jenkins > Manage Plugins.
2. Select the Advanced tab
3. In the Upload Plugin section, click upload and select the file `xray-connector.hpi` file.


## Jenkins Native Installation (via web UI)

Since version 2.1.0, you can install the plugin by using the Jenkins native Web UI. You can read more about how to do it [here](https://jenkins.io/doc/book/managing/plugins/#from-the-web-ui).

# Configuration

Xray for Jenkins is configured in the global settings configuration page **Manage Jenkins** > **Configure System > Xray for Jira configuration**.

## Credential permissions

If you want to ket your Jenkins' users to use their own Jira credentials in each build, you need to make sure that the users that need to configure the jobs have both USE ITEM and USE OWN permissions.

These permissions are not configurable in the Credentials plugin by default, you need to run your Jenkins instance with the following flags enabled:

`          -Dcom.cloudbees.plugins.credentials.UseOwnPermission=true` `-Dcom.cloudbees.plugins.credentials.UseItemPermission=true`

After enabling these flags, go to the Credentials plugin configuration page, and give the required users the USE ITEM and USE OWN permissions.

You can read more about these permissions in the official [CloudBees documentation](https://docs.cloudbees.com/docs/cloudbees-ci/latest/cloud-secure-guide/authentication-mapping).

## Jira Instance

The Jira configuration defines connections with Jira instances.

To add a new Jira instance connection, you need to specify some properties:

1. **Configuration alias**
2. **Hosting: ** <span style="color: #172B4D">Hosting (instance type) in this case Server/Data Center.</span>
3. **Server Address**: The address of the Jira Server where Xray is running
4. Credentials:
  1. Use the **Jenkins Credentials Plugin** to set the API key/secret (please check [Global Settings - API Keys](https://getxraydocs.atlassian.net/wiki/spaces/XRAYCLOUD/pages/44568019) for more info on creating API keys)
  2. Make sure that was used to create the API key has the following permissions in the projects where you want to import the results and import/export feature files: **View, Edit, Create.**
  3. **This field is optional** - if you don't want to use a System scoped credential to authenticate in your instance, you can leave this field empty and force the users to use a User scoped credential in the build task.


Note: the Configuration ID is not editable. This value can be used in the pipeline scripts.


> ℹ️ **Please note**
> ℹ️ 
> ℹ️ The user present in this configuration must exist in the Jira instance and have permission to Create Test and Test Execution Issues

![image](media://5d32617e-feae-416b-b4a3-1934fd8f9bd0)

# Creating a new Project

The project is where the work that should be performed by Jenkins is configured.

For this app, you can configure:

- Freestyle projects
- Maven Projects
- Multi-configuration Projects
- Pipeline Projects

On the home page, click for example New Item > Freestyle project, provide a name, and then click OK.

![image](media://69ee4672-9af2-4d12-8f94-7eaaaa2c6895)

# Build Steps

Build steps are the building blocks of the build process. These need to be defined in the project configuration.

The app provides

- one build step for exporting Cucumber Scenario/Scenario Outlines from Jira as .feature files
- one build step for importing Cucumber Tests from existing Cucumber features into Jira.
- one post-build action which publishes the execution results back to Jira, regardless of the build process status.


> ℹ️ **Please note**
> ℹ️ 
> ℹ️ The fields of the tasks may take advantage of the Jenkins Environment variables, which can be used to populate fields such as the "Revision" for specifying the source code's revision. For more information, please see [Jenkins set environment variables](https://wiki.jenkins-ci.org/display/JENKINS/Building+a+software+project#Buildingasoftwareproject-belowJenkinsSetEnvironmentVariables).

## Xray: Cucumber Features Export Task

This build step will export the Cucumber Tests (i.e., Scenario/Scenario Outlines) in .feature or bundled in a .zip file. The rules for exporting are defined [here](https://getxraydocs.atlassian.net/wiki/spaces/XRAY/pages/301406470).

It invokes Xray's Export Cucumber Tests REST API endpoint (see more information [here](https://getxraydocs.atlassian.net/wiki/spaces/XRAY/pages/301667739)).

### Configuration

Some fields need to be configured in order to export the Cucumber Tests. As input, you can either specify issue keys (see the endpoint documentation [here](https://getxraydocs.atlassian.net/wiki/spaces/XRAY/pages/301667739)) or the ID of the saved filter in Jira.

| **field** | **description** |
| --- | --- |
| Jira instance | The Jira instance where Xray is running |
| Credentials | If the above Jira Instance does not have any credential configured, you must define a User scoped credential here |
| Issue keys | Set of issue keys separated by ";" |
| Filter ID | A number that indicates the filter ID |
| File path | The relative path of the directory where the features should be exported to; normally, this corresponds to the "features" folder of the Cucumber project that has the implementation steps. Note: The directory will be created if it does not exist. |

## Xray: Cucumber Features Import Task

This build step will import existing cucumber Tests from existing Cucumber feature files into Xray issues. This Task will import from .feature files and also from .zip files.

It invokes Xray's Import Cucumber Tests REST API endpoint (see more information [here](https://getxraydocs.atlassian.net/wiki/spaces/XRAY/pages/301667739))

| **field** | **description** |
| --- | --- |
| JIRA instance | The Jira instance where Xray is running. |
| Credentials | If the above Jira Instance does not have any credential configured, you must define a User scoped credential here |
| Project Key | This is the project where the Tests and Pre-Conditions will be created/updated. |
| Cucumber feature files directory | This is the directory containing your feature files. All the files in this directory and sub directories will be imported. Supports both *relative* and *absolute* paths. |
| Modified in the last hours | By entering an integer  *n*  here, only files that were modified in the last  *n*  hours will be imported.    
Leave empty if you do not want to use this parameter. |


## Xray: Results Import Task

The app provides easy access to Xray's Import Execution Results REST API endpoints (see more information [here](https://getxraydocs.atlassian.net/wiki/spaces/XRAY/pages/301667997)). Therefore, it mimics the endpoints' input parameters.

It supports importing results in Xray's own JSON format, Cucumber, Behave, JUnit, and NUnit, among others.

Using a glob expression, you can import multiple results files in the following formats:

- JUnit
- TestNG
- NUnit
- Robot framework

For those formats, the file path needs to be relative to the workspace.

### Configuration

| **field** | **description** |
| --- | --- |
| Jira instance | The Jira instance where Xray is running |
| Credentials | If the above Jira Instance does not have any credential configured, you must define a User scoped credential here |
| Format | A list of test result formats and their specific endpoint |
| Execution Report File | The results' relative or absolute file path<br>Note: glob expressions are supported for<br>- JUnit
- JUnit Multipart
- TestNG
- TestNG Multipart
- NUnit
- NUnit Multipart
- Robot framework
- Robot framework Multipart |

### Additional fields

Depending on the chosen test result format and endpoint, some additional fields may need to be configured.

| **Format and specific endpoint** | **Field** | **Description** |
| --- | --- | --- |
| Behave JSON multipart<br>Cucumber JSON multipart<br>NUnit XML multipart<br>JUnit XML multipart<br>Robot XML multipart<br>TestNG XML multipart | Import to Same Test Execution | When this option is checked, if you are importing multiple execution report files using a glob expression, the results will be imported to the same Test Execution |
| Test execution fields | An object (JSON) specifying the fields for the issue. You may specify the object either directly in the field or in the file path.<br>> ℹ️ **Learn more**
> ℹ️ 
> ℹ️ The custom field IDs can be obtained using the Jira REST API Browser tool included in Jira. Each ID is of the form "**customfield_ID**".
> ℹ️ 
> ℹ️ Another option, which does not require Jira administration rights, is to invoke the "Get edit issue meta" in an existing issue (e.g., in a Test issue) as mentioned [here](https://docs.atlassian.com/jira/REST/server/#api/2/issue-getEditIssueMeta).
> ℹ️ 
> ℹ️ Example: **GET **** ****http://yourserver/rest/api/2/issue/CALC-1/editmeta**** **** ** |
| Import in parallel | If there are several result files, when this checkbox is selected, we will import all the files in parallel (using all available CPU cores) |
| NUnit XML<br>JUnit XML<br>Robot XML<br>TestNG XML | Import to Same Test Execution | When this option is checked, if you are importing multiple execution report files using a glob expression, the results will be imported to the same Test Execution |
| Project key | Key of the project where the Test Execution (if the **Test**  ** Execution Key**  field wasn't provided) and the Tests (if they aren't created yet) are going to be created |
| Test execution key | Key of the Test Execution |
| Test plan key | Key of the Test Plan |
| Test environments | List of Test Environments separated by ";" |
| Revision | Source code's revision being targeted by the Test Execution |
| Fix version | The Fix Version to associate with the test execution (it supports only one value) |
| Import in parallel | If there are several result files, when this checkbox is selected, we will import all the files in parallel (using all available CPU cores) |

## Xray: Build Environment Variables

Since version 2.2.0, the Xray plugin will now set some build environment variables according to the operation result after each of the Xray Steps mentioned above.


| **Build Environment Variable Name** | **Meaning and Value** |
| --- | --- |
| XRAY_IS_REQUEST_SUCCESSFUL | Contains the string 'true' if all requests made by the step were successful, or 'false' otherwise. |
| XRAY_ISSUES_MODIFIED | All Issue keys that were modified and/or created by the step, separated by ';' with no duplicated entries (E.g. 'CALC-100;CALC-101;CALC-102'). |
| XRAY_RAW_RESPONSE | The unprocessed JSON response of all requests made by the step, separated by ';'. |
| XRAY_TEST_EXECS | All Test Execution Issue keys that were modified and/or created by the step, separated by ';' with no duplicated entries (E.g. 'CALC-200;CALC-201;CALC-202').<br>Please note that in some cases, it will be not possible to determine the issue type of the Issue key returned in the request response and in that case, the key it will only be added to the *XRAY_ISSUES_MODIFIED* variable. |
| XRAY_TEST | All Test Issue keys that were modified and/or created by the step, separated by ';' with no duplicated entries (E.g. 'CALC-300;CALC-301;CALC-302').<br>Please note that in some cases, it will be not possible to determine the issue type of the Issue key returned in the request response and in that case, the key it will only be added to the *XRAY_ISSUES_MODIFIED* variable. |

> ℹ️ **Pipeline Project Limitations**
> ℹ️ 
> ℹ️ Due to Jenkins limitations, these variables will not be set on Pipeline projects.

![image](media://7a253408-6d0a-4dc9-93bd-63468e7c4842)

#   
Examples

## Cucumber

In a typical Cucumber Workflow, after having created a Cucumber project and the Cucumber tests specified in Jira, you may want to have a project that **exports** the features from Jira, executes the automated tests on a CI environment and then **imports** back its results.

For this scenario, the Jenkins project would be configured with a set of tasks responsible for:

1. Pulling the Cucumber project
2. **Exporting Cucumber features from Jira to your Cucumber project**
3. Executing the tests in the CI environment
4. **Importing the execution results back to Jira**

### Exporting Cucumber features

To start the configuration, add the build step* Xray: Cucumber Features Export Task.*

![image](media://ce738122-8099-427c-ab46-53845859571b)

After that, configure it.

In this example, we configured the task to extract the *features* from a set of issues (PROJ-78 and PROJ-79) to the folder that holds the Cucumber project.

![image](media://70530ca7-a978-4987-9cd2-338831d99caa)

### Importing Cucumber features

To start the configuration, add the build step* Xray: Cucumber Features Import Task.*

![image](media://d3748a57-274e-4f0d-adbe-4ff0ece436df)

After that, configure it.

In this example, we configured the task to import to the Project IF of the Xray instance all the .features and .zip files that are contained in \Cucumber directory and subdirectories, which were modified in the last 3 hours.

![image](media://85dd4537-2cf8-4f9e-b018-9b0123ff0a96)


### Importing the execution results

To start the configuration, add the post-build action* Xray: Results Import* *Task*.

![image](media://b9828221-19f4-4fab-b7fb-6d19ba81ff71)

After that, configure it.

In this example, we configured the task to import the **Cucumber JSON** results back to Jira.

![image](media://43cc4a66-38ff-4aec-930c-32a39c3f221c)

Once all configurations are done, click Save at the bottom of the page.

After running the job, the expected result is a new Test Execution issue created in the Jira instance.

![image](media://a31e57e2-9210-40f2-b368-6b68588d645c)

### Importing the execution results with user-defined field values

For Cucumber, Behave, JUnit, Nunit and Robot, Xray for Jenkins allows you to create new Test Executions and have control over newly-created Test Execution fields. You can send two files, the normal execution result file and a JSON file similar to the one Jira uses to create new issues. More details regarding how Jira creates new issues [here](https://developer.atlassian.com/jiradev/jira-apis/about-the-jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-create-issue).

For this scenario and example, the import task needs to be configured with the **Cucumber JSON Multipart** format. When selecting this option, you can additionally configure the *Test Execution fields* in one of two ways:

- Insert the relative **path** to the JSON file containing the information, or
- Insert the **JSON content** directly in the field.

In this example, we configured the following object:

```javascript
{
   "fields": {
      "project": {
         "key": "PROJ"
      },
      "summary": "Test Execution for Cucumber results (Generated by job: ${BUILD_TAG})",
      "issuetype": {
         "id": "10102"
      }
   }
}
```


And configured the task to import the **Cucumber JSON Multipart** results back to Jira.

![image](media://5956c7cb-a126-4ba9-a10e-ae0ca2ec947a)

Once all configurations are done, click Save at the bottom of the page.

After running the job, the expected result is a new Test Execution issue created in the Jira instance, with the Test Execution fields as specified in the Jenkins build step configuration.

![image](media://0a1088ed-794a-4683-aea0-f59c085e2396)

## JUnit

Apart from supporting Cucumber natively, Xray enables you to take advantage of many other testing frameworks like JUnit. In this sense, Xray for Jenkins lets you import results in other formats besides Cucumber JSON.

If you want to import **JUnit XML reports,** a typical Job outline would be:

1. Pulling the JUnit project
2. Executing the tests in the CI environment
3. **Importing the execution results, including Tests, to JIRA**

### Importing the execution results

To start the configuration, add the post-build action* Xray: Results Import* *Task*.

![image](media://b9828221-19f4-4fab-b7fb-6d19ba81ff71)

After that, configure it.

In this example, we have a configuration where the **JUnit XML** format is chosen.

![image](media://5f074626-f121-4833-aacb-cfc8bd7937c4)

After running the plan, the expected result is a new Test Execution issue created in the JIRA instance.

![image](media://5fb833a3-c45c-4f49-b829-7538698a90e4)

You can also import multiple results using a glob expression, like in the following example

![image](media://e7df4e30-5349-4cd0-843d-11e44d1c2b38)

# Pipeline projects support

Xray for Jenkins provides support for pipeline projects, allowing you to use Xray-specific tasks.

![image](media://64552e77-a452-4871-9236-32935e08eebd)


There are 3 available steps to be used in a Pipeline project:

- `
      ``XrayImportBuilder`` ` ** **`-`** ** Import test results (Junit, NUnit, etc...) from your Jenkins job to Jira
- ** **`XrayExportBuilder`** ** ` ` ** **`-`** ** Export feature files from Jira to your Jenkins job workspace
- `
      ``XrayImportFeatureBuilder`` ` ** **`-`** ** Import feature files from Jenkins to Jira


> ℹ️ **Generated syntax helper**
> ℹ️ 
> ℹ️ For each of the steps mentioned above, you can check the generated syntax reference in the official [Jenkins documentation website](https://www.jenkins.io/doc/pipeline/steps/xray-connector/#stepclass-xrayimportbuilder-xray-results-import-task).

> ⚠️ **See and try some examples by yourself**
> ⚠️ 
> ⚠️ Please see a tutorial with working [Examples using Jenkins pipeline](https://getxraydocs.atlassian.net/wiki/spaces/XRAY/pages/301473197), showcasing different scenarios, which you can download and try by yourself.

## Step: XrayImportBuilder (import test execution results)


<details>
<summary>Parameters</summary>

| **Parameter** | **Required?** | **Type** | **Description** |
| --- | --- | --- | --- |
| `serverInstance` | **Yes** | String | The ID of the Jira instance configured in the |
| `endpointName` | **Yes** | String | The result file type to be imported. Allowed Values:<br>- "" (Xray Json format)
- "/multipart" (Xray JSON multipart format)
- "/cucumber"
- "/cucumber/multipart"
- "/behave"
- "/behave/multipart"
- "/junit"
- "/junit/multipart"
- "/nunit"
- "/nunit/multipart"
- "/robot"
- "/robot/multipart"
- "/bundle" (import of zip file with several cucumber results)
- "/testng"
- "/testng/multipart"
- "/xunit"
- "/xunit/multipart"<br>Please note that not all endpoints are available for Jira Sever/Cloud. Please refer to the REST API documentation to see what is available in your instance. |
| `projectKey` | **Yes** | String | The Jira project key where you want to import your results |
| `importFilePath` | **Yes** | String | File path where the result files can be found. |
| `credentialId` | **Yes, if the Jira instance was configured without credentials in System Configuration** | String | to be used to authenticate the Jira requests |
| `testEnvironments` | No | String | Test environments to be added to the Test Execution issue, separated by ";".<br>:warning: This value will only be used if the `endpointName` is **not** multipart |
| `testPlanKey` | No | String | All Tests will be added to the given Test Plan key, if provided.<br>:warning: This value will only be used if the `endpointName` is **not** multipart |
| `fixVersion` | No | String | Fix version to be added to the Test Execution issue.<br>:warning: This value will only be used if the `endpointName` is **not** multipart |
| `testExecKey` | No | String | Key of the test Execution issue to be updated. Leave empty to create a new issue with the import.<br>:warning: This value will only be used if the `endpointName` is **not** multipart |
| `revision` | No | String | Source code and documentation version used in the test execution.<br>:warning: This value will only be used if the `endpointName` is **not** multipart |
| `importInfo` | **Yes, if multipart endpoint** | String | File path to the Test Execution info file **OR** JSON String with the info. |
| `inputInfoSwitcher` | **Yes, if **`importInfo`** is being used** | String | Allowed values:<br>- "filePath" - if `importInfo` field is used and represents a file path
- "fileContent" - if `importInfo` field is used and represents a JSON text |
| `testImportInfo` | No | String | File path to the Test info file. |
| `inputTestInfoSwitcher` | **Yes, if **`testImportInfo`** is being used** | String | Allowed values:<br>- "filePath" - if `testImportInfo` field is used and represents a file path
- "fileContent" - if `testImportInfo` field is used and represents a JSON text |
| `importToSameExecution` | No | String | Allowed values:<br>- "true" - to import all created tests and linked them to a single Test Execution issue
- "" - link a Test Execution issue to every imported Test issue |
| `importInParallel` | No | String | Allowed values:<br>- "true" - to import all result files (if there are multiple) in parallel, in order to speed up the import process
- "" - to import all result files (if there are multiple) sequentially |
</details>

<details>
<summary>Example: simple Junit multi-file result import</summary>

```groovy
        stage('Import results to Xray') {
            steps {
                step([$class: 'XrayImportBuilder', endpointName: '/junit', importFilePath: 'java-junit-calc/target/surefire-reports/*.xml', importToSameExecution: 'true', projectKey: 'CALC', serverInstance: 'ecc67055-c359-40cb-8b8a-a44cb9f6ca30'])
            }
        }
```
</details>

<details>
<summary>Example: xUnit result import with optional fields</summary>

```groovy
        stage('Import results to Xray') {
            steps {
                step([$class: 'XrayImportBuilder', endpointName: '/xunit', importFilePath: '/reports/*.xml', importToSameExecution: 'true', projectKey: 'CALC', serverInstance: 'ecc67055-c359-40cb-8b8a-a44cb9f6ca30', importInParallel: '', fixVersion: 'v3.0', testEnvironments: 'linux;firefox', testPlanKey: 'CALC-123', testExecKey: 'CALC-456', revision: 'commit eccc5855b', credentialId: '26dba0be-45ca-4ffd-b959-13dbd241aa82'])
            }
        }
```
</details>

<details>
<summary>Example: Nunit multipart result import</summary>

```groovy
        stage('Import results to Xray (multipart)') {
            steps {
                step([$class: 'XrayImportBuilder', endpointName: '/nunit/multipart', importFilePath: '/reports/*.xml', importToSameExecution: 'true', projectKey: 'CALC', serverInstance: 'ecc67055-c359-40cb-8b8a-a44cb9f6ca30', importInParallel: 'true', importInfo: '/info/my-test-exec-info.json', inputInfoSwitcher: 'filePath' ])
            }
        }
```

> ℹ️ `importInfo` must comply with the same format as the Jira issue [create/update REST API format](https://docs.atlassian.com/software/jira/docs/api/REST/7.4.1/#api/2/issue-createIssue)
</details>

<details>
<summary>Example: Nunit multipart result import with Test info and using environment variables</summary>

```groovy
        stage('Import results to Xray (multipart)') {
            steps {
                step([$class: 'XrayImportBuilder', endpointName: '/nunit/multipart', importFilePath: '/reports/*.xml', importToSameExecution: 'true', projectKey: 'CALC', serverInstance: 'ecc67055-c359-40cb-8b8a-a44cb9f6ca30', importInParallel: 'true', importInfo: '/info/my-test-exec-info.json', inputInfoSwitcher: 'filePath', inputTestInfoSwitcher: 'fileContent', testImportInfo: '''{
           "fields": {
              "project": {
                 "key": "CALC"
              },
              "summary": "Test Execution for java junit ${BUILD_NUMBER}",
              "issuetype": {
                 "id": "9"
              },
              "customfield_11807": [
                 "CALC-1200"
              ]
           }
        }'''])
            }
        }
```

> ℹ️ `importInfo` and `testImportInfo` must comply with the same format as the Jira issue [create/update REST API format](https://docs.atlassian.com/software/jira/docs/api/REST/7.4.1/#api/2/issue-createIssue)
</details>

## Step: XrayExportBuilder (export cucumber features from Jira to Jenkins)


<details>
<summary>Parameters</summary>

| **Parameter** | **Required?** | **Type** | **Description** |
| --- | --- | --- | --- |
| `serverInstance` | **Yes** | String | The ID of the Jira instance configured in the |
| `issues` | **Yes**<br>(not required if `filter` is used) | String | Xray Tests/Test Plans/Test Sets/Test Execution issue keys, seperated by ';'. |
| `filter` | **Yes**<br>(not required if `issues` is used) | String | The Jira filter ID containing Xray Tests/Test Plans/Test Sets/Test Execution issues |
| `filePath` | No | String | The default value is "/features"<br>File path where the feature files will be downloaded |
| `credentialId` | **Yes, if the Jira instance was configured without credentials in System Configuration** | String | to be used to authenticate the Jira requests |
</details>

<details>
<summary>Example: Export features from filter to default folder</summary>

```groovy
        stage('Export feature files') {
            step([$class: 'XrayExportBuilder', filter: '12345', serverInstance: 'ecc67055-c359-40cb-8b8a-a44cb9f6ca30'])
        }
```
</details>

<details>
<summary>Example: Export features from issues to custom folder (with user's credentials)</summary>

```groovy
        stage('Export feature files') {
            step([$class: 'XrayExportBuilder', issues: 'CALC-123;CALC-234;CALC-345', serverInstance: 'ecc67055-c359-40cb-8b8a-a44cb9f6ca30', credentialId: '26dba0be-45ca-4ffd-b959-13dbd2410a82', filePath: 'my/feature/folder'])
        }
```
</details>

<details>
<summary>Example: Export features using variables</summary>

```groovy
        stage('Export feature files') {
            step([$class: 'XrayExportBuilder', issues: '${MY_ISSUE_KEYS}', filter: '${MY_FILTER_ID}', filePath: '${MY_FILE_PATH}', serverInstance: 'ecc67055-c359-40cb-8b8a-a44cb9f6ca30', credentialId: '26dba0be-45ca-4ffd-b959-13dbd2410a82'])
        }
```
</details>

## Step: XrayImportFeatureBuilder (import cucumber features from Jenkins to Jira)


<details>
<summary>Parameters</summary>

| **Parameter** | **Required?** | **Type** | **Description** |
| --- | --- | --- | --- |
| `serverInstance` | **Yes** | String | The ID of the Jira instance configured in the |
| `folderPath` | **Yes** | String | This is the directory containing your feature files. All the files in this directory and sub directories will be imported. |
| `credentialId` | **Yes, if the Jira instance was configured without credentials in System Configuration** | String | to be used to authenticate the Jira requests |
| `projectKey` | **Yes** | String | This is the project where the Tests and Pre-Conditions will be created/updated. |
| `testInfo` | No | String | File path to the Test info file that will be used to create the new Test issues. |
| `preconditions` | No | String | File path to the Preconditions info file that will be used to create the new Precondition issues. |
| `lastModified` | No | String | By entering an integer *n* here, only files that where modified in the last *n* hours will be imported.   
Leave empty if you do not want to use this parameter. |
</details>

<details>
<summary>Example: Import features modified in the last day</summary>

```groovy
        stage('Export feature files') {
            step([$class: 'XrayImportFeatureBuilder', folderPath: '/my/feature/folder', lastModified: '24', projectKey: 'CALC', serverInstance: 'ecc67055-c359-40cb-8b8a-a44cb9f6ca30'])
        }
```
</details>

<details>
<summary>Example: Import features with test info and preconditions info</summary>

```groovy
        stage('Export feature files') {
            step([$class: 'XrayImportFeatureBuilder', credentialId: 'f5522808-5cfa-4cd4-8972-8059f80cb3ed', folderPath: '/my/feature/folder', preconditions: '/path/to/precond/precondinfo.json', projectKey: 'CALC', serverInstance: 'ecc67055-c359-40cb-8b8a-a44cb9f6ca30', testInfo: '/path/to/testInfo/tesinfo.json'])
        }
```
</details>





> ℹ️ **Learn more**
> ℹ️ 
> ℹ️ For Pipeline specific documentation, you may want to give a look at:
> ℹ️ 
> ℹ️ - [https://jenkins.io/doc/book/pipeline/](https://jenkins.io/doc/book/pipeline/)
> ℹ️ - [https://jenkins.io/doc/book/pipeline/syntax/#declarative-pipeline](https://jenkins.io/doc/book/pipeline/syntax/#declarative-pipeline)
> ℹ️ - [https://github.com/jenkinsci/pipeline-plugin/blob/master/TUTORIAL.md](https://github.com/jenkinsci/pipeline-plugin/blob/master/TUTORIAL.md)


## Cucumber Workflow suggestions

### Cucumber ("standard" workflow)

This is a declarative example, for Cucumber tests using the "standard" workflow (see [Testing in BDD with Gherkin based frameworks (e.g. Cucumber)](https://getxraydocs.atlassian.net/wiki/spaces/XRAY/pages/301470422)).

##### **Jenkinsfile example (declarative)**

```groovy
pipeline {
    agent any
    stages {
        stage('Export features from Xray'){
            steps {
                checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'a3285253-a867-4ea7-a843-da349fd36490', url: 'ssh://git@localhost/home/git/repos/automation-samples.git']]])
                step([$class: 'XrayExportBuilder', filePath: 'cucumber_xray_tests/features', filter: '11400', serverInstance: '552d0cb6-6f8d-48ba-bbad-50e94f39b722'])
            }
        }
        
        stage('Test'){
            steps{
                sh "cd cucumber_xray_tests && cucumber -x -f json -o data.json"
            }
        }
        
        stage('Import results to Xray') {
            steps {
                step([$class: 'XrayImportBuilder', endpointName: '/cucumber', importFilePath: 'cucumber_xray_tests/data.json', serverInstance: '552d0cb6-6f8d-48ba-bbad-50e94f39b722'])
            }
        }
    }
}
```

### Cucumber ("VCS/Git based" workflow)

This is a declarative example, for Cucumber tests using the "VCS/Git based" workflow (see [Testing in BDD with Gherkin based frameworks (e.g. Cucumber)](https://getxraydocs.atlassian.net/wiki/spaces/XRAY/pages/301470422)).

##### **Jenkinsfile example (declarative)**

```groovy
pipeline {
    agent any
    stages {
         stage('Synch (update) recent tests to Xray'){
            steps {
                checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'a3285253-a867-4ea7-a843-da349fd36490', url: 'ssh://git@localhost/home/git/repos/automation-samples.git']]])
                step([$class: 'XrayImportFeatureBuilder', folderPath: 'cucumber_xray_tests/features', lastModified: '10', projectKey: 'CALC', serverInstance: '552d0cb6-6f8d-48ba-bbad-50e94f39b722'])
            }
        }
        
        stage('Export features from Xray'){
            steps {
                checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'a3285253-a867-4ea7-a843-da349fd36490', url: 'ssh://git@localhost/home/git/repos/automation-samples.git']]])
                sh "rm -rf cucumber_xray_tests/features"
                step([$class: 'XrayExportBuilder', filePath: 'cucumber_xray_tests/features', filter: '11400', serverInstance: '552d0cb6-6f8d-48ba-bbad-50e94f39b722'])
            }
        }
        
        stage('Test'){
            steps{
                sh "cd cucumber_xray_tests && cucumber -x -f json -o data.json"
            }
        }
        
        stage('Import results to Xray') {
            steps {
                step([$class: 'XrayImportBuilder', endpointName: '/cucumber', importFilePath: 'cucumber_xray_tests/data.json', serverInstance: '552d0cb6-6f8d-48ba-bbad-50e94f39b722'])
            }
        }
    }
}
```

## Using parameters

You can ask for human input in your pipeline builds by passing parameters

##### **Parameters usage**

```groovy
pipeline{
    agent any
    parameters {
        string(defaultValue: "NTP", description: '', name: 'projectKey')
        string(defaultValue: "Android", description: '', name: 'env')
    }
    stages {
        stage ('Import Results') {
            steps {
                step([$class: 'XrayImportBuilder', 
                endpointName: '/junit', 
                importFilePath: 'java-junit-calc/target/surefire-reports/*.xml', 
                importToSameExecution: 'true', 
                projectKey: params.projectKey,
                revision: params.projectKey + env.BUILD_NUMBER,
                serverInstance: '552d0cb6-6f8d-48ba-bbad-50e94f39b722',
                testEnvironments: params.env])
            }
            
        }
    }
}
```


## Recommendations

You can automatically generate your step scripts using the <span style="color: #003366">Jenkins Snippet Generator.</span>

![image](media://9a85c618-76f5-4db7-ae9a-a160774e3676)

![image](media://00cc70e2-bdc3-44de-8bde-8f8784f994cb)

This is the simplest way to generate your step script, and we strongly recommend the use of this snippet due to the complexity of some task related parameters.

# Jira instances configuration via Groovy script (Jenkins Script Console)

If you use a containerized version of Jenkins, or simply want to avoid creating the Jira configurations manually (using the Jenkins UI), you can use the following script in the *Jenkins Script Console*.

To use the script below, you just need to modify the contents of the *instances* and *deleteOldInstances* variables.

##### **Create new Jira instances in Xray global configuration**

```groovy
import jenkins.model.Jenkins
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import com.xpandit.plugins.xrayjenkins.model.HostingType
import com.xpandit.plugins.xrayjenkins.model.XrayInstance
import com.xpandit.plugins.xrayjenkins.model.ServerConfiguration

// true, if you want the old Jira instances removed, false otherwise.
boolean deleteOldInstances = false

/* Represents the Jira instances to be added to the Global Jenkins configuration.
 * - name: the name of the Jira instance to be displayed to the users.
 * - hostingType: must be one of two values. 'SERVER' for Server or Data Center instances OR 'CLOUD' for cloud instances.
 * - url: [ONLY FOR SERVER INSTANCES] the base URL/IP of the Jira server address.
 * - credentialId: [OPTIONAL] the credential ID from the 'Credentials' plugin that will be used to authenticate the jira REST API requests.
 */
JSONArray instances = [
        [
                name: 'my Jira server',
                hostingType: 'SERVER',
                url: 'http://example.com',
                credentialId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // Credential ID from the 'Credentials' plugin.
        ],
        [
                name: 'my Jira cloud',
                hostingType: 'CLOUD',
                credentialId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // Credential ID from the 'Credentials' plugin.
        ]
] as JSONArray

// ~~~ Saves the new Jira instances into the Jenkins global configuration ~~~
ServerConfiguration config = ServerConfiguration.get()
List<XrayInstance> xrayInstances = new ArrayList<XrayInstance>()

instances.each {instance ->
    String name = instance.optString('name', '')
    String hostingTypeString = instance.optString('hostingType', '')
    String url = instance.optString('url', '')
    String credentialId = instance.optString('credentialId', null)

    HostingType hostingType = hostingTypeString == 'CLOUD' ? HostingType.CLOUD : HostingType.SERVER

    xrayInstances.add(new XrayInstance(null, name, hostingType, url, credentialId))
}

List<XrayInstance> oldXrayInstances = config.getServerInstances()
if (!deleteOldInstances && oldXrayInstances != null) {
    xrayInstances.addAll(oldXrayInstances)
}

config.setServerInstances(xrayInstances)
config.save()

println('Xray Jira Instances created :)')
```

# Troubleshooting

## *The build process is failing with status code ****403**** *

When you check the log, it has the following:

![image](media://a531dea6-3ed1-4bb4-9d60-c22f0c71cbe8)

By default, when you s<span style="color: #212121">uccessively </span>try to log into Jira with the wrong credentials, the Jira instance will prompt you to provide a CAPTCHA the next time you try to log in. It is not possible to provide this information via the build process, so it will fail with status code **403 Forbidden**.

You will need to log into Jira via the browser and provide the CAPTCHA.

![image](media://730795ea-5a2e-4ac9-926e-5c227afe700f)

If you are a Jira administrator, you can go to Jira administration > User Management and reset the failed login.

![image](media://23be8442-77be-413e-9ed9-d31e2df72b01)

## *The Jira xxx configuration of this task was not found*

If you obtain this error, probably you have migrated from an old version of this plugin. You need to open each project/job configuration and save it.

![image](media://a859b183-2531-4ec7-91a1-48b46a3f2e14)