Scripting Examples

Practical recipes and patterns for common automation tasks.

Guide Description
Bulk operations Mass issue updates, transitions, and field changes
Reporting Data aggregation, statistics, and summaries
Field sync Synchronizing fields between issues
Table operations CRUD patterns with custom tables
Queue patterns Message queue workflows and processing
Automation recipes Common automation trigger scripts

Where to start:

Conventions - all examples use these conventions:

  • // => value - shows the output of a log() call
  • // result: value - shows the script’s return value
  • Examples are self-contained and can be pasted directly into the Console
  • PROJ-123 is used as a placeholder issue key - replace with your own

For one-shot changes without code - copy, update, transition, label, resolve or delete issues by JQL - see the built-in Recipes.


Bulk operations

Recipes for mass issue updates, transitions, and field changes.

Simple bulk operations (Console scripts)

Update all issues in a project

const result = await Issues.search('project = PROJ AND status = Open')
const report = await result.updateAll({ priority: 'Medium' })

return `Updated ${report.success} issues, ${report.failed} failed`

Add a comment to multiple issues

const keys = ['PROJ-1', 'PROJ-2', 'PROJ-3']

for (const key of keys) {
  await Issues.get(key).addComment('Reviewed and approved.')
  log(`Commented on ${key}`)
}

return `Commented on ${keys.length} issues`

Transition issues by JQL

Move issues matching a query to a target status.

const result = await Issues.search('project = PROJ AND status = "To Do" AND created < -30d')
const report = await result.transitionAll('In Progress')

return `Transitioned ${report.success}/${report.success + report.failed}`

Bulk assign issues

const user = await Users.current()
const result = await Issues.search('project = PROJ AND assignee is EMPTY AND status = Open')
const report = await result.forEach(async (issue) => {
  await issue.assign(user.accountId)
})

return `Assigned ${report.success} issues to ${user.displayName}`

Scenario batch operations (large scale)

For processing thousands of issues, use batch() in scenarios. Each page of results runs as a separate invocation with automatic pagination, progress tracking, and error handling.

Batch by JQL (string shorthand)

step('count', () => {
  return { total: Issues.count('project = PROJ') }
})

batch('cleanup', 'project = PROJ AND updated < -180d', (issue) => {
  issue.transition('Done')
})

step('report', (ctx) => {
  log(`Done: ${ctx.cleanup.processed}/${ctx.count.total}, ${ctx.cleanup.failed} errors`)
})

Batch with config object

Use a config object to specify fields, expand, and batch options:

batch('export', {
  jql: 'project = PROJ',
  fields: ['summary', 'status', 'priority'],
  expand: ['changelog'],
  batchSize: 50,
  maxIssues: 10000,
  continueOnError: true,
}, (issue) => {
  log(issue.key + ': ' + issue.summary)
})
// Result: { processed: 4523, failed: 12, errors: [...], totalPages: 46 }

Batch by issue keys

batch('update', {
  keys: ['PROJ-1', 'PROJ-2', 'PROJ-3'],
  fields: ['summary', 'status'],
}, (issue) => {
  issue.addLabel('reviewed')
})

Batch from previous step

step('find', () => {
  var result = Issues.search('project = PROJ AND priority = High')
  return { keys: result.map(i => i.key) }
})

batch('process', {
  source: ctx => ctx.find.keys,
  batchSize: 50,
}, (issue) => {
  issue.addComment('High priority review')
})

Config object properties

Property Type Description
jql string JQL query (one of jql/keys/source required)
keys string[] Array of issue keys
source (ctx) => string[] Function returning keys from ctx
fields string[] Fields to load (default: all)
expand string[] Expand options (e.g. ["changelog"])
batchSize number Issues per page (default: 100, max: 100)
maxIssues number Processing limit (default: unlimited)
continueOnError boolean Continue on failure (default: true)

Loop for custom pagination

When you need more control than batch() provides, use loop():

loop('export', (state, ctx) => {
  var result = Issues.search('project = PROJ', {
    maxResults: 100,
    nextPageToken: state.cursor,
  })
  var keys = state.keys.concat(result.map(i => i.key))

  if (result.hasMore) {
    return next({ cursor: result.nextPageToken, keys })
  }
  return { allKeys: keys }
}, { cursor: null, keys: [] })

step('report', (ctx) => {
  log(`Found ${ctx.export.allKeys.length} issues`)
})

Note: async/await in scenario callbacks is optional - API calls are auto-awaited. You can still use async/await if you prefer explicit syntax.

Note: Console scripts have API call limits per trigger type (e.g. 40 for console, 100 for scheduled, 250 for async). For large datasets, use scenario batch() or loop() which automatically split work across invocations.



Reporting

Recipes for data aggregation, statistics, and summaries.

Issue count by status

const result = await Issues.search('project = PROJ')
const counts = result.countBy('status')

log('Issue counts by status:')
for (let [status, count] of Object.entries(counts)) {
  log(`  ${status}: ${count}`)
}

return counts

Priority distribution

const result = await Issues.search('project = PROJ AND status != Done')
const dist = result.countBy('priority')

return dist
// result: { "High": 12, "Medium": 25, "Low": 8 }

Overdue issues report

const result = await Issues.search(
  'project = PROJ AND duedate < now() AND status != Done'
)
const overdue = result.filter(issue => issue.isOverdue)

log(`Found ${overdue.length} overdue issues:`)
for (const issue of overdue) {
  log(`  ${issue.key}: ${issue.summary} (due: ${issue.dueDate}, assignee: ${issue.assignee || 'Unassigned'})`)
}

return { count: overdue.length }

Sprint progress summary

const boards = await Boards.list()
const board = boards[0]

const sprints = await Boards.getSprints(board.id, 'active')
const sprint = sprints[0]

const issues = await Sprints.getIssues(sprint.id)

let done = 0
for (const issue of issues) {
  if (issue.isResolved) done++
}

return {
  sprint: sprint.name,
  total: issues.length,
  done,
  remaining: issues.length - done,
  progress: `${Math.round(done / issues.length * 100)}%`
}

Assignee workload

const result = await Issues.search('project = PROJ AND status != Done')
const workload = result.countBy('assignee')

// Sort by count descending
const sorted = Object.entries(workload).sort((a, b) => b[1] - a[1])

log('Workload:')
for (const [name, count] of sorted) {
  log(`  ${name}: ${count} issues`)
}

return Object.fromEntries(sorted)

Created vs resolved trend

const created = await Issues.count('project = PROJ AND created >= -7d')
const resolved = await Issues.count('project = PROJ AND resolved >= -7d')

return {
  period: 'Last 7 days',
  created,
  resolved,
  net: created - resolved
}

Component coverage

const project = await Projects.get('PROJ')
const components = await project.getComponents()

let results = []
for (const comp of components) {
  const count = await Issues.count(`project = PROJ AND component = "${comp.name}"`)
  results.push({ name: comp.name, count })
}

results.sort((a, b) => b.count - a.count)

log('Issues by component:')
for (const r of results) {
  log(`  ${r.name}: ${r.count}`)
}

return results

Tip: When you only need a number, use Issues.count(jql) - one API call, no issues loaded. Issues.search(jql, { includeTotal: true }) also sets total, but costs an extra call on top of the search. Both return Jira’s approximate count.



Field sync

Recipes for synchronizing fields between issues, parent/child, and linked issues.

Sync labels from parent to subtasks

const parent = await Issues.get('PROJ-100')
const subtasks = await Issues.search(`parent = ${parent.key}`)

const report = await subtasks.forEach(async (sub) => {
  await sub.update({ labels: parent.labels })
  log(`Synced labels to ${sub.key}`)
})

return `Synced labels to ${report.success} subtasks`

Copy priority from epic to stories

const epic = await Issues.get('PROJ-50')
const stories = await Issues.search(`"Epic Link" = ${epic.key}`)

let updated = 0
for (const story of stories.issues) {
  if (story.priority !== epic.priority) {
    await story.update({ priority: epic.priority })
    updated++
  }
}

return `Updated priority on ${updated}/${stories.issues.length} stories`

Sync due date from parent

const parent = await Issues.get(issue.key)
if (!parent.dueDate) {
  return 'Parent has no due date'
}

const children = await Issues.search(`parent = ${issue.key}`)
const report = await children.forEach(async (child) => {
  if (!child.dueDate) {
    await child.update({ duedate: parent.dueDate })
    log(`Set due date on ${child.key}`)
  }
})

Mirror fix version to linked issues

const source = await Issues.get('PROJ-100')
if (source.fixVersions.length === 0) {
  return 'No fix versions to sync'
}

let synced = 0
for (const link of source.links) {
  await Issues.get(link.key).update({ fixVersions: source.fixVersions })
  synced++
}

return `Synced fix versions to ${synced} linked issues`

Propagate component from parent

Useful as a scheduled or event trigger script.

const issues = await Issues.search(
  'project = PROJ AND issuetype = Story AND component is EMPTY AND parent is not EMPTY'
)

let updated = 0
for (const story of issues.issues) {
  if (story.parent) {
    const parent = await Issues.get(story.parent)
    if (parent.components.length > 0) {
      await story.update({ components: parent.components })
      updated++
    }
  }
}

return `Updated components on ${updated} stories`

Sync custom field across project

Copy a custom field value from one issue to all related issues.

const source = await Issues.get('PROJ-100')
const value = await source.field('Story Points')

const targets = await Issues.search(
  'project = PROJ AND "Epic Link" = PROJ-100 AND "Story Points" is EMPTY'
)
const report = await targets.forEach(async (target) => {
  await target.update({ 'Story Points': value })
})

return `Synced Story Points to ${report.success} issues`


Table operations

Recipes for working with custom tables - CRUD, filtering, aggregation, and data management. The tables API is accessed via the tables variable (lowercase).

Basic CRUD

Add a row

await tables.addRow('inventory', {
  name: 'Widget A',
  quantity: 100,
  category: 'hardware'
})

Find and update

// findRow / count / deleteRows take the filter object directly (no `where` wrapper)
let row = await tables.findRow('inventory', { name: { $eq: 'Widget A' } })

if (row) {
  await tables.updateRow('inventory', row.id, {
    quantity: row.data.quantity - 10
  })
  log(`Updated quantity to ${row.data.quantity - 10}`)
}

Upsert pattern

tables.upsert(name, where, data) inserts the row when no row matches where, otherwise updates it:

const upserted = await tables.upsert('inventory',
  { name: 'Widget A' },
  { name: 'Widget A', quantity: 100, category: 'hardware' }
)
log(upserted._action)  // "created" or "updated"

Delete by condition

let deleted = await tables.deleteRows('inventory', { quantity: { $eq: 0 } })

return `Deleted ${deleted} empty rows`

Filtering and sorting

Search with multiple conditions

// tables.rows takes options ({ where, orderBy, limit, offset })
// and returns { rows, total }
let result = await tables.rows('inventory', {
  where: {
    category: { $eq: 'hardware' },
    quantity: { $gt: 0 }
  },
  orderBy: '-quantity',   // "-" prefix = descending
  limit: 10
})

for (let row of result.rows) {
  log(`${row.data.name}: ${row.data.quantity}`)
}

Aggregate data

// Without `limit` a page holds 50 rows; the maximum is 200
let result = await tables.rows('sales', {
  where: { status: { $eq: 'completed' } },
  limit: 200
})

let total = 0
for (let row of result.rows) {
  total += row.data.amount || 0
}

return { totalSales: total, count: result.rows.length, matching: result.total }

Sync Jira data to a table

Export issue data to table

let issues = await Jira.search('project = PROJ AND status = Done AND resolved >= -7d', {
  fields: ['summary', 'assignee', 'resolutiondate']
})

let data = issues.issues.map(i => ({
  issueKey: i.key,
  summary: i.fields.summary,
  assignee: i.fields.assignee?.displayName || 'None',
  resolved: i.fields.resolutiondate
}))

await tables.addRows('resolved-report', data)

return `Exported ${data.length} issues to table`

Lookup table for configuration

// Use a table as a config store
let config = await tables.findRow('config', { key: { $eq: 'notification-emails' } })

if (config) {
  let emails = JSON.parse(config.data.value)
  log(`Notification emails: ${emails.join(', ')}`)
}

Count and statistics

let total = await tables.count('inventory')
let lowStock = await tables.count('inventory', { quantity: { $lt: 10 } })
let outOfStock = await tables.count('inventory', { quantity: { $eq: 0 } })

return {
  total,
  lowStock,
  outOfStock,
  healthy: total - lowStock
}

Bulk insert with validation

let items = [
  { name: 'Item A', price: 10.99, active: true },
  { name: 'Item B', price: 24.50, active: true },
  { name: 'Item C', price: 5.00, active: false }
]

// Validate before insert
let valid = items.filter(item =>
  item.name && item.price > 0
)

await tables.addRows('products', valid)

return `Inserted ${valid.length}/${items.length} items`

Table as issue tracker extension

Track extra metadata not available in Jira fields.

// On issue event: save extended metadata
let issueKey = issue.key

let existing = await tables.findRow('issue-metadata', { issueKey: { $eq: issueKey } })

let metadata = {
  issueKey,
  lastReviewDate: DateUtils.format(new Date(), 'YYYY-MM-DD'),
  reviewCount: existing ? (existing.data.reviewCount || 0) + 1 : 1,
  reviewer: currentUser.displayName
}

if (existing) {
  await tables.updateRow('issue-metadata', existing.id, metadata)
} else {
  await tables.addRow('issue-metadata', metadata)
}

return metadata


Queue patterns

Recipes for message queue workflows - producer/consumer, error handling, and processing patterns.

Basic producer/consumer

Producer: push messages

let issues = await Jira.search('project = PROJ AND status = "To Do" AND created >= -1d', {
  fields: ['summary', 'created'],
  maxResults: 20,   // every push counts against the 25 queue calls per script
})

for (let issue of issues.issues) {
  await queue.push('pending-review', {
    issueKey: issue.key,
    summary: issue.fields.summary,
    created: issue.fields.created
  })
}

return `Queued ${issues.issues.length} issues for review`

Consumer: process messages

let messages = await queue.pull('pending-review', 5)

for (let msg of messages) {
  try {
    // Process the issue
    await Jira.addComment(msg.payload.issueKey, 'Auto-reviewed by script')
    await queue.ack(msg.id)
    log(`Processed ${msg.payload.issueKey}`)
  } catch (e) {
    await queue.reject(msg.id)
    warn(`Failed ${msg.payload.issueKey}: ${e.message}`)
  }
}

return `Processed ${messages.length} messages`

Priority queue

// Push with different priorities (higher = processed first)
await queue.push('notifications', { type: 'critical', text: 'Server down' }, 10)
await queue.push('notifications', { type: 'warning', text: 'High memory' }, 5)
await queue.push('notifications', { type: 'info', text: 'Deploy complete' }, 1)

// Pull returns highest priority first
let msgs = await queue.pull('notifications', 3)
for (let msg of msgs) {
  log(`[${msg.payload.type}] ${msg.payload.text}`)
}
// => [critical] Server down
// => [warning] High memory
// => [info] Deploy complete

Peek before processing

Preview messages without changing their status.

let preview = await queue.peek('work-queue', 5)

log(`Next ${preview.length} items:`)
for (let msg of preview) {
  log(`  ${msg.id}: ${JSON.stringify(msg.payload)}`)
}

// Messages remain in pending state
let stats = await queue.stats('work-queue')
log(`Queue stats: ${JSON.stringify(stats)}`)

Consume pattern (one-shot processing)

Process and immediately remove messages - no ack/reject needed.

let messages = await queue.consume('email-queue', 5)

for (let msg of messages) {
  log(`Sending email to ${msg.payload.to}: ${msg.payload.subject}`)
  // Messages are already removed from the queue
}

return `Consumed ${messages.length} messages`

Error handling with retry

Decide about a retry while you still hold the message id - peek, pull and consume only return pending messages, so a message marked failed with reject cannot be listed from a script later (queue.stats still counts it).

let messages = await queue.pull('work-queue', 5)

for (let msg of messages) {
  try {
    await Issues.addComment(msg.payload.issueKey, 'Processed')
    await queue.ack(msg.id)
  } catch (e) {
    let attempts = (msg.payload.attempts || 0) + 1
    if (attempts < 3) {
      // Put it back with an attempt counter, drop the current copy
      await queue.push('work-queue', { ...msg.payload, attempts }, msg.priority)
      await queue.ack(msg.id)
      log(`Retry ${attempts} scheduled for ${msg.payload.issueKey}`)
    } else {
      await queue.reject(msg.id)   // give up: mark as failed
      warn(`Giving up on ${msg.payload.issueKey}: ${e.message}`)
    }
  }
}

// queue.requeue(id) returns a pulled message to pending unchanged

Queue as event bus

Use queues to pass data between scripts triggered at different times.

Script 1 (event trigger - on issue create)

await queue.push('issue-events', {
  event: 'created',
  issueKey: issue.key,
  timestamp: Date.now()
})

Script 2 (scheduled - runs hourly)

let messages = await queue.consume('issue-events', 10)

let counts = { created: 0, updated: 0 }
for (let msg of messages) {
  counts[msg.payload.event] = (counts[msg.payload.event] || 0) + 1
}

// Write summary to a table
await tables.addRow('hourly-events', {
  hour: DateUtils.format(new Date(), 'YYYY-MM-DD'),
  ...counts
})

return counts

Queue size monitoring

let queues = ['work-queue', 'email-queue', 'notification-queue']
let report = []

for (let name of queues) {
  let stats = await queue.stats(name)
  let size = await queue.size(name)
  report.push({ name, size, ...stats })

  if (stats.failed > 0) {
    warn(`Queue "${name}" has ${stats.failed} failed messages`)
  }
}

return report


Automation recipes

Common script patterns for different trigger types and automation scenarios.

Scheduled scripts

Daily stale issue reminder

Runs daily. Finds issues not updated in 14 days and adds a comment.

const result = await Issues.search(
  'project = PROJ AND status != Done AND updated < -14d'
)
const report = await result.forEach(async (issue) => {
  await issue.addComment('This issue has not been updated in 14 days. Please review.')
})

return `Reminded ${report.success} stale issues`

Weekly status report to table

Runs weekly. Captures project statistics.

// Issues.count costs one API call and loads no issues
let open = await Issues.count('project = PROJ AND status != Done')
let created = await Issues.count('project = PROJ AND created >= -7d')
let resolved = await Issues.count('project = PROJ AND resolved >= -7d')

await tables.addRow('weekly-stats', {
  date: DateUtils.format(new Date(), 'YYYY-MM-DD'),
  open,
  created,
  resolved
})

return { open, created, resolved }

Event trigger scripts

Auto-assign based on component

Triggers on issue_created.

// Map components to assignees
let assignments = {
  'Frontend': '5a1234567890abcdef',
  'Backend': '5b1234567890abcdef',
  'DevOps': '5c1234567890abcdef'
}

let components = issue.components || []
if (components.length > 0) {
  let accountId = assignments[components[0]]
  if (accountId) {
    await issue.assign(accountId)
    log(`Assigned ${issue.key} to ${components[0]} owner`)
  }
}

Auto-label high priority issues

Triggers on issue_created and issue_updated.

let priority = issue.priority
let labels = issue.labels || []

if ((priority === 'Highest' || priority === 'High') && !labels.includes('urgent')) {
  await issue.addLabel('urgent')
  log(`Added 'urgent' label to ${issue.key}`)
}

Notify on issue delete

Triggers on issue_deleted. Logs deleted issue to a table.

await tables.addRow('deleted-issues', {
  issueKey: event.issue?.key || 'unknown',
  deletedAt: new Date().toISOString(),
  deletedBy: currentUser?.displayName || 'system'
})

UIM scripts (UI Modifications)

Make field required based on priority

if (uimData.callbackType === 'onInit' || uimData.changedFieldId === 'priority') {
  let priority = uimData.fieldValues?.priority?.value
  if (priority === 'Highest' || priority === 'High') {
    uim.setRequired('duedate', true)
    uim.setDescription('duedate', 'Due date is required for high priority issues')
  } else {
    uim.setRequired('duedate', false)
    uim.setDescription('duedate', '')
  }
}

Auto-fill fields on create

if (uimData.callbackType === 'onInit' && uimData.viewType === 'GIC') {
  let user = await Users.current()
  uim.setValue('reporter', { accountId: user.accountId })

  // Set default due date to 2 weeks from now
  let due = LocalDate.now().plusDays(14)
  uim.setValue('duedate', due.toString())
}

Show/hide fields dynamically

if (uimData.callbackType === 'onInit' || uimData.changedFieldId === 'issuetype') {
  let type = uimData.fieldValues?.issuetype?.value
  if (type === 'Bug') {
    uim.setVisible('environment', true)
    uim.setVisible('customfield_10100', true)  // Steps to reproduce
  } else {
    uim.setVisible('environment', false)
    uim.setVisible('customfield_10100', false)
  }
}

Scripted fields

Calculate days since created

// Scripted Text Field
let created = Date.parse(issue.created)
let days = Math.floor((Date.now() - created) / (1000 * 60 * 60 * 24))
return `${days} days`

Sum subtask story points

// Scripted Number Field
const subtasks = await Issues.search(`parent = ${issue.key}`)

let total = 0
for (const sub of subtasks.issues) {
  let sp = await sub.field('Story Points')
  total += sp || 0
}

return total

Next business day due date

// Scripted Date Field
let due = issue.dueDate
if (!due) return null

let date = LocalDate.parse(due)
let dayOfWeek = date.getDayOfWeek()

// If due on weekend, move to Monday
if (dayOfWeek === 6) date = date.plusDays(2)  // Saturday -> Monday
if (dayOfWeek === 7) date = date.plusDays(1)  // Sunday -> Monday

return date.toString()

JQL function scripts

Custom JQL functions extend Jira’s query language. Users invoke them with issue in jbExec("name", arg1, arg2) and your script returns matching issue keys, IDs, or a JQL fragment. See JQL Functions for setup.

Find blockers of a given issue

Returns every issue blocked by a source key, optionally restricted by link type.

const sourceKey = jqlFunction.args[0]
const linkType = jqlFunction.args[1] || 'blocks'

const issue = await Issues.get(sourceKey)

// Outward "blocks" links point from the source to the issues it blocks
return issue.links
  .filter(l => l.direction === 'outward' && l.type.toLowerCase() === linkType.toLowerCase())
  .map(l => l.key)

JQL: issue in jbExec("findBlockers", "PROJ-1", "blocks")

Issues whose linked epic field equals a given label

Returns numeric IDs (recommended for performance) of issues whose epic carries a specific label.

const targetLabel = jqlFunction.args[0]

const epics = await Issues.search(
  `issuetype = Epic AND labels = "${targetLabel}"`,
  { fields: ['id'] }
)
const epicKeys = epics.issues.map(e => e.key)
if (epicKeys.length === 0) return []

const children = await Issues.search(
  `"Epic Link" in (${epicKeys.map(k => `"${k}"`).join(',')})`,
  { fields: ['id'] }
)

return children.issues.map(i => Number(i.id))

JQL: issue in jbExec("issuesByEpicLabel", "Q4-roadmap")

Return a JQL fragment instead of issue list

When the matching logic can be expressed in pure JQL, return a string fragment. Forge evaluates it server-side - usually faster than fetching keys.

const minPoints = Number(jqlFunction.args[0]) || 5
return `"Story Points" >= ${minPoints} AND status != Done`

JQL: issue in jbExec("bigOpenStories", "8")



Next steps


JiBrok Studio for Jira Cloud JiBrok Studio for Jira Cloud
Release notes
Core Features
Triggers
Extensions
Data Storage
Scripting Overview
JavaScript Engine
Python Engine
Groovy Engine
Scripting API
Administration
Guides