Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # (c) 2023, Devon Mar (@devon-mar)
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
9 __metaclass__ = type
10
11 DOCUMENTATION = """
12 module: vault_kv2_write
13 version_added: 4.2.0
14 author:
15 - Devon Mar (@devon-mar)
16 short_description: Perform a write operation against a KVv2 secret in HashiCorp Vault
17 description:
18 - Perform a write operation against a KVv2 secret in HashiCorp Vault.
19 requirements:
20 - C(hvac) (L(Python library,https://hvac.readthedocs.io/en/stable/overview.html))
21 - For detailed requirements, see R(the collection requirements page,ansible_collections.community.hashi_vault.docsite.user_guide.requirements).
22 seealso:
23 - module: community.hashi_vault.vault_write
24 - module: community.hashi_vault.vault_kv2_get
25 - module: community.hashi_vault.vault_kv2_delete
26 - ref: community.hashi_vault.vault_write lookup <ansible_collections.community.hashi_vault.vault_write_lookup>
27 description: The official documentation for the C(community.hashi_vault.vault_write) lookup plugin.
28 - name: KV2 Secrets Engine
29 description: Documentation for the Vault KV secrets engine, version 2.
30 link: https://www.vaultproject.io/docs/secrets/kv/kv-v2
31 extends_documentation_fragment:
32 - community.hashi_vault.attributes
33 - community.hashi_vault.attributes.action_group
34 - community.hashi_vault.connection
35 - community.hashi_vault.auth
36 - community.hashi_vault.engine_mount
37 attributes:
38 check_mode:
39 support: partial
40 details:
41 - If I(read_before_write) is C(true), full check mode functionality is supported.
42 - If I(read_before_write) is C(false), the status will always be C(changed) but a write will not be performed in check mode.
43 options:
44 engine_mount_point:
45 type: str
46 default: secret
47 path:
48 type: str
49 required: true
50 description:
51 - Vault KVv2 path to be written to.
52 - This is relative to the I(engine_mount_point), so the mount path should not be included.
53 data:
54 type: dict
55 required: true
56 description:
57 - KVv2 secret data to write.
58 cas:
59 type: int
60 description:
61 - Perform a check-and-set operation.
62 read_before_write:
63 type: bool
64 default: false
65 description:
66 - Read the secret first and write only when I(data) differs from the read data.
67 - Requires C(read) permission on the secret if C(true).
68 - If C(false), this module will always write to I(path) when not in check mode.
69 """
70
71 EXAMPLES = r"""
72 - name: Write/create a secret
73 community.hashi_vault.vault_kv2_write:
74 url: https://vault:8200
75 path: hello
76 data:
77 foo: bar
78
79 - name: Create a secret with CAS (the secret must not exist)
80 community.hashi_vault.vault_kv2_write:
81 url: https://vault:8200
82 path: caspath
83 cas: 0
84 data:
85 foo: bar
86
87 - name: Update a secret with CAS
88 community.hashi_vault.vault_kv2_write:
89 url: https://vault:8200
90 path: caspath
91 cas: 2
92 data:
93 hello: world
94
95 # This module does not have patch capability built in.
96 # Patching can be achieved with multiple tasks.
97
98 - name: Retrieve current secret
99 register: current
100 community.hashi_vault.vault_kv2_get:
101 url: https://vault:8200
102 path: hello
103
104 ## patch without CAS
105 - name: Update the secret
106 vars:
107 values_to_update:
108 foo: baz
109 hello: goodbye
110 community.hashi_vault.vault_kv2_write:
111 url: https://vault:8200
112 path: hello
113 data: >-
114 {{
115 current.secret
116 | combine(values_to_update)
117 }}
118
119 ## patch with CAS
120 - name: Update the secret
121 vars:
122 values_to_update:
123 foo: baz
124 hello: goodbye
125 community.hashi_vault.vault_kv2_write:
126 url: https://vault:8200
127 path: hello
128 cas: '{{ current.metadata.version | int }}'
129 data: >-
130 {{
131 current.secret
132 | combine(values_to_update)
133 }}
134 """
135
136 RETURN = r"""
137 raw:
138 type: dict
139 description: The raw Vault response.
140 returned: changed
141 sample:
142 auth:
143 data:
144 created_time: "2023-02-21T19:51:50.801757862Z"
145 custom_metadata:
146 deletion_time: ""
147 destroyed: false
148 version: 1
149 lease_duration: 0
150 lease_id: ""
151 renewable: false
152 request_id: 52eb1aa7-5a38-9a02-9246-efc5bf9581ec
153 warnings: null
154 wrap_info: null
155 """
156
157 import traceback
158
159 from ansible.module_utils.common.text.converters import to_text
160 from ..module_utils._hashi_vault_module import HashiVaultModule
161 from ..module_utils._hashi_vault_common import HashiVaultValueError
162
163
164 def run_module():
165 argspec = HashiVaultModule.generate_argspec(
166 engine_mount_point=dict(type="str", default="secret"),
167 path=dict(type="str", required=True),
168 data=dict(type="dict", required=True, no_log=True),
169 cas=dict(type="int"),
170 read_before_write=dict(type="bool", default=False),
171 )
172
173 module = HashiVaultModule(
174 argument_spec=argspec,
175 supports_check_mode=True,
176 )
177
178 mount_point = module.params.get("engine_mount_point")
179 path = module.params.get("path")
180 cas = module.params.get("cas")
181 data = module.params.get("data")
182 read_before_write = module.params.get("read_before_write")
183
184 module.connection_options.process_connection_options()
185 client_args = module.connection_options.get_hvac_connection_options()
186 client = module.helper.get_vault_client(**client_args)
187 hvac_exceptions = module.helper.get_hvac().exceptions
188
189 try:
190 module.authenticator.validate()
191 module.authenticator.authenticate(client)
192 except (NotImplementedError, HashiVaultValueError) as e:
193 module.fail_json(msg=to_text(e), exception=traceback.format_exc())
194
195 if read_before_write is True:
196 try:
197 response = client.secrets.kv.v2.read_secret_version(
198 path=path, mount_point=mount_point
199 )
200 if "data" not in response or "data" not in response["data"]:
201 module.fail_json(
202 msg="Vault response did not contain data: %s" % response
203 )
204 current_data = response["data"]["data"]
205 except hvac_exceptions.InvalidPath:
206 current_data = {}
207 except hvac_exceptions.Forbidden:
208 module.fail_json(
209 msg="Permission denied reading %s" % path,
210 exception=traceback.format_exc(),
211 )
212 except hvac_exceptions.VaultError:
213 module.fail_json(
214 msg="VaultError reading %s" % path,
215 exception=traceback.format_exc(),
216 )
217 else:
218 current_data = {}
219
220 changed = current_data != data
221
222 if changed is True and module.check_mode is False:
223 args = {
224 "path": path,
225 "secret": data,
226 "mount_point": mount_point,
227 }
228 if cas is not None:
229 args["cas"] = cas
230
231 try:
232 raw = client.secrets.kv.v2.create_or_update_secret(**args)
233 except hvac_exceptions.InvalidRequest:
234 module.fail_json(
235 msg="InvalidRequest writing to '%s'" % path,
236 exception=traceback.format_exc(),
237 )
238 except hvac_exceptions.InvalidPath:
239 module.fail_json(
240 msg="InvalidPath writing to '%s'" % path,
241 exception=traceback.format_exc(),
242 )
243 except hvac_exceptions.Forbidden:
244 module.fail_json(
245 msg="Permission denied writing to '%s'" % path,
246 exception=traceback.format_exc(),
247 )
248
249 module.exit_json(changed=True, raw=raw)
250
251 module.exit_json(changed=changed)
252
253
254 def main():
255 run_module()
256
257
258 if __name__ == "__main__":
259 main()