diff --git a/docs/reference/schemas/config/functions/overview.md b/docs/reference/schemas/config/functions/overview.md index 236b8a6db..f4c8fdb0d 100644 --- a/docs/reference/schemas/config/functions/overview.md +++ b/docs/reference/schemas/config/functions/overview.md @@ -567,24 +567,65 @@ resources: The following sections include the available DSC configuration functions by purpose and input type. -### Array functions +### Array and collection functions -The following list of functions operate on arrays: +The following list of functions operate on arrays and collections: +- [array()][array] - Convert a value into an array containing that value. - [concat()][concat] - Combine multiple arrays of strings into a single array of strings. +- [contains()][contains] - Check if an array contains a value or an object contains a key. - [createArray()][createArray] - Create an array of a given type from zero or more values of the same type. -- [min()][min] - Return the smallest integer value from an array of integers. +- [empty()][empty] - Check if a value (string, array, or object) is empty. +- [first()][first] - Return the first element of an array or the first character of a string. +- [indexOf()][indexOf] - Return the zero-based index of the first occurrence of a value in an array. +- [intersection()][intersection] - Return a single array or object with the common elements from the parameters. +- [items()][items] - Convert an object into an array of key-value pair objects. +- [join()][join] - Combine array elements into a single string with a specified delimiter. +- [last()][last] - Return the last element of an array or the last character of a string. +- [lastIndexOf()][lastIndexOf] - Return the zero-based index of the last occurrence of a value in an array. +- [length()][length] - Return the number of elements in an array, characters in a string, or top-level properties in an object. - [max()][max] - Return the largest integer value from an array of integers. +- [min()][min] - Return the smallest integer value from an array of integers. +- [range()][range] - Create an array of integers within a specified range. +- [skip()][skip] - Return an array or string with elements skipped from the beginning. +- [tryGet()][tryGet] - Safely retrieve a value from an array by index or an object by key without throwing an error. +- [tryIndexFromEnd()][tryIndexFromEnd] - Safely retrieve a value from an array by counting backward from the end. +- [union()][union] - Return a single array or object with all unique elements from the parameters. + +### Comparison functions + +The following list of functions compare values: + +- [equals()][equals] - Check if two values are equal. +- [greater()][greater] - Check if the first value is greater than the second value. +- [greaterOrEquals()][greaterOrEquals] - Check if the first value is greater than or equal to the second value. +- [less()][less] - Check if the first value is less than the second value. +- [lessOrEquals()][lessOrEquals] - Check if the first value is less than or equal to the second value. ### Data functions The following list of functions operate on data outside of a resource instance: +- [context()][context] - Return contextual information about the system and execution environment. - [envvar()][envvar] - Return the value of a specified environment variable. - [parameters()][parameters] - Return the value of a specified configuration parameter. +- [secret()][secret] - Retrieve a secret value from a secure store. - [variables()][variables] - Return the value of a specified configuration variable. +### Logical functions + +The following list of functions perform logical operations: + +- [and()][and] - Return true if all boolean values are true. +- [bool()][bool] - Convert a value to a boolean. +- [false()][false] - Return the boolean value false. +- [if()][if] - Return one of two values based on a boolean condition. +- [not()][not] - Return the logical negation of a boolean value. +- [null()][null] - Return a null value. +- [or()][or] - Return true if any boolean value is true. +- [true()][true] - Return the boolean value true. + ### Mathematics functions The following list of functions operate on integer values or arrays of integer values: @@ -599,6 +640,18 @@ The following list of functions operate on integer values or arrays of integer v - [mul()][mul] - Return the product from multiplying two integers. - [sub()][sub] - Return the difference from subtracting one integer from another. +### Object functions + +The following list of functions operate on objects: + +- [coalesce()][coalesce] - Return the first non-null value from the provided arguments. +- [contains()][contains] - Check if an array contains a value or an object contains a key. +- [createObject()][createObject] - Create an object from key-value pairs. +- [empty()][empty] - Check if a value (string, array, or object) is empty. +- [items()][items] - Convert an object into an array of key-value pair objects. +- [json()][json] - Parse a JSON string and return the resulting value. +- [tryGet()][tryGet] - Safely retrieve a value from an array by index or an object by key without throwing an error. + ### Resource functions The following list of functions operate on resource instances: @@ -613,36 +666,118 @@ The following list of functions operate on resource instances: The following list of functions are for manipulating strings: - [base64()][base64] - Return the base64 representation of a string. +- [base64ToString()][base64ToString] - Decode a base64-encoded string and return the original string. - [concat()][concat] - Return a combined string where the input strings are concatenated in the order they're specified. +- [contains()][contains] - Check if an array contains a value or an object contains a key. +- [empty()][empty] - Check if a value (string, array, or object) is empty. +- [endsWith()][endsWith] - Check if a string ends with a specified suffix. +- [first()][first] - Return the first element of an array or the first character of a string. +- [format()][format] - Create a formatted string from input values. +- [join()][join] - Combine array elements into a single string with a specified delimiter. +- [last()][last] - Return the last element of an array or the last character of a string. +- [length()][length] - Return the number of elements in an array, characters in a string, or top-level properties in an object. +- [skip()][skip] - Return an array or string with elements skipped from the beginning. +- [startsWith()][startsWith] - Check if a string starts with a specified prefix. +- [string()][string] - Convert a value to its string representation. +- [substring()][substring] - Extract a portion of a string starting at a specified position. +- [toLower()][toLower] - Convert a string to lowercase. +- [toUpper()][toUpper] - Convert a string to uppercase. +- [trim()][trim] - Remove leading and trailing whitespace from a string. +- [uniqueString()][uniqueString] - Create a deterministic hash string based on provided values. +- [uri()][uri] - Create an absolute URI by combining a base URI with a relative URI string. +- [uriComponent()][uriComponent] - Encode a string for use as a URI component. +- [uriComponentToString()][uriComponentToString] - Decode a URI-encoded string. + +### System functions + +The following list of functions provide system-level information: + +- [path()][path] - Construct a file system path from one or more path segments. +- [systemRoot()][systemRoot] - Return the system root directory path. +- [utcNow()][utcNow] - Return the current UTC datetime in a specified format. ### Type functions The following list of functions create or convert values of a given type: +- [array()][array] - Convert a value into an array containing that value. +- [bool()][bool] - Convert a value to a boolean. - [createArray()][createArray] - Create an array of a given type from zero or more values of the same type. +- [createObject()][createObject] - Create an object from key-value pairs. - [int()][int] - Convert a string or number with a fractional part into an integer. +- [string()][string] - Convert a value to its string representation. [01]: https://yaml.org/spec/1.2.2/#folded-style [02]: https://yaml.org/spec/1.2.2/#literal-style [03]: https://yaml.org/spec/1.2.2/#block-chomping-indicator -[add]: ./add.md -[base64]: ./base64.md -[concat]: ./concat.md -[copyIndex]: ./copyIndex.md -[createArray]: ./createArray.md -[div]: ./div.md -[envvar]: ./envvar.md -[int]: ./int.md -[max]: ./max.md -[min]: ./min.md -[mod]: ./mod.md -[mul]: ./mul.md -[parameters]: ./parameters.md -[reference]: ./reference.md -[resourceId]: ./resourceId.md -[sub]: ./sub.md -[variables]: ./variables.md +[add]: ./add.md +[and]: ./and.md +[array]: ./array.md +[base64]: ./base64.md +[base64ToString]: ./base64ToString.md +[bool]: ./bool.md +[coalesce]: ./coalesce.md +[concat]: ./concat.md +[contains]: ./contains.md +[context]: ./context.md +[copyIndex]: ./copyIndex.md +[createArray]: ./createArray.md +[createObject]: ./createObject.md +[div]: ./div.md +[empty]: ./empty.md +[endsWith]: ./endsWith.md +[envvar]: ./envvar.md +[equals]: ./equals.md +[false]: ./false.md +[first]: ./first.md +[format]: ./format.md +[greater]: ./greater.md +[greaterOrEquals]: ./greaterOrEquals.md +[if]: ./if.md +[indexOf]: ./indexOf.md +[int]: ./int.md +[intersection]: ./intersection.md +[items]: ./items.md +[join]: ./join.md +[json]: ./json.md +[last]: ./last.md +[lastIndexOf]: ./lastIndexOf.md +[length]: ./length.md +[less]: ./less.md +[lessOrEquals]: ./lessOrEquals.md +[max]: ./max.md +[min]: ./min.md +[mod]: ./mod.md +[mul]: ./mul.md +[not]: ./not.md +[null]: ./null.md +[or]: ./or.md +[parameters]: ./parameters.md +[path]: ./path.md +[range]: ./range.md +[reference]: ./reference.md +[resourceId]: ./resourceId.md +[secret]: ./secret.md +[skip]: ./skip.md +[startsWith]: ./startsWith.md +[string]: ./string.md +[sub]: ./sub.md +[substring]: ./substring.md +[systemRoot]: ./systemRoot.md +[toLower]: ./toLower.md +[toUpper]: ./toUpper.md +[trim]: ./trim.md +[true]: ./true.md +[tryGet]: ./tryGet.md +[tryIndexFromEnd]: ./tryIndexFromEnd.md +[union]: ./union.md +[uniqueString]: ./uniqueString.md +[uri]: ./uri.md +[uriComponent]: ./uriComponent.md +[uriComponentToString]: ./uriComponentToString.md +[utcNow]: ./utcNow.md +[variables]: ./variables.md diff --git a/docs/reference/schemas/config/functions/tryGet.md b/docs/reference/schemas/config/functions/tryGet.md new file mode 100644 index 000000000..1e87f08d2 --- /dev/null +++ b/docs/reference/schemas/config/functions/tryGet.md @@ -0,0 +1,323 @@ +--- +description: Reference for the 'tryGet' DSC configuration document function +ms.date: 01/29/2025 +ms.topic: reference +title: tryGet +--- + +## Synopsis + +Safely retrieves a value from an array by index or an object by key without +throwing an error if the key or index doesn't exist. + +## Syntax + +```Syntax +tryGet(source, keyOrIndex) +``` + +## Description + +The `tryGet()` function provides a safe way to access elements in arrays or +objects without causing errors when the key or index doesn't exist. Unlike +direct property access that might fail, this function returns `null` when the +requested element cannot be found. + +For arrays, the function uses zero-based indexing where `0` refers to the first +element. For objects, it retrieves values by their property key name. This is +particularly useful when working with dynamic data structures where the presence +of keys or the length of arrays isn't guaranteed. + +The function returns `null` in the following cases: + +- The specified key doesn't exist in the object +- The array index is negative +- The array index is greater than or equal to the array length +- The array is empty + +## Examples + +### Example 1 - Safely access configuration settings with fallbacks + +Access optional configuration values that might not be present in all +environments without causing errors. This example demonstrates retrieving +feature flags that may or may not be defined. This example uses +[`createObject()`][03] to build the configuration object and [`coalesce()`][02] +for fallback values. + +```yaml +# tryGet.example.1.dsc.config.yaml +$schema: https://aka.ms/dsc/schemas/v3/bundled/config/document.json +resources: +- name: Feature Flags + type: Microsoft.DSC.Debug/Echo + properties: + output: + config: "[createObject('enableBeta', true, 'enableDebug', false)]" + betaEnabled: "[coalesce(tryGet(createObject('enableBeta', true, 'enableDebug', false), 'enableBeta'), false)]" + alphaEnabled: "[coalesce(tryGet(createObject('enableBeta', true, 'enableDebug', false), 'enableAlpha'), false)]" + debugEnabled: "[tryGet(createObject('enableBeta', true, 'enableDebug', false), 'enableDebug')]" +``` + +```bash +dsc config get --file tryGet.example.1.dsc.config.yaml +``` + +```yaml +results: +- name: Feature Flags + type: Microsoft.DSC.Debug/Echo + result: + actualState: + output: + config: + enableBeta: true + enableDebug: false + betaEnabled: true + alphaEnabled: false + debugEnabled: false +messages: [] +hadErrors: false +``` + +The function safely returns `true` for the existing `enableBeta` flag, `null` +for the non-existent `enableAlpha` flag (which `coalesce()` converts to +`false`), and `false` for the `enableDebug` flag. + +### Example 2 - Access deployment environment settings + +Retrieve environment-specific configuration values with safe defaults. This is +useful when different environments might have different configuration keys. This +example uses [`parameters()`][07] to reference the environment configuration, +making the complex nested object structure easier to understand. + +```yaml +# tryGet.example.2.dsc.config.yaml +$schema: https://aka.ms/dsc/schemas/v3/bundled/config/document.json +parameters: + environments: + type: object + defaultValue: + production: + replicas: 5 + region: us-east-1 + staging: + replicas: 2 +resources: +- name: Environment Config + type: Microsoft.DSC.Debug/Echo + properties: + output: + environments: "[parameters('environments')]" + productionEnv: "[tryGet(parameters('environments'), 'production')]" + stagingEnv: "[tryGet(parameters('environments'), 'staging')]" + developmentEnv: "[tryGet(parameters('environments'), 'development')]" + prodReplicas: "[tryGet(tryGet(parameters('environments'), 'production'), 'replicas')]" + prodRegion: "[tryGet(tryGet(parameters('environments'), 'production'), 'region')]" + stagingRegion: "[tryGet(tryGet(parameters('environments'), 'staging'), 'region')]" +``` + +```bash +dsc config get --file tryGet.example.2.dsc.config.yaml +``` + +```yaml +results: +- name: Environment Config + type: Microsoft.DSC.Debug/Echo + result: + actualState: + output: + environments: + production: + replicas: 5 + region: us-east-1 + staging: + replicas: 2 + productionEnv: + replicas: 5 + region: us-east-1 + stagingEnv: + replicas: 2 + developmentEnv: null + prodReplicas: 5 + prodRegion: us-east-1 + stagingRegion: null +messages: [] +hadErrors: false +``` + +The function safely returns the environment objects when they exist, or `null` +for the non-existent `development` environment. It also demonstrates accessing +nested object properties separately. + +### Example 3 - Safely access array elements by position + +Access array elements without worrying about index out-of-range errors. This is +particularly useful when processing arrays of unknown or varying length. This +example uses [`createArray()`][00] to build the version history. + +```yaml +# tryGet.example.3.dsc.config.yaml +$schema: https://aka.ms/dsc/schemas/v3/bundled/config/document.json +resources: +- name: Version History + type: Microsoft.DSC.Debug/Echo + properties: + output: + versions: "[createArray('v1.0.0', 'v1.1.0', 'v1.2.0')]" + current: "[tryGet(createArray('v1.0.0', 'v1.1.0', 'v1.2.0'), 2)]" + previous: "[tryGet(createArray('v1.0.0', 'v1.1.0', 'v1.2.0'), 1)]" + future: "[tryGet(createArray('v1.0.0', 'v1.1.0', 'v1.2.0'), 5)]" + invalid: "[tryGet(createArray('v1.0.0', 'v1.1.0', 'v1.2.0'), -1)]" +``` + +```bash +dsc config get --file tryGet.example.3.dsc.config.yaml +``` + +```yaml +results: +- name: Version History + type: Microsoft.DSC.Debug/Echo + result: + actualState: + output: + versions: + - v1.0.0 + - v1.1.0 + - v1.2.0 + current: v1.2.0 + previous: v1.1.0 + future: null + invalid: null +messages: [] +hadErrors: false +``` + +The function safely returns array elements at valid indices, and `null` for +out-of-range indices (both negative and beyond the array length). + +### Example 4 - Parse API responses with optional fields + +Process data structures that might have optional or conditional fields, such as +API responses where certain fields only appear in specific scenarios. This +example uses [`createObject()`][03] to simulate API response data. + +```yaml +# tryGet.example.4.dsc.config.yaml +$schema: https://aka.ms/dsc/schemas/v3/bundled/config/document.json +resources: +- name: API Response Parser + type: Microsoft.DSC.Debug/Echo + properties: + output: + successResponse: "[createObject('status', 200, 'data', createObject('id', 123, 'name', 'example'))]" + errorResponse: "[createObject('status', 404, 'error', 'Not Found')]" + successData: "[tryGet(createObject('status', 200, 'data', createObject('id', 123, 'name', 'example')), 'data')]" + successError: "[tryGet(createObject('status', 200, 'data', createObject('id', 123, 'name', 'example')), 'error')]" + errorData: "[tryGet(createObject('status', 404, 'error', 'Not Found'), 'data')]" + errorMessage: "[tryGet(createObject('status', 404, 'error', 'Not Found'), 'error')]" +``` + +```bash +dsc config get --file tryGet.example.4.dsc.config.yaml +``` + +```yaml +results: +- name: API Response Parser + type: Microsoft.DSC.Debug/Echo + result: + actualState: + output: + successResponse: + status: 200 + data: + id: 123 + name: example + errorResponse: + status: 404 + error: Not Found + successData: + id: 123 + name: example + successError: null + errorData: null + errorMessage: Not Found +messages: [] +hadErrors: false +``` + +The function gracefully handles missing fields, allowing you to build robust +parsers that work with varying response structures. + +## Parameters + +### source + +The array or object to retrieve the value from. For arrays, elements are +accessed by zero-based index. For objects, values are accessed by string key. +Required. + +```yaml +Type: array | object +Required: true +Position: 1 +``` + +### keyOrIndex + +For arrays: the zero-based integer index of the element to retrieve. For +objects: the string key name of the property to retrieve. Required. + +```yaml +Type: integer | string +Required: true +Position: 2 +``` + +## Output + +Returns the value at the specified index or key if it exists. Returns `null` if: + +- The array index is negative, out of range, or the array is empty +- The object key doesn't exist + +The return type matches the type of the element or property value in the +array or object. + +```yaml +Type: any | null +``` + +## Errors + +The function returns an error in the following cases: + +- **Invalid source type**: The first argument is neither an array nor an object +- **Invalid key type for object**: When accessing an object, the second argument + must be a string +- **Invalid index type for array**: When accessing an array, the second argument + must be an integer + +## Related functions + +- [`createArray()`][00] - Creates an array from provided values +- [`createObject()`][03] - Creates an object from key-value pairs +- [`coalesce()`][02] - Returns the first non-null value from a list +- [`if()`][04] - Returns one of two values based on a condition +- [`equals()`][05] - Compares two values for equality +- [`not()`][06] - Inverts a boolean value +- [`tryIndexFromEnd()`][01] - Safely retrieves array elements by counting backward from the end +- [`parameters()`][07] - Returns the value of a specified configuration parameter + + +[00]: ./createArray.md +[01]: ./tryIndexFromEnd.md +[02]: ./coalesce.md +[03]: ./createObject.md +[04]: ./if.md +[05]: ./equals.md +[06]: ./not.md +[07]: ./parameters.md