Skip to content
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

make random_choice more error resilient #27380

Merged
merged 3 commits into from
Jul 31, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/ansible/plugins/lookup/random_choice.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

import random

from ansible.errors import AnsibleError
from ansible.module_utils._text import to_native
from ansible.plugins.lookup import LookupBase

# useful for introducing chaos ... or just somewhat reasonably fair selection
Expand All @@ -36,4 +38,11 @@ class LookupModule(LookupBase):

def run(self, terms, inject=None, **kwargs):

return [random.choice(terms)]
ret = terms
if terms:
try:
ret = [random.choice(terms)]
except Exception as e:
raise AnsibleError("Unable to choose random term: %s" % to_native(e))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would requre from ansible.errors import AnsibleError L22.

Copy link
Contributor

@evrardjp evrardjp Jul 28, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would require from ansible.module_utils._text import to_native

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error message could give more constructive feedback:
random requires a non-empty list of elements.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in that case you dont get an error, you skip the task

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see, thanks for the discussion on IRC!


return ret