changeTracking

package
v0.111.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 2, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CmdChangeTrackingCreate = &cobra.Command{
	Use:   "create",
	Short: "Create a New Relic change tracking event",
	Long: `Create a New Relic change tracking event.

This command allows you to create a change tracking event for a New Relic entity, supporting all fields in the Change Tracking GraphQL API schema for the changeTrackingCreateEvent mutation. For more information on each field, visit: https://docs.newrelic.com/docs/change-tracking/change-tracking-events/#change-tracking-event-mutation

Required fields:
  --entitySearch        Entity search query (e.g., name = 'MyService' AND type = 'SERVICE'). See our docs on 'entitySearch.query' under 'Required attributes' for more detailed examples: https://docs.newrelic.com/docs/change-tracking/change-tracking-events/#required-fields
  --category            Category of event (e.g. Deployment, Feature Flag, Operational, etc.)
  --type                Type of event (e.g. Basic, Rollback, Server Reboot, etc.)

For Deployment events, the following are required/supported:
  --version             Version of the deployment (required)
  --changelog           Changelog for the deployment (URL or text)
  --commit              Commit hash for the deployment
  --deepLink            Deep link URL for the deployment

For Feature Flag events, the following are required/supported:
  --featureFlagId       ID of the feature flag (required)

Other supported fields:
  --description         Description of the event
  --user                Username of the actor or bot
  --groupId             String to correlate two or more events
  --shortDescription    Short description for the event
  --customAttributes    Custom attributes: use '-' for STDIN, '{...}' for inline JS object, or provide a file path
  --validationFlags     Comma-separated list of validation flags (e.g. ALLOW_CUSTOM_CATEGORY_OR_TYPE, FAIL_ON_FIELD_LENGTH, FAIL_ON_REST_API_FAILURES)
  --timestamp           Time of the event (milliseconds since Unix epoch, defaults to now). Can not be more than 24 hours in the past or future

Custom attributes can be provided in three ways:
  1. From STDIN by passing '-' (e.g. 'echo  '{cloud_vendor: "vendor_name", region: "us-east-1", isProd: true, instances: 2}' | newrelic changeTracking create ... --customAttributes -')
  2. As an inline JS object starting with '{' (e.g. --customAttributes '{cloud_vendor: "vendor_name", region: "us-east-1", isProd: true, instances: 2}')
  3. As a file path (e.g. --customAttributes ./attrs.js)

The JS object format must use unquoted keys and values of type string, boolean, or number. Example: {cloud_vendor: "vendor_name", region: "us-east-1", isProd: true, instances: 2}

Validation is performed before sending to the API. Keys must be valid JS identifiers, and values must be string, boolean, or number.

For more information, see: https://docs.newrelic.com/docs/change-tracking/change-tracking-events/#change-tracking-event-mutation
`,
	Example: cmdChangeTrackingCreateExample,
	PreRun:  client.RequireClient,
	Run: func(cmd *cobra.Command, args []string) {
		params := changetracking.ChangeTrackingCreateEventInput{}

		if eventTimestamp == 0 {
			params.Timestamp = nrtime.EpochMilliseconds(time.Now())
		} else {
			params.Timestamp = nrtime.EpochMilliseconds(time.UnixMilli(eventTimestamp))
		}

		if eventCategory == "" {
			log.Fatal("--category cannot be empty")
		}
		if eventType == "" {
			log.Fatal("--type cannot be empty")
		}
		if eventSearchQuery == "" {
			log.Fatal("--entitySearch cannot be empty")
		}

		params.Description = eventDescription
		params.User = eventUser
		params.GroupId = eventGroupID
		params.ShortDescription = eventShortDescription
		params.EntitySearch = changetracking.ChangeTrackingEntitySearchInput{
			Query: eventSearchQuery,
		}
		params.CategoryAndTypeData = &changetracking.ChangeTrackingCategoryRelatedInput{
			Kind: &changetracking.ChangeTrackingCategoryAndTypeInput{
				Category: eventCategory,
				Type:     eventType,
			},
			CategoryFields: &changetracking.ChangeTrackingCategoryFieldsInput{},
		}

		validateCategoryFields(eventCategory)
		setCategoryFields(eventCategory, &params)

		// Custom Attributes: support --customAttributes with three parsing modes:
		// 1. If equals "-", read from STDIN
		// 2. If starts with "{", parse as JS object
		// 3. Otherwise, treat as file path
		var customAttrRaw string
		if eventCustomAttributes != "" {
			if eventCustomAttributes == "-" {

				stdinBytes, err := os.ReadFile("/dev/stdin")
				if err != nil {
					log.Fatalf("Failed to read custom attributes from STDIN: %v", err)
				}
				customAttrRaw = string(stdinBytes)
			} else if strings.HasPrefix(strings.TrimSpace(eventCustomAttributes), "{") {

				customAttrRaw = eventCustomAttributes
			} else {

				fileBytes, err := os.ReadFile(eventCustomAttributes)
				if err != nil {
					log.Fatalf("Failed to read custom attributes file: %v", err)
				}
				customAttrRaw = string(fileBytes)
			}
		}

		if customAttrRaw != "" {

			jsObj := strings.TrimSpace(customAttrRaw)
			if !strings.HasPrefix(jsObj, "{") || !strings.HasSuffix(jsObj, "}") {
				log.Fatal("customAttributes must be a JS object, e.g. {foo: \"bar\", num: 2, flag: true}")
			}

			kvRe := regexp.MustCompile(`([a-zA-Z_][a-zA-Z0-9_]*)\s*:\s*([^\"]+|\"[^\"]*\"|true|false|[0-9.]+)`)
			matches := kvRe.FindAllStringSubmatch(jsObj, -1)
			if len(matches) == 0 {
				log.Fatal("customAttributes must contain at least one valid key: value pair")
			}

			attrs, err := changetracking.ReadCustomAttributesJS(customAttrRaw, false)
			if err != nil {
				log.Fatalf("Failed to parse customAttributes as JS object: %v", err)
			}
			params.CustomAttributes = attrs
		}

		// Parse validation flags
		var flags []changetracking.ChangeTrackingValidationFlag
		for _, flag := range eventValidationFlags {
			switch flag {
			case "ALLOW_CUSTOM_CATEGORY_OR_TYPE":
				flags = append(flags, changetracking.ChangeTrackingValidationFlagTypes.ALLOW_CUSTOM_CATEGORY_OR_TYPE)
			case "FAIL_ON_FIELD_LENGTH":
				flags = append(flags, changetracking.ChangeTrackingValidationFlagTypes.FAIL_ON_FIELD_LENGTH)
			case "FAIL_ON_REST_API_FAILURES":
				flags = append(flags, changetracking.ChangeTrackingValidationFlagTypes.FAIL_ON_REST_API_FAILURES)
			}
		}
		dataHandlingRules := changetracking.ChangeTrackingDataHandlingRules{ValidationFlags: flags}

		result, err := client.NRClient.ChangeTracking.ChangeTrackingCreateEventWithContext(
			utils.SignalCtx,
			params,
			dataHandlingRules,
		)
		utils.LogIfFatal(err)
		utils.LogIfFatal(output.Print(result))
	},
}
View Source
var Command = &cobra.Command{
	Use:   "changeTracking",
	Short: "Manage change tracking events for New Relic",
}

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL