Set a key to an arbitrary value. It is used like setval but works with nested keys. This function is conservative. It will only overwrite an entry if its value and the given one are not a list or a dict. The ``force`` parameter is used to allow overwriting in all cases. ..
(key, val="", force=False, destructive=False, delimiter=DEFAULT_TARGET_DELIM)
| 618 | |
| 619 | |
| 620 | def set(key, val="", force=False, destructive=False, delimiter=DEFAULT_TARGET_DELIM): |
| 621 | """ |
| 622 | Set a key to an arbitrary value. It is used like setval but works |
| 623 | with nested keys. |
| 624 | |
| 625 | This function is conservative. It will only overwrite an entry if |
| 626 | its value and the given one are not a list or a dict. The ``force`` |
| 627 | parameter is used to allow overwriting in all cases. |
| 628 | |
| 629 | .. versionadded:: 2015.8.0 |
| 630 | |
| 631 | :param force: Force writing over existing entry if given or existing |
| 632 | values are list or dict. Defaults to False. |
| 633 | :param destructive: If an operation results in a key being removed, |
| 634 | delete the key, too. Defaults to False. |
| 635 | :param delimiter: |
| 636 | Specify an alternate delimiter to use when traversing a nested dict, |
| 637 | the default being ``:`` |
| 638 | |
| 639 | CLI Example: |
| 640 | |
| 641 | .. code-block:: bash |
| 642 | |
| 643 | salt '*' grains.set 'apps:myApp:port' 2209 |
| 644 | salt '*' grains.set 'apps:myApp' '{port: 2209}' |
| 645 | """ |
| 646 | |
| 647 | ret = {"comment": "", "changes": {}, "result": True} |
| 648 | |
| 649 | # Get val type |
| 650 | _new_value_type = "simple" |
| 651 | if isinstance(val, dict): |
| 652 | _new_value_type = "complex" |
| 653 | elif isinstance(val, list): |
| 654 | _new_value_type = "complex" |
| 655 | |
| 656 | _non_existent = object() |
| 657 | _existing_value = get(key, _non_existent, delimiter) |
| 658 | _value = _existing_value |
| 659 | |
| 660 | _existing_value_type = "simple" |
| 661 | if _existing_value is _non_existent: |
| 662 | _existing_value_type = None |
| 663 | elif isinstance(_existing_value, dict): |
| 664 | _existing_value_type = "complex" |
| 665 | elif isinstance(_existing_value, list): |
| 666 | _existing_value_type = "complex" |
| 667 | |
| 668 | if ( |
| 669 | _existing_value_type is not None |
| 670 | and _existing_value == val |
| 671 | and (val is not None or destructive is not True) |
| 672 | ): |
| 673 | ret["comment"] = "Grain is already set" |
| 674 | return ret |
| 675 | |
| 676 | if _existing_value is not None and not force: |
| 677 | if _existing_value_type == "complex": |