ServiceNowの開発現場では長らくUpdate Setを手動でエクスポート/インポートする運用が一般的でしたが、公式ドキュメント(SDLC on ServiceNow Guide)ではGitをベースとした開発手法が推奨されるようになっています。
この記事では、ServiceNow SDK(v4.14.0)とTypeScript DSLである「ServiceNow Fluent」を使い、以下の2つのパターンを実装した手順をまとめました。
- 新規カスタムアプリの開発(IT資産調達申請)
- 既存標準テーブルの拡張(incidentテーブルの拡張と保存ガード)
あわせて、開発エージェント(Google Antigravity)と連携させた実機テストスクリプト(テストハーネス)の作成や、実際に動かす中で引っかかったポイントについても記録しておきます。
1. Update Set運用の課題とGit管理の背景
大規模なServiceNow環境でUpdate Setを手動移送していると、いくつか避けられない課題に直面します。
- 変更履歴の追跡が難しい: Update SetはXML形式のメタデータの集まりであり、Gitのコミットログやプルリクエストのように行単位で差分を追ったりレビューしたりすることが困難です。
- リリースの衝突と先祖返り: 複数人で同じテーブルやビジネスルールを修正した場合、環境への適用順序を誤ると最新の変更が古い設定で上書きされてしまうリスクがあります。
- デプロイ作業の属人化: 開発・テスト・本番の各環境で手動のプレビューとコミットを繰り返す必要があり、リリース作業自体の負担が大きくなります。
ServiceNowのテクニカルコンサルタントである Sascha Wildgrube 氏のホワイトペーパー『A mature Development and Deployment Process』でも指摘されている通り、Update Set依存から脱却し、ソースコードを信頼できる情報源(Single Source of Truth)としてバージョン管理することが求められています。
これを実現するために公式から提供されているのが、ServiceNow SDKとServiceNow Fluentです。メタデータをTypeScriptで記述し、Gitで差分管理を行いながら、CLI経由でインスタンスへのビルドと配備を行えます。
2. 公式ガイドにおける開発スコープの考え方
公式のSDLCガイドでは、サポートされる開発パターン(In-Scope)と推奨されないパターン(Out-of-Scope)が整理されています。
対象範囲(In-Scope)
- 新規アプリケーション(Net-new Apps): 独自の業務要件を満たす独立したカスタムスコープドアプリ。
- 標準テーブルの拡張(Table Augments): incidentなどの標準テーブルに対し、自社のスコープから安全にフィールドやロジックを追加する開発。
非推奨・対象外(Out-of-Scope)
- Update Setによる環境間移行: 環境間移送の手段としては使わず、開発環境内での一時的な作業保存にとどめる方針とされています。
- 旧Studio(Dev Studio)の利用: VS CodeやServiceNow IDEなど、ファイルベースのエディタへの移行が前提です。
- ベンダー提供アプリの直接編集(Edit-in-place): 他社製パッケージを直接書き換えるのではなく、自社スコープから拡張する形をとります。
3. 実装したシナリオ
単なるHello Worldではなく、実務でありそうなシナリオとして「PC故障インシデントに伴う代替機材の調達申請と、調達完了前の誤解決防止ガード」を作成しました。
4. 開発環境のセットアップとコード実装
ローカルPC(VS Code)からServiceNow PDI(Personal Developer Instance)に接続して開発を進めました。
環境準備
- Node.js: v24.x
- ServiceNow SDK:
@servicenow/sdk(v4.14.0) - インスタンス: ServiceNow PDI (Washington / Xanadu)
mkdir servicenow-sdlc-demo
cd servicenow-sdlc-demo
npm init -y
ServiceNow SDKは大量の型定義を展開するため、Node.jsのデフォルトメモリ上限(約1.4GB)を超えて JavaScript heap out of memory が発生することがあります。プロジェクト直下に .npmrc を配置してメモリ上限を拡張しておくと安全です。
# .npmrc
node-options="--max-old-space-size=4096"
SDKを開発用依存関係としてインストールします。
npm install --save-dev @servicenow/sdk
PDIの認証とプロジェクトの初期化
1. 接続先インスタンスの登録
CLIからインスタンスの接続情報を登録します。パスワードは標準入力から安全に渡せます。
"YOUR_PASSWORD" | npx now-sdk auth --add https://devXXXXXX.service-now.com --type basic --alias pdi --username admin --password-stdin
npx now-sdk auth --use pdi
2. Company Codeの確認と初期化
カスタムスコープ名のプレフィックスに必要なCompany Codeを確認します。
npx now-sdk query sys_properties -q "name=glide.appcreator.company.code" -f value
# 出力例: [{ "value": "XXXXXX" }]
確認したコードを使ってTypeScriptテンプレートでプロジェクトを初期化し、インスタンスから型定義を取得します。
npx now-sdk init \
--appName "SDLC Demo" \
--packageName "sdlc-demo" \
--scopeName "x_customer_sdlc" \
--auth pdi \
--template typescript.basic
npm install
npm run types
これでVS Code上でServiceNowのAPIやテーブル定義に対する型補完が有効になります。
パターンA:新規テーブル(IT資産調達申請)
調達申請テーブルを src/fluent/procurement.now.ts に定義しました。
UI上の設定として、他のテーブルから参照された際に表示されるカラムを display: 'model_name' で指定しています。また、選択肢フィールドをテキストボックスではなくドロップダウン形式で表示させるため、dropdown: 'dropdown_without_none' を指定しています。
import { Table, StringColumn, IntegerColumn, BooleanColumn, ReferenceColumn, BusinessRule, ClientScript } from '@servicenow/sdk/core'
export const x_customer_sdlc_procurement_request = Table({
name: 'x_customer_sdlc_procurement_request',
label: 'IT Asset Procurement Request',
display: 'model_name',
schema: {
requester: ReferenceColumn({
label: 'Requester',
referenceTable: 'sys_user',
mandatory: true,
}),
asset_category: StringColumn({
label: 'Asset Category',
dropdown: 'dropdown_without_none',
choices: {
laptop: 'Laptop PC',
monitor: 'External Monitor',
mobile: 'Mobile Device',
server: 'Server / Network Appliance',
},
mandatory: true,
default: 'laptop',
}),
model_name: StringColumn({
label: 'Model / Specification',
maxLength: 200,
mandatory: true,
}),
estimated_cost: IntegerColumn({
label: 'Estimated Cost (JPY)',
mandatory: true,
}),
business_justification: StringColumn({
label: 'Business Justification',
maxLength: 1000,
mandatory: true,
}),
approval_status: StringColumn({
label: 'Approval Status',
dropdown: 'dropdown_without_none',
choices: {
draft: 'Draft',
pending_dept: 'Pending Department Approval',
pending_exec: 'Pending Executive Approval',
approved: 'Approved',
rejected: 'Rejected',
fulfilled: 'Fulfilled',
},
default: 'draft',
}),
urgency: StringColumn({
label: 'Urgency',
dropdown: 'dropdown_without_none',
choices: {
low: 'Low',
normal: 'Normal',
high: 'High',
critical: 'Critical',
},
default: 'normal',
}),
requires_executive_approval: BooleanColumn({
label: 'Requires Executive Approval',
default: false,
}),
},
})
ClientScript({
$id: Now.ID['cs_procurement_on_load'],
name: 'ProcurementFormLoaded',
table: 'x_customer_sdlc_procurement_request',
active: true,
applies_extended: false,
global: true,
ui_type: 'all',
type: 'onLoad',
script: `function onLoad() {
var cost = g_form.getValue('estimated_cost');
if (cost && parseInt(cost, 10) >= 200000) {
g_form.addWarningMessage("【高額調達案件】概算費用が20万円以上のため、部門長承認に加えて役員決裁が必要となります。");
} else {
g_form.addInfoMessage("IT資産調達申請フォームへようこそ。必要事項を正確に入力してください。");
}
}`,
})
BusinessRule({
$id: Now.ID['br_procurement_check_cost'],
name: 'EvaluateExecutiveApprovalPolicy',
table: 'x_customer_sdlc_procurement_request',
action: ['insert', 'update'],
when: 'before',
order: 100,
active: true,
script: `(function executeRule(current, previous /*null when async*/) {
var cost = current.getValue('estimated_cost');
if (cost >= 200000) {
current.setValue('requires_executive_approval', true);
if (current.getValue('approval_status') == 'draft') {
current.setValue('approval_status', 'pending_exec');
}
gs.info("High-value request flagged: " + current.getValue('model_name') + " (" + cost + " JPY)");
} else {
current.setValue('requires_executive_approval', false);
}
})(current, previous);`,
})
パターンB:標準テーブル拡張(Table Augments)
既存の incident テーブルを拡張し、調達申請への参照フィールドと解決制御ロジックを追加しました(src/fluent/incident_extension.now.ts)。
保存をブロックする処理には、スクリプト内で current.setAbortAction(true) を呼び出すのではなく、ServiceNowネイティブのプロパティである abortAction: true と condition 式を組み合わせています。JavaScriptエンジンの実行を経由せずDB層の直前で安全に中断できるため、パフォーマンス面とバージョンアップ耐性の両面で有利です。
import { Table, ReferenceColumn, BusinessRule, ClientScript } from '@servicenow/sdk/core'
export const incident = Table({
augments: 'incident',
schema: {
x_customer_sdlc_procurement_ref: ReferenceColumn({
label: 'Related Procurement Request',
referenceTable: 'x_customer_sdlc_procurement_request',
}),
},
})
ClientScript({
$id: Now.ID['cs_incident_procurement_alert'],
name: 'IncidentProcurementAlert',
table: 'incident',
active: true,
applies_extended: false,
global: true,
ui_type: 'all',
type: 'onLoad',
script: `function onLoad() {
var procRef = g_form.getValue('x_customer_sdlc_procurement_ref');
if (procRef) {
g_form.addInfoMessage("【機器交換手配中】このインシデントには代替機材の調達申請が紐付けられています。手配完了までインシデント解決はお待ちください。");
}
}`,
})
BusinessRule({
$id: Now.ID['br_incident_resolve_guard'],
name: 'GuardIncidentResolutionUntilProcurementFulfilled',
table: 'incident',
action: ['insert', 'update'],
when: 'before',
order: 150,
active: true,
condition: "current.state == 6 && !current.x_customer_sdlc_procurement_ref.nil() && current.x_customer_sdlc_procurement_ref.approval_status != 'fulfilled'",
abortAction: true,
addMessage: true,
message: "【解決不可】紐付けられたIT資産調達申請の手配・納品が完了していません。調達完了後にインシデントを解決してください。",
script: `(function executeRule(current, previous /*null when async*/) {
gs.warn("[ITSM Guard] Blocked resolution of " + current.getValue('number') + " because procurement is unfulfilled.");
})(current, previous);`,
})
パターンC:ATF(自動テスト)の定義
ServiceNow Fluentでは、ATFのテストケースもコードとして管理できます(src/fluent/procurement_test.now.ts)。
import { Test } from '@servicenow/sdk/core'
export const procurement_workflow_test = Test(
{
$id: Now.ID['atf_procurement_test'],
name: 'Procurement Request Workflow Test',
description: 'Verify high-value procurement creation and incident integration',
active: true,
failOnServerError: true,
},
(atf) => {
atf.server.log({
$id: Now.ID['step_log_start'],
log: 'Starting Procurement test',
})
atf.server.recordInsert({
$id: Now.ID['step_insert_proc'],
table: 'x_customer_sdlc_procurement_request',
fieldValues: {
asset_category: 'laptop',
model_name: 'High-end Developer Workstation',
estimated_cost: 250000,
business_justification: 'Automated test for high-value procurement',
approval_status: 'draft',
},
})
atf.server.log({
$id: Now.ID['step_log_end'],
log: 'Completed Procurement record insertion step',
})
}
)
コードが書けたらローカルビルドを実行し、Gitにコミットします。
npm run build
git init
git branch -M main
git add .
git commit -m "feat: implement procurement app, incident extension, and ATF test"
ビルドを実行すると dist/app/update/ 配下にServiceNow形式のXMLメタデータが生成されます。
5. デプロイと実機確認
ビルドした成果物をPDIへ配備します。
npm run deploy # now-sdk install を実行
[now-sdk] Starting installation with SDK 4.14.0...
[now-sdk] Attempting to log into instance https://devXXXXXX.service-now.com as admin.
[now-sdk] Rollback (undo installation): https://devXXXXXX.service-now.com/sys_rollback_context.do?sys_id=...
[now-sdk] Installation completed. Access the application at: https://devXXXXXX.service-now.com/sys_app.do?sys_id=...
デプロイログに表示される sys_rollback_context のURLにアクセスすると、今回のインストールで作成・更新された全メタデータの一覧が確認でき、ワンクリックで適用前の状態に戻せます。
デプロイ後の画面確認
6. テストハーネスによる実機検証の自動化
AIエージェントにコード修正を依頼する際、毎回人間がブラウザを開いて手動で動作確認をしていては手間がかかります。特にServiceNowの独自仕様(スキーマ設定値やBusiness Ruleの実行タイミングなど)は、一発で思い通りの挙動にならないことがよくあります。
そこで、PDIインスタンス上で直接アサーションを実行し、結果をJSON形式で受け取れるテストスクリプト(テストハーネス)を用意しました。
// scripts/test-harness.js
(function() {
var results = { harnessVersion: "1.0.0", checks: [], allPassed: true };
function assert(name, condition, details) {
var passed = !!condition;
results.checks.push({ name: name, passed: passed, details: details || '' });
if (!passed) {
results.allPassed = false;
gs.error("[HARNESS FAIL] " + name + (details ? " (" + details + ")" : ""));
} else {
gs.info("[HARNESS PASS] " + name + (details ? " (" + details + ")" : ""));
}
}
try {
// 1. スキーマ検証: Display Columnがmodel_nameになっているか
var dictGr = new GlideRecord('sys_dictionary');
dictGr.addQuery('name', 'x_customer_sdlc_procurement_request');
dictGr.addQuery('element', 'model_name');
dictGr.query();
assert("Display column is model_name", dictGr.next() && dictGr.display == true);
// 2. UI設定検証: asset_categoryがプルダウン(choice=3)になっているか
var choiceDict = new GlideRecord('sys_dictionary');
choiceDict.addQuery('name', 'x_customer_sdlc_procurement_request');
choiceDict.addQuery('element', 'asset_category');
choiceDict.query();
assert("Asset category dropdown configured", choiceDict.next() && (choiceDict.choice == '1' || choiceDict.choice == '3'));
// 3. 業務ガード検証: 未完了申請が紐付くインシデントの解決がブロックされるか
var proc = new GlideRecord('x_customer_sdlc_procurement_request');
proc.initialize();
proc.model_name = 'Harness Test Laptop';
proc.approval_status = 'draft';
var procId = proc.insert();
var inc = new GlideRecord('incident');
inc.initialize();
inc.short_description = 'Harness Guard Incident Test';
inc.x_customer_sdlc_procurement_ref = procId;
inc.state = '1'; // New
var incId = inc.insert();
// 解決を試みる(宣言的ガードによりブロックされて null が返ることを検証)
inc.state = '6'; // Resolved
var updateResult = inc.update();
assert("Resolution aborted when procurement is draft", updateResult === null);
// 納品完了後は正常に解決できることを検証
proc.approval_status = 'fulfilled';
proc.update();
inc.state = '6';
var updateResult2 = inc.update();
assert("Resolution succeeds after procurement fulfilled", updateResult2 !== null);
// テストデータの削除
inc.deleteRecord();
proc.deleteRecord();
assert("Test data cleanup completed", true);
} catch (e) {
assert("Harness runtime exception", false, e.message);
}
gs.info("===AUTONOMOUS_HARNESS_SUMMARY===" + JSON.stringify(results));
})();
package.json に実行スクリプトを追加します。
{
"scripts": {
"build": "now-sdk build",
"deploy": "now-sdk install",
"test:harness": "now-sdk exec --auth pdi --file ./scripts/test-harness.js"
}
}
CLIから npm run test:harness を実行すると、インスタンス上での実行ログが出力されます。
> now-sdk exec --auth pdi --file ./scripts/test-harness.js
[HARNESS PASS] Display column is model_name (display=true)
[HARNESS PASS] Asset category choice dropdown configured (choice=3)
[HARNESS PASS] Resolution aborted when procurement is draft (updateResult=null)
[HARNESS PASS] Resolution succeeds after procurement fulfilled (updateResult2=...)
[HARNESS PASS] Test data cleanup completed
===AUTONOMOUS_HARNESS_SUMMARY==={"harnessVersion":"1.0.0","allPassed":true}
このハーネスを用意しておくことで、エージェント自身に npm run test:harness を実行させ、エラーログをもとに修正とデプロイを繰り返させることが可能になりました。
7. CI/CDパイプライン連携(GitHub Actions)
作成したコードはGitHub Actionsで自動検証・配備できます。
--frozenKeys によるキーの整合性チェック
ServiceNow Fluentでは、コード内の論理ID($id)と実機の物理ID(sys_id)の紐付け情報が src/fluent/generated/keys.ts に記録されます。
もし keys.ts の変更をコミットし忘れて別のインスタンスにデプロイすると、既存レコードが上書きされず別レコードとして二重登録される恐れがあります。
CIビルド時に --frozenKeys オプションを付与することで、未コミットのキー変更を検知してビルドを失敗させることができます。
npx now-sdk build --frozenKeys
ワークフローの記述例(.github/workflows/deploy.yml)
ServiceNow公式のGitHub Action(ServiceNow/sncicd-atf-run)を組み合わせた設定例です。
name: ServiceNow SDK CI/CD Pipeline
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 24.x
cache: 'npm'
- name: Install Dependencies
run: npm ci
env:
NODE_OPTIONS: "--max-old-space-size=4096"
- name: Build with Frozen Keys Validation
run: npx now-sdk build --frozenKeys
- name: Authenticate to ServiceNow (CI Target Instance)
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
run: |
echo "${{ secrets.NOW_PASSWORD }}" | npx now-sdk auth --add "${{ secrets.NOW_INSTANCE_URL }}" \
--type basic \
--alias ci-instance \
--username "${{ secrets.NOW_USERNAME }}" \
--password-stdin
npx now-sdk auth --use ci-instance
- name: Deploy Application to ServiceNow
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
run: npx now-sdk install --auth ci-instance
- name: Execute ATF Test Suite via ServiceNow Official Action
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
uses: ServiceNow/sncicd-atf-run@2.0.0
with:
nowInstanceUrl: ${{ secrets.NOW_INSTANCE_URL }}
nowUsername: ${{ secrets.NOW_USERNAME }}
nowPassword: ${{ secrets.NOW_PASSWORD }}
testSuiteSysId: ${{ secrets.NOW_TEST_SUITE_SYS_ID }}
8. 実装でわかった知見とまとめ
ハマりどころと対処法
-
選択肢フィールドのUI設定:
StringColumnにchoicesを定義しただけでは、画面上はテキスト入力のままになります。ドロップダウン形式にするにはdropdown: 'dropdown_without_none'の指定が必要です。 -
Display Columnの指定:
他テーブルからの参照時にレコードを識別しやすくするため、Table定義のルートでdisplay: 'model_name'を明示しておく必要があります。 -
Node.jsのヒープメモリ枯渇:
型定義の展開でビルドが落ちることがあるため、プロジェクト直下の.npmrcでnode-options="--max-old-space-size=4096"を指定しておくのが無難です。 -
クロススコープでのAbort制御:
標準テーブル(Global)を拡張したスコープから処理をブロックする場合、スクリプト内でcurrent.setAbortAction(true)を呼ぶとスコープ制約に引っかかることがあります。Business Ruleのプロパティ(abortAction: trueとcondition)を用いた宣言的Abortを使うのが確実です。
Update Set運用とモダンSDLCの比較
| 項目 | Update Set運用 | ServiceNow SDK & Fluent |
|---|---|---|
| 管理の基準 (SSOT) | インスタンス内のDBレコード | Gitリポジトリのソースコード |
| コードレビュー | 困難(目視またはXML差分) | GitHub等のプルリクエストで差分確認 |
| 環境間デプロイ | 各環境での手動プレビュー・コミット | CI/CDパイプラインによる自動配備 |
| ロールバック | バックアウト(依存関係で失敗しやすい) |
sys_rollback_context による一括復元 |
| テスト自動化 | インスタンス画面での手動実行 | FluentによるATFコード化とCI自動実行 |
| AIエージェント親和性 | 低い(ブラウザ画面の操作が必要) | 高い(CLI経由でのビルド・テスト実行が可能) |
所感
ServiceNow SDKとFluentを実際に触ってみると、設定のコード化やGitによるバージョン管理、CI/CDとの連携など、一般的なWebアプリケーション開発に近いワークフローが実現できていると感じます。
組織内のリリースプロセスや権限設計との兼ね合いはあるものの、マージコンフリクトの防止や変更履歴の可視化といった恩恵は大きいです。また、CLIから実行可能なテストハーネスを用意しておくアプローチは、AIエージェントを活用した開発だけでなく、通常の自動テストパイプラインとしても有用だと感じました。



