Debian Codegraph @

lib/ansible/plugins/lookup/random_choice.py

raw
1 # (c) 2013, Michael DeHaan <[email protected]>
2 # (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4 from __future__ import annotations
5
6 DOCUMENTATION = """
7 name: random_choice
8 author: Michael DeHaan
9 version_added: "1.1"
10 short_description: return random element from list
11 description:
12 - The 'random_choice' feature can be used to pick something at random. While it's not a load balancer (there are modules for those),
13 it can somewhat be used as a poor man's load balancer in a MacGyver like situation.
14 - At a more basic level, they can be used to add chaos and excitement to otherwise predictable automation environments.
15 """
16
17 EXAMPLES = """
18 - name: Magic 8 ball for MUDs
19 ansible.builtin.debug:
20 msg: "{{ item }}"
21 with_random_choice:
22 - "go through the door"
23 - "drink from the goblet"
24 - "press the red button"
25 - "do nothing"
26 """
27
28 RETURN = """
29 _raw:
30 description:
31 - random item
32 type: raw
33 """
34 import secrets
35
36 from ansible.errors import AnsibleError
37 from ansible.module_utils.common.text.converters import to_native
38 from ansible.plugins.lookup import LookupBase
39
40
41 class LookupModule(LookupBase):
42
43 def run(self, terms, variables=None, **kwargs):
44
45 ret = terms
46 if terms:
47 try:
48 ret = [secrets.choice(terms)]
49 except Exception as e:
50 raise AnsibleError("Unable to choose random term: %s" % to_native(e))
51
52 return ret