Debian Codegraph @

lib/ansible/plugins/lookup/env.py

raw
1 # (c) 2012, Jan-Piet Mens <jpmens(at)gmail.com>
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: env
8 author: Jan-Piet Mens (@jpmens) <jpmens(at)gmail.com>
9 version_added: "0.9"
10 short_description: Read the value of environment variables
11 description:
12 - Allows you to query the environment variables available on the
13 controller when you invoked Ansible.
14 positional: _terms
15 options:
16 _terms:
17 description:
18 - Environment variable or list of them to lookup the values for.
19 required: True
20 default:
21 description: What return when the variable is undefined
22 type: raw
23 default: ''
24 version_added: '2.13'
25 notes:
26 - You can pass the C(Undefined) object as O(default) to force an undefined error
27 """
28
29 EXAMPLES = """
30 - name: Basic usage
31 ansible.builtin.debug:
32 msg: "'{{ lookup('ansible.builtin.env', 'HOME') }}' is the HOME environment variable."
33
34 - name: Before 2.13, how to set default value if the variable is not defined
35 ansible.builtin.debug:
36 msg: "Hello {{ lookup('ansible.builtin.env', 'UNDEFINED_VARIABLE') | default('World', True) }}"
37
38 - name: Example how to set default value if the variable is not defined
39 ansible.builtin.debug:
40 msg: "Hello {{ lookup('ansible.builtin.env', 'UNDEFINED_VARIABLE', default='World') }}"
41
42 - name: Fail if the variable is not defined by setting default value to 'undef()'
43 ansible.builtin.debug:
44 msg: "Hello {{ lookup('ansible.builtin.env', 'UNDEFINED_VARIABLE', default=undef()) }}"
45 """
46
47 RETURN = """
48 _list:
49 description:
50 - Values from the environment variables.
51 type: list
52 """
53
54 import os
55
56
57 from ansible.plugins.lookup import LookupBase
58 from ansible._internal._templating._jinja_bits import _undef, _DEFAULT_UNDEF
59 from ansible._internal._datatag._tags import Origin
60
61
62 class LookupModule(LookupBase):
63 accept_args_markers = True # the `default` arg can accept undefined values
64
65 def run(self, terms, variables=None, **kwargs):
66 self.set_options(var_options=variables, direct=kwargs)
67
68 ret = []
69 d = self.get_option('default')
70
71 for term in terms:
72 var = term.split()[0]
73 val = os.environ.get(var, d)
74
75 if val is _DEFAULT_UNDEF:
76 val = _undef(f'The environment variable {var!r} is not set.')
77 else:
78 val = Origin(description=f"<environment variable {var!r}>").try_tag(val)
79
80 ret.append(val)
81
82 return ret