-
Notifications
You must be signed in to change notification settings - Fork 56
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[BUG] value_raw set to a variable #186
Comments
Hello clagio, can you please try to write the rule as dict(key:list)? Tuples and ansible are kind of impossible and I suspect that the API call will be JSON-encoded anyways. JSON doesn't know tuples. The debug output in ansible is the output of json.dumps() and thus the original type of the object isn't preserved. At the moment I have no 2.1 instance available for testing and 2.0-API does not provide the rules. |
Hi, I tried removing the double quotes s you asked, but I get the same error "Unsupported type. Field must be string" but in this case I see from the debug info that all the output is mixed up. I get the same error also with a different rule (ruleset special_agents:aws) if I try to move the access_key_id in a variable`. As before, if I hardcode the value, it works fine:
|
Have you removed the "()" and replaced them with "[]", too? Ansible doesn't know the tuple-notation (tup1,tup2) of python. The line in YAML is then interpreted as string and mixed up. Edit: Does not work. See next comment for solution. |
I set up a 2.1 instance, modified the source and achieved this:
=>
Source modification:
and
Now I have two options:
My modifications construct the proper string for the API including replacement of the square brackets (=python/YAML list) with the round brackets (=python tuple). |
thanks, I modified the source as you did, and indeed now the first task( myvariable: {'levels': [81,91]}) works, but I get an error with the following :
I will have a look later at the sources to see if I can find why |
I had a better look, your change replace all squared brackets with rounded brackets, which means this: I have also an issue where it keep creating the rule even if already exists, but I haven't narrowed down the problem yet. Would make sense to use the description field to detect if the rule already exists instead of matching conditions/properties/value_raw? |
Yes, you are right. The only clean way to get this resolved in my opinion is that the API of Checkmk should accept and deliver JSON and not a string which is "evaluated" into a python object. There was some discussion about that in #153 The second possibility will be to get rid of all tuples inside the rules. But this is a lot more work to do I think. I have problems to update the rule without my modifications, too. If only a single character or value differs in "conditions", "properties" or "value_raw" a new rule is created. |
I agree the cleanest way is to fix it at the API level.. Anyway I did some changes and now I have a rule.py that works in all my cases. It's not super clean, but I'm not sure there is a better way without modifying the API. I also changed so that the rule matching (if already exists) is done only comparing the description. There are several problem trying to compare conditions, properties and value_raw. Value raw has all the problems with escaping chars, and since there are different possible parameters I suspect there is an high chance of mismatch.
It's not impossible to match against all the properties, but I think requires a lot of work to make it work for all the possible cases. I believe matching by description it's simple and effective. I created a new function transform_value_raw, where I take the value_raw and change the brackets only for secret_access_key. Eventually new keys can be added if needed,
Modified the create_rule:
Modified the get_existing_rule:
I'm happy to submit the change if is ok |
For all password fields I found out the following: You can just write the password as string without the ('password', 'YOURPASSWORD') notation: This is done automatically and removes at least one type of tuples you have to care about, if the API won't be changed in the future. I try to find the relevant part in the API of https://github.com/tribe29/checkmk to make a PR there. |
that's right! thanks, it's helpful at least for the passwords |
Another tuple issue with the overall_tags:
The playbook runs fine and the rule is created but when I check the rule in checkmk the option "Restrict monitoring services by one of these AWS tags" is not flagged and I get the following message: Unable to read current options of this rule. Falling back to default values. When saving this rule now, your previous settings will be overwritten. Problem was: Restrict monitoring services by one of these AWS tags: The datatype must be a tuple, but is list. |
Unfortunately string substitution does not solve the problem and creates other ones, because there are arrays (lists) too, not only tuples! With this substitution for example I agree though that API should deliver correctly formatted JSON. Otherwise:
|
Probably this is also helpful, jinja2 template file with macros {#- Generate value_raw for rule from yaml nested dictionary -#}
{#- ########################################################################################################################### -#}
{%- macro generateline(elem) -%}
{%- if elem is mapping -%}
{{- '{' -}}
{%- for el in elem | dict2items -%}
{%- if el.value | lower != 'none' -%}
'{{ el.key }}': {{ generateline(el.value) }}
{%- endif -%}
{%- endfor -%}
{{- '}' -}},
{%- elif ( elem is iterable ) and ( elem is not string ) -%}
{#- check if it is real array, escaped, '[[]]' or just a substitute for tuple '[]' -#}
{%- if ( elem | count == 1 ) and ( elem[0] is not mapping ) and ( elem[0] is iterable ) and ( elem[0] is not string ) -%}
{{- '(' -}}
{%- for el in elem[0] -%}
{{ generateline(el)[:(-1 if loop.last else none):] }}
{%- endfor -%}
{{- ')' -}},
{%- else -%}
{{- '[' -}}
{%- for el in elem -%}
{{ generateline(el)[:(-1 if loop.last else none):] }}
{%- endfor -%}
{{- ']' -}},
{%- endif -%}
{%- else -%}
{%- if elem |int(-1) == -1 -%}
{% if '"' in elem or "'" in elem -%}
{{- elem }},
{%- else -%}
{{ elem | to_json }},
{%- endif -%}
{%- else -%}
{{ elem }},
{%- endif -%}
{%- endif -%}
{%- endmacro -%}
{#- ########################################################################################################################### -#}
{#- -#}
{#- ########################################################################################################################### -#}
{%- if value_raw is defined -%}
{{ generateline(value_raw)[:-1:] }}
{%- endif -%} in ansible then value_raw: "{{ lookup('template', 'value_raw_gen.j2') | string }}" |
I talked to one of our developers, and it looks like this is an upstream issue, which we cannot solve in the collection. Maybe someone can write up some sort of bottom line, where we are right now? |
If one will not get REST API fixed, so that
Before, it might be also useful to get some obvious bug fixes, I'll be glad to help. |
Thanks, Michael, we are on the same page. |
Both are closely tied to the idempotency of Ansible and the underlying REST API in modules. If there is a clear answer to the second question, or alternatively a decision what the primary and secondary properties of the rule are, I think the rest can be addressed more systematically and hence relatively easy. |
from my understanding there is a ID field that uniquely identify a rule, but a new random ID it's created automatically when you call the API, so you can have multiple rules with all the same values/properties but different ID. To achieve idempotency, in the collection has been arbitrarily decided to check against "conditions", "properties" and "value_raw". Personally I think we should have a "name" field for the rule (that's why I suggested to use the description since it's basically a name for the rule), and check against that, but again should be changed in the API. |
@clagio, there is one key problem in your proposal, how can one then apply the same rule to different folders? possible solutions:
Therefore I still think that there should be a reasonable set of primary fields/properties that are used to Identify the rule, like rule-set, folder, conditions, properties, and may be some subset of ID-s are for internal management and you do not know it apriori from Ansible or API side! |
Hi! Two problems related to this issue I came across while developping custom installation playbooks:
If we do not, the comparison fails. It would be great to add these (empty conditions) by default. I have edited the code to check only the description like suggested above, even if it's not a universal solution, it works for me. |
there is even more fundamental problem in the following comparison in rule module:
it cannot distinguish between the following variants (just an example, one can also make some others):
To avoid all related complication, even for such a simple case, one should parse As for now, as I understand, each of us has it's own workaround, which are not suitable to cover general cases and hnece to be integrated in the rule module, IMHO. Therefor, I will still repeat my question @robin-tribe29:
|
First, Happy new year everybody, and sorry for my late reply. I had a very busy December and the had some time to relax. The "ID" is only key the REST API uses to identify rules.
What do you think of implementing both solutions by inventing a parameter "keys" that has "[ ruleset, folder, conditions, properties, value_raw]" as a default, but can also be set to "[ description ]"? The function get_existing_rule() then can take care of that choice. @clagio, @muehlings, @geof77 & @msekania: What's your opinion on this? |
Hello @lgetwan, Adding flags or mechanisms to circumvent the problem are not my preferred way... I'm going to analyze the logic of the API endpoints (e.g. cmk/gui/plugins/openapi/endpoints/rule/init.py) soon. It should even be possible to programmatically "write" all ansible modules ("parse('endpoints/rule/init.py') -> endpoint_module.py"). But I think I need a newer development vm. I try to get this snippet
to work, but "match" in [https://raw.githubusercontent.com/tribe29/checkmk/627515db4ad05457276325806f1948841382c112/cmk/gui/watolib/rulesets.py] is python3.10 and my Debian 10 has python3.9. I'm interested in the structure of the rulesets and how the API itself is checking against "AllRulesets". @lgetwan Perhaps we should define a "target version" we want the ansible modules to work against (2.1.0pXY.*, python3.10+)? |
Hello and happy new year! |
Well, Ok... that idea would work only for "create", not for "delete". Creating a temporary rule just to get the format correct (and delete both if it exists)... I don't like it... |
@lgetwan I did some more tests and it works quite well, but I have to go now for a few hours. If you can have a look at it, I can make a PR later this evening. I have not tested delete. |
@lgetwan @robin-tribe29 |
@lgetwan @muehlings @robin-tribe29 When I was looking at the source code of ansible's module_utils to see how argument validation works, I discovered Ansible has a 'safe_eval' function to parse string and create python dictionaries. It's a wrapper around AST's literal_eval. It can be found here: https://github.com/ansible/ansible/blob/devel/lib/ansible/module_utils/common/validation.py Unless there is strong advice against it, and since it is already used everywhere in ansible, I propose to modify the rule module to use ansible's safe_eval instead of creating a temp rule. In fact, I already have the code in https://github.com/geof77/ansible-collection-tribe29.checkmk/tree/rule-safe-eval But not tested at all yet... myabe later this evening. What do you think? |
@muehlings we are actually working towards proper support communication. Currently, we state the "tested scenario" for each release in SUPPORT.md. Additionally, the automated tests check compatibility for all current Ansible releases. That means, if you can run one of those Ansible versions, the collection should work too. Of course the next layer of complexity is Checkmk itself, and I do not know how good the current state of affairs is towards transparency regarding compatibility. That being said, I am kind of out of the loop regarding the programming details in here, so I will leave this in the very capable hands of @lgetwan. |
With #241, the need for
is no longer there, I guess. What's your opinion about that, @geof77 and @muehlings? |
this sounds indeed interesting! and thanks for considerably improved rule module! |
@robin-tribe29 @msekania @lgetwan : I was just thinking... is there any use case where we would have several rules
Does it make sense? My understanding is that the first rule matching the conditions would apply and the others would be ignored. If I'm correct, we do not have to compare the value_raw at all and in fact it's not the ideal behavior. So my patches to create a temp rule or use safe_eval to compare value_raw are not necessary... I just stick to the original idea and tried to make it work, but I think it's a bad idea. I was reading about the host module and the way it moves hosts (issue #175). The rule module should behave similarly. Otherwise it would be very difficult to modify rules, we would have to look for the existing rule with the correct value_raw and I see no way to do it easily. So I propose to modify the behavior of the rule module to compare only the ruleset, folder and conditions, and if there is already a rule matching this, we simply delete it and recreate it with the new value_raw. That would be a huge improvement IMHO. |
Yes, I would say that it should behave almost like that, but with an additional check. "Surprisingly", there is no modify or update function for rule in the REST API.
How about introducing a flag that explicitly states that ignoring the contents of "value_raw" is explicitly intended in rule comparison?
I see the problem here:
|
Don't know if that solves all constellations for setting the value_raw option for a rule, but this works for me in all my playbooks so far: setting var for http_test: setting var for credentials (example for mariadb/mysql): In the rule use: Maybe someone in this thread can test this with their own rules. KR, |
Unfortunately it's not so easy, there are several threads where the issues have been discussed extensively, see e.g. #186. One of the main problems for example: how do you enter the python tuple-s, neither JSON nor YAML have this structure. With string conversions one also should take care that one does not have extra One should either in the REST API value_raw stricter or write a convertor module. |
With the next major Checkmk release, we plan to make the API fully JSON-compatible which should rid us of this issue. |
Just my 2 cents (coming from #335): I think without clearly and unambiguously identifying the rule you want to change, no amount of checking title, description, folder, conditions or anything else will work. What if one of these parameters is exactly the one you want to change? So I'd like to propose to add a mandatory parameter to
This ID could be attached with some boilerplate to the description or title field ( This way, you can change any aspect of this rule, even transfer it to another folder. |
Today I tried to convert my existing reference sites to ansible playbooks (read everything with api, construct the yaml).
There were indeed rules where the get() on "disabled" gave a result (probably rules where the rule was enabled and disabled and the information remains in the rule) and then on the other side the default hit and set "" for disabled. Before that change ansible almost always generated the rules again and again. Now unchanged rules stay "ok", changed rules and new rules get "changed" as module status. Can anybody please cross check that? |
Just hit this (long) discussion and some others related as I'm trying to setup a Checkmk instance a completely declarative manner (or better, this is wat I'm asked to). For my basic understanding, this is quite impossible as of today. Another big issue I'm seeing here is that is not possible to define with certainty where a rule will be add on the ruleset. On the first creation, I can add all my rules (hypothetically defined in an inventory list) on the bottom of the ruleset. But after, from day2, how does this going? As the order of appearance matters, how can I define a position that will not change? Other than a some sort of rule "id", I think that also a numeral position inside the ruleset is needed to achieve the goal of idempotency and declarative definition of rules. |
@pandvan the second issue you are mentioning is out of the scope of this issue. But you can control, where rules are created and if you want to be 100% certain of their position, you can look up the existing rules with the new lookup plugins, which we just released. Anyway, regarding this specific aspect, please open a dedicated issue, if you feel like this is something we should discuss. Regarding the main discussion, I have no update yet. |
in issue #523 I described the issue we are facing, which is in fact the same issue as described here. Characters get replaced in value_raw when using ansible. While using the exact same value_raw via Swagger UI, it works as expected. I did read this entire issue, however not really sure what the exact issue is now, or what a workaround for the issue is. in regards of the main discussion, i am not into API/ansible enough to provide any valuable input there. |
So i have fixed the conversion issue by just passing the value_raw as a string to the ansible module: checkmk.general.rule:
automation_secret: "{{ automation_secret }}"
automation_user: "{{ automation_user }}"
rule:
conditions: "{{ item.rule.conditions }}"
properties:
description: "{{ item.rule.properties.description }}"
comment: "{{ item.rule.properties.comment | default() }}"
disabled: "{{ item.rule.properties.disabled | default(False) }}"
documentation_url: "{{ documentation_url }}"
value_raw: "{{ item.rule.value_raw|string }}"
location: "{{ item.rule.location }}"
ruleset: "{{ item.ruleset }}"
server_url: "{{ master_site_baseurl }}"
site: "{{ master_site }}"
loop: "{{ rulesets | flatten(levels=1) }}"
loop_control:
label: "{{ item.ruleset }} [{{ item.rule.properties.description | default() }}]" reading through all the comments above i see this has been provided as a workaround more often, it just disappeared in the amount of comments in this bug. |
I have given up on this. The API is not consistent and the module logic is not consistent. 3 examples:
I work around this with deleting rules.mk and writing the rulesets with ansible again. Without a full compare (ansible module task) and a reliable source of the real rule content (API task) there will be no solution to this problem. |
Describe the bug
I'm trying to set the value of value_raw to a variable instead of hardcoding it in the task, so I can reuse the same task for multiple rules. Unfortunately I get the error "Unsupported type. Field must be string". The same task with the value_raw explicitly set works fine. Seems to be an escaping issue, and I'm not 100% the issue is with the collection honestly.. but I'm banging my head on this so any help is appreciated.
Component Name
tribe29.checkmk.rule
Ansible Version
Checkmk Version
Collection Version
To Reproduce
Steps to reproduce the behavior:
Execute this task:
If I replace
value_raw: "{{ myvariable }}"
tovalue_raw: "{'levels': (80.0, 90.0)}"
the task works fine.Expected behavior
Rule to be created using the value in "myvariable"
Actual behavior
The following error is printed:
Additional context
I suspect the issue is caused by the curly bracket required by the API which make ansible interpret the variable's value as a dictionary instead of a string. But I couldn't find a way to escape that and make it works with the API.
The text was updated successfully, but these errors were encountered: