Coverage for scripts / create_asset.py: 23%
48 statements
« prev ^ index » next coverage.py v7.13.0, created at 2025-12-25 18:08 -0500
« prev ^ index » next coverage.py v7.13.0, created at 2025-12-25 18:08 -0500
1#!/usr/bin/env python3
2"""
3Create a new asset/CMDB object.
5Creates new asset with specified attributes.
6Requires JSM Premium license or Assets license.
8Usage:
9 create_asset.py --type-id 5 --attr "IP Address=192.168.1.105" --attr "Status=Active"
10 create_asset.py --type-id 5 --attr "IP Address=192.168.1.105" --attr "Status=Active" --dry-run
11"""
13import argparse
14import sys
15import json
16from pathlib import Path
18# Add shared lib to path
19shared_lib_path = str(Path(__file__).parent.parent.parent.parent / 'shared' / 'scripts' / 'lib')
20if shared_lib_path not in sys.path:
21 sys.path.insert(0, shared_lib_path)
23from config_manager import get_jira_client
26def create_asset(object_type_id: int, attributes: dict, dry_run: bool = False):
27 """
28 Create a new asset.
30 Args:
31 object_type_id: Object type ID
32 attributes: Dict mapping attribute names to values
33 dry_run: If True, don't actually create
35 Returns:
36 Created asset object (or None if dry_run)
37 """
38 with get_jira_client() as client:
39 # Check license first
40 if not client.has_assets_license():
41 print("ERROR: Assets/Insight not available. Requires JSM Premium license.", file=sys.stderr)
42 sys.exit(1)
44 if dry_run:
45 print("DRY RUN: Would create asset with:")
46 print(f" Object Type ID: {object_type_id}")
47 print(f" Attributes: {json.dumps(attributes, indent=4)}")
48 return None
50 return client.create_asset(object_type_id, attributes)
53def parse_attributes(attr_list: list) -> dict:
54 """Parse attribute list into dict."""
55 attributes = {}
56 for attr_str in attr_list:
57 if '=' not in attr_str:
58 raise ValueError(f"Invalid attribute format: {attr_str}. Expected: name=value")
59 name, value = attr_str.split('=', 1)
60 attributes[name.strip()] = value.strip()
61 return attributes
64def main():
65 parser = argparse.ArgumentParser(
66 description="Create new asset/CMDB object",
67 formatter_class=argparse.RawDescriptionHelpFormatter,
68 epilog=__doc__
69 )
70 parser.add_argument('--type-id', type=int, required=True,
71 help='Object type ID')
72 parser.add_argument('--attr', action='append', required=True,
73 help='Attribute in format name=value (can be used multiple times)')
74 parser.add_argument('--dry-run', action='store_true',
75 help='Preview changes without creating')
76 parser.add_argument('--profile', help='JIRA profile to use')
78 args = parser.parse_args()
80 try:
81 attributes = parse_attributes(args.attr)
82 asset = create_asset(args.type_id, attributes, args.dry_run)
84 if not args.dry_run:
85 print(f"✓ Asset created successfully!")
86 print(f"Asset ID: {asset.get('id')}")
87 print(f"Asset Key: {asset.get('objectKey')}")
89 except SystemExit:
90 raise
91 except Exception as e:
92 print(f"Error creating asset: {str(e)}", file=sys.stderr)
93 sys.exit(1)
96if __name__ == "__main__":
97 main()