Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # (c) 2022, Brian Scholer (@briantist)
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import (absolute_import, division, print_function)
8 __metaclass__ = type
9
10 DOCUMENTATION = """
11 module: vault_token_create
12 version_added: 2.3.0
13 author:
14 - Brian Scholer (@briantist)
15 short_description: Create a HashiCorp Vault token
16 requirements:
17 - C(hvac) (L(Python library,https://hvac.readthedocs.io/en/stable/overview.html))
18 - For detailed requirements, see R(the collection requirements page,ansible_collections.community.hashi_vault.docsite.user_guide.requirements).
19 description:
20 - Creates a token in HashiCorp Vault, returning the response, including the token.
21 seealso:
22 - ref: community.hashi_vault.vault_token_create lookup <ansible_collections.community.hashi_vault.vault_token_create_lookup>
23 description: The official documentation for the C(community.hashi_vault.vault_token_create) lookup plugin.
24 - module: community.hashi_vault.vault_login
25 - ref: community.hashi_vault.vault_login lookup <ansible_collections.community.hashi_vault.vault_login_lookup>
26 description: The official documentation for the C(community.hashi_vault.vault_login) lookup plugin.
27 - ref: community.hashi_vault.vault_login_token filter <ansible_collections.community.hashi_vault.vault_login_token_filter>
28 description: The official documentation for the C(community.hashi_vault.vault_login_token) filter plugin.
29 extends_documentation_fragment:
30 - community.hashi_vault.attributes
31 - community.hashi_vault.attributes.action_group
32 - community.hashi_vault.connection
33 - community.hashi_vault.auth
34 - community.hashi_vault.token_create
35 - community.hashi_vault.wrapping
36 notes:
37 - Token creation is a write operation (creating a token persisted to storage), so this module always reports C(changed=True).
38 - For the purposes of Ansible playbooks however,
39 it may be more useful to set I(changed_when=false) if you are doing idempotency checks against the target system.
40 attributes:
41 check_mode:
42 support: partial
43 details:
44 - In check mode, this module will not create a token, and will instead return a basic structure with an empty token.
45 However, this may not be useful if the token is required for follow on tasks.
46 - It may be better to use this module with I(check_mode=false) in order to have a valid token that can be used.
47 options: {}
48 """
49
50 EXAMPLES = """
51 - name: Login via userpass and create a child token
52 community.hashi_vault.vault_token_create:
53 url: https://vault:8201
54 auth_method: userpass
55 username: user
56 password: '{{ passwd }}'
57 register: token_data
58
59 - name: Retrieve an approle role ID using the child token (token via filter)
60 community.hashi_vault.vault_read:
61 url: https://vault:8201
62 auth_method: token
63 token: '{{ token_data | community.hashi_vault.vault_login_token }}'
64 path: auth/approle/role/role-name/role-id
65 register: approle_id
66
67 - name: Retrieve an approle role ID using the child token (token via direct dict access)
68 community.hashi_vault.vault_read:
69 url: https://vault:8201
70 auth_method: token
71 token: '{{ token_data.login.auth.client_token }}'
72 path: auth/approle/role/role-name/role-id
73 register: approle_id
74
75 # implicitly uses token auth with a token from the environment
76 - name: Create an orphaned token with a short TTL
77 community.hashi_vault.vault_token_create:
78 url: https://vault:8201
79 orphan: true
80 ttl: 60s
81 register: token_data
82
83 - name: Display the full response
84 ansible.builtin.debug:
85 var: token_data.login
86 """
87
88 RETURN = """
89 login:
90 description: The result of the token creation operation.
91 returned: success
92 type: dict
93 sample:
94 auth:
95 client_token: s.rlwajI2bblHAWU7uPqZhLru3
96 data: null
97 contains:
98 auth:
99 description: The C(auth) member of the token response.
100 returned: success
101 type: dict
102 contains:
103 client_token:
104 description: Contains the newly created token.
105 returned: success
106 type: str
107 data:
108 description: The C(data) member of the token response.
109 returned: success, when available
110 type: dict
111 """
112
113 import traceback
114
115 from ansible.module_utils.common.text.converters import to_text
116
117 from ansible_collections.community.hashi_vault.plugins.module_utils._hashi_vault_module import HashiVaultModule
118 from ansible_collections.community.hashi_vault.plugins.module_utils._hashi_vault_common import HashiVaultValueError
119
120
121 PASS_THRU_OPTION_NAMES = [
122 'no_parent',
123 'no_default_policy',
124 'policies',
125 'id',
126 'role_name',
127 'meta',
128 'renewable',
129 'ttl',
130 'type',
131 'explicit_max_ttl',
132 'display_name',
133 'num_uses',
134 'period',
135 'entity_alias',
136 'wrap_ttl',
137 ]
138
139
140 ORPHAN_OPTION_TRANSLATION = {
141 'id': 'token_id',
142 'role_name': 'role',
143 'type': 'token_type',
144 }
145
146
147 def run_module():
148 argspec = HashiVaultModule.generate_argspec(
149 orphan=dict(type='bool', default=False),
150 no_parent=dict(type='bool'),
151 no_default_policy=dict(type='bool'),
152 policies=dict(type='list', elements='str'),
153 id=dict(type='str'),
154 role_name=dict(type='str'),
155 meta=dict(type='dict'),
156 renewable=dict(type='bool'),
157 ttl=dict(type='str'),
158 type=dict(type='str', choices=['batch', 'service']),
159 explicit_max_ttl=dict(type='str'),
160 display_name=dict(type='str'),
161 num_uses=dict(type='int'),
162 period=dict(type='str'),
163 entity_alias=dict(type='str'),
164 wrap_ttl=dict(type='str'),
165 )
166
167 module = HashiVaultModule(
168 argument_spec=argspec,
169 supports_check_mode=True
170 )
171
172 module.connection_options.process_connection_options()
173 client_args = module.connection_options.get_hvac_connection_options()
174 client = module.helper.get_vault_client(**client_args)
175
176 try:
177 module.authenticator.validate()
178 module.authenticator.authenticate(client)
179 except (NotImplementedError, HashiVaultValueError) as e:
180 module.fail_json(msg=to_text(e), exception=traceback.format_exc())
181
182 pass_thru_options = module.adapter.get_filled_options(*PASS_THRU_OPTION_NAMES)
183
184 orphan_options = pass_thru_options.copy()
185
186 for key in pass_thru_options.keys():
187 if key in ORPHAN_OPTION_TRANSLATION:
188 orphan_options[ORPHAN_OPTION_TRANSLATION[key]] = orphan_options.pop(key)
189
190 # token creation is a write operation, using storage and resources
191 changed = True
192 response = None
193
194 if module.check_mode:
195 module.exit_json(changed=changed, login={'auth': {'client_token': None}})
196
197 if module.adapter.get_option('orphan'):
198 try:
199 try:
200 # this method was added in hvac 1.0.0
201 # See: https://github.com/hvac/hvac/pull/869
202 response = client.auth.token.create_orphan(**orphan_options)
203 except AttributeError:
204 # this method was removed in hvac 1.0.0
205 # See: https://github.com/hvac/hvac/issues/758
206 response = client.create_token(orphan=True, **orphan_options)
207 except Exception as e:
208 module.fail_json(msg=to_text(e), exception=traceback.format_exc())
209 else:
210 try:
211 response = client.auth.token.create(**pass_thru_options)
212 except Exception as e:
213 module.fail_json(msg=to_text(e), exception=traceback.format_exc())
214
215 module.exit_json(changed=changed, login=response)
216
217
218 def main():
219 run_module()
220
221
222 if __name__ == '__main__':
223 main()