Debian Codegraph @

ansible_collections/community/hashi_vault/plugins/lookup/vault_token_create.py

raw
1 # (c) 2022, Brian Scholer (@briantist)
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 from __future__ import (absolute_import, division, print_function)
6 __metaclass__ = type
7
8 DOCUMENTATION = """
9 name: vault_token_create
10 version_added: 2.3.0
11 author:
12 - Brian Scholer (@briantist)
13 short_description: Create a HashiCorp Vault token
14 requirements:
15 - C(hvac) (L(Python library,https://hvac.readthedocs.io/en/stable/overview.html))
16 - For detailed requirements, see R(the collection requirements page,ansible_collections.community.hashi_vault.docsite.user_guide.requirements).
17 description:
18 - Creates a token in HashiCorp Vault, returning the response, including the token.
19 seealso:
20 - module: community.hashi_vault.vault_token_create
21 - ref: community.hashi_vault.vault_login lookup <ansible_collections.community.hashi_vault.vault_login_lookup>
22 description: The official documentation for the C(community.hashi_vault.vault_login) lookup plugin.
23 - module: community.hashi_vault.vault_login
24 - ref: community.hashi_vault.vault_login_token filter <ansible_collections.community.hashi_vault.vault_login_token_filter>
25 description: The official documentation for the C(community.hashi_vault.vault_login_token) filter plugin.
26 notes:
27 - Token creation is a write operation (creating a token persisted to storage), so this module always reports C(changed=True).
28 - For the purposes of Ansible playbooks however,
29 it may be more useful to set I(changed_when=false) if you are doing idempotency checks against the target system.
30 - In check mode, this module will not create a token, and will instead return a basic structure with an empty token.
31 However, this may not be useful if the token is required for follow on tasks.
32 It may be better to use this module with I(check_mode=false) in order to have a valid token that can be used.
33 extends_documentation_fragment:
34 - community.hashi_vault.connection
35 - community.hashi_vault.connection.plugins
36 - community.hashi_vault.auth
37 - community.hashi_vault.auth.plugins
38 - community.hashi_vault.token_create
39 - community.hashi_vault.wrapping
40 - community.hashi_vault.wrapping.plugins
41 options:
42 _terms:
43 description: This is unused and any terms supplied will be ignored.
44 type: str
45 required: false
46 """
47
48 EXAMPLES = """
49 - name: Login via userpass and create a child token
50 ansible.builtin.set_fact:
51 token_data: "{{ lookup('community.hashi_vault.vault_token_create', url='https://vault', auth_method='userpass', username=user, password=passwd) }}"
52
53 - name: Retrieve an approle role ID using the child token (token via filter)
54 community.hashi_vault.vault_read:
55 url: https://vault:8201
56 auth_method: token
57 token: '{{ token_data | community.hashi_vault.vault_login_token }}'
58 path: auth/approle/role/role-name/role-id
59 register: approle_id
60
61 - name: Retrieve an approle role ID (token via direct dict access)
62 community.hashi_vault.vault_read:
63 url: https://vault:8201
64 auth_method: token
65 token: '{{ token_data.auth.client_token }}'
66 path: auth/approle/role/role-name/role-id
67 register: approle_id
68
69 # implicitly uses url & token auth with a token from the environment
70 - name: Create an orphaned token with a short TTL and display the full response
71 ansible.builtin.debug:
72 var: lookup('community.hashi_vault.vault_token_create', orphan=True, ttl='60s')
73 """
74
75 RETURN = """
76 _raw:
77 description: The result of the token creation operation.
78 returned: success
79 type: dict
80 sample:
81 auth:
82 client_token: s.rlwajI2bblHAWU7uPqZhLru3
83 data: null
84 contains:
85 auth:
86 description: The C(auth) member of the token response.
87 returned: success
88 type: dict
89 contains:
90 client_token:
91 description: Contains the newly created token.
92 returned: success
93 type: str
94 data:
95 description: The C(data) member of the token response.
96 returned: success, when available
97 type: dict
98 """
99
100 from ansible.errors import AnsibleError
101 from ansible.utils.display import Display
102
103 from ...plugins.plugin_utils._hashi_vault_lookup_base import HashiVaultLookupBase
104 from ...plugins.module_utils._hashi_vault_common import HashiVaultValueError
105
106 display = Display()
107
108
109 class LookupModule(HashiVaultLookupBase):
110 PASS_THRU_OPTION_NAMES = [
111 'no_parent',
112 'no_default_policy',
113 'policies',
114 'id',
115 'role_name',
116 'meta',
117 'renewable',
118 'ttl',
119 'type',
120 'explicit_max_ttl',
121 'display_name',
122 'num_uses',
123 'period',
124 'entity_alias',
125 'wrap_ttl',
126 ]
127
128 ORPHAN_OPTION_TRANSLATION = {
129 'id': 'token_id',
130 'role_name': 'role',
131 'type': 'token_type',
132 }
133
134 def run(self, terms, variables=None, **kwargs):
135 self.set_options(direct=kwargs, var_options=variables)
136 # TODO: remove process_deprecations() if backported fix is available (see method definition)
137 self.process_deprecations()
138
139 self.connection_options.process_connection_options()
140 client_args = self.connection_options.get_hvac_connection_options()
141 client = self.helper.get_vault_client(**client_args)
142
143 if len(terms) != 0:
144 display.warning("Supplied term strings will be ignored. This lookup does not use term strings.")
145
146 try:
147 self.authenticator.validate()
148 self.authenticator.authenticate(client)
149 except (NotImplementedError, HashiVaultValueError) as e:
150 raise AnsibleError(e)
151
152 pass_thru_options = self._options_adapter.get_filled_options(*self.PASS_THRU_OPTION_NAMES)
153
154 orphan_options = pass_thru_options.copy()
155
156 for key in pass_thru_options.keys():
157 if key in self.ORPHAN_OPTION_TRANSLATION:
158 orphan_options[self.ORPHAN_OPTION_TRANSLATION[key]] = orphan_options.pop(key)
159
160 response = None
161
162 if self.get_option('orphan'):
163 try:
164 try:
165 # this method was added in hvac 1.0.0
166 # See: https://github.com/hvac/hvac/pull/869
167 response = client.auth.token.create_orphan(**orphan_options)
168 except AttributeError:
169 # this method was removed in hvac 1.0.0
170 # See: https://github.com/hvac/hvac/issues/758
171 response = client.create_token(orphan=True, **orphan_options)
172 except Exception as e:
173 raise AnsibleError(e)
174 else:
175 try:
176 response = client.auth.token.create(**pass_thru_options)
177 except Exception as e:
178 raise AnsibleError(e)
179
180 return [response]