Debian Codegraph @

ansible_collections/purestorage/flashblade/plugins/modules/purefb_apiclient.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2021, Simon Dodsley ([email protected])
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 ANSIBLE_METADATA = {
12 "metadata_version": "1.1",
13 "status": ["preview"],
14 "supported_by": "community",
15 }
16
17 DOCUMENTATION = r"""
18 ---
19 module: purefb_apiclient
20 version_added: '1.6.0'
21 short_description: Manage FlashBlade API Clients
22 description:
23 - Enable or disable FlashBlade API Clients
24 author:
25 - Pure Storage Ansible Team (@sdodsley) <[email protected]>
26 options:
27 name:
28 description:
29 - Name of the API Client
30 type: str
31 required: true
32 state:
33 description:
34 - Define whether the API client should exist or not.
35 default: present
36 choices: [ absent, present ]
37 type: str
38 role:
39 description:
40 - The maximum role allowed for ID Tokens issued by this API client
41 type: str
42 choices: [readonly, ops_admin, storage_admin, array_admin]
43 issuer:
44 description:
45 - The name of the identity provider that will be issuing ID Tokens for this API client
46 - If not specified, defaults to the API client name, I(name).
47 type: str
48 public_key:
49 description:
50 - The API clients PEM formatted (Base64 encoded) RSA public key.
51 - Include the I(—–BEGIN PUBLIC KEY—–) and I(—–END PUBLIC KEY—–) lines
52 type: str
53 token_ttl:
54 description:
55 - Time To Live length in seconds for the exchanged access token
56 - Range is 1 second to 1 day (86400 seconds)
57 type: int
58 default: 86400
59 enabled:
60 description:
61 - State of the API Client Key
62 type: bool
63 default: true
64 extends_documentation_fragment:
65 - purestorage.flashblade.purestorage.fb
66 """
67
68 EXAMPLES = r"""
69 - name: Create API token ansible-token
70 purestorage.flashblade.purefb_apiclient:
71 name: ansible_token
72 issuer: "Pure_Storage"
73 token_ttl: 3000
74 role: array_admin
75 public_key: "{{lookup('file', 'public_pem_file') }}"
76 fb_url: 10.10.10.2
77 api_token: T-68618f31-0c9e-4e57-aa44-5306a2cf10e3
78
79 - name: Disable API CLient
80 purestorage.flashblade.purefb_apiclient:
81 name: ansible_token
82 enabled: false
83 fb_url: 10.10.10.2
84 api_token: T-68618f31-0c9e-4e57-aa44-5306a2cf10e3
85
86 - name: Enable API CLient
87 purestorage.flashblade.purefb_apiclient:
88 name: ansible_token
89 enabled: true
90 fb_url: 10.10.10.2
91 api_token: T-68618f31-0c9e-4e57-aa44-5306a2cf10e3
92
93 - name: Delete API Client
94 purestorage.flashblade.purefb_apiclient:
95 state: absent
96 name: ansible_token
97 fb_url: 10.10.10.2
98 api_token: T-68618f31-0c9e-4e57-aa44-5306a2cf10e3
99 """
100
101 RETURN = r"""
102 """
103
104 HAS_PURESTORAGE = True
105 try:
106 from pypureclient.flashblade import ApiClient, ApiClientsPost, ReferenceWritable
107 except ImportError:
108 HAS_PURESTORAGE = False
109
110 import re
111 from ansible.module_utils.basic import AnsibleModule
112 from ansible_collections.purestorage.flashblade.plugins.module_utils.purefb import (
113 get_system,
114 purefb_argument_spec,
115 )
116
117
118 def delete_client(module, blade):
119 changed = True
120 if not module.check_mode:
121 res = blade.delete_api_clients(names=[module.params["name"]])
122 if res.status_code != 200:
123 module.fail_json(
124 msg="Failed to delete API Client {0}".format(module.params["name"])
125 )
126 module.exit_json(changed=changed)
127
128
129 def update_client(module, blade, client):
130 """Update API Client"""
131 changed = False
132 if client.enabled != module.params["enabled"]:
133 changed = True
134 if not module.check_mode:
135 res = blade.patch_api_clients(
136 names=[module.params["name"]],
137 api_clients=ApiClient(enabled=module.params["enabled"]),
138 )
139 if res.status_code != 200:
140 module.fail_json(
141 msg="Failed to update API Client {0}".format(module.params["name"])
142 )
143 module.exit_json(changed=changed)
144
145
146 def create_client(module, blade):
147 """Create API Client"""
148 changed = True
149 if not module.params["public_key"]:
150 module.fail_json(msg="public_key is required to create an API Client")
151 if not 1 <= module.params["token_ttl"] <= 86400:
152 module.fail_json(msg="token_ttl parameter is out of range (1 to 86400)")
153 else:
154 token_ttl = module.params["token_ttl"] * 1000
155 if not module.params["issuer"]:
156 module.params["issuer"] = module.params["name"]
157 if not module.check_mode:
158 api_client = ApiClientsPost(
159 max_role=ReferenceWritable(name=module.params["role"]),
160 issuer=module.params["issuer"],
161 access_token_ttl_in_ms=token_ttl,
162 public_key=module.params["public_key"],
163 )
164 res = blade.post_api_clients(
165 names=[module.params["name"]], api_client=api_client
166 )
167 if res.status_code != 200:
168 module.fail_json(
169 msg="Failed to create API Client {0}. Error message: {1}".format(
170 module.params["name"], res.errors[0].message
171 )
172 )
173 if module.params["enabled"]:
174 attr = ApiClient(enabled=True)
175 res = blade.patch_api_clients(
176 api_clients=attr, names=[module.params["name"]]
177 )
178 if res.status_code != 200:
179 module.warn(
180 "API Client {0} created by enable failed. Please investigate.".format(
181 module.params["name"]
182 )
183 )
184 module.exit_json(changed=changed)
185
186
187 def main():
188 argument_spec = purefb_argument_spec()
189 argument_spec.update(
190 dict(
191 state=dict(type="str", default="present", choices=["absent", "present"]),
192 enabled=dict(type="bool", default=True),
193 name=dict(type="str", required=True),
194 role=dict(
195 type="str",
196 choices=["readonly", "ops_admin", "storage_admin", "array_admin"],
197 ),
198 public_key=dict(type="str", no_log=True),
199 token_ttl=dict(type="int", default=86400, no_log=False),
200 issuer=dict(type="str"),
201 )
202 )
203
204 module = AnsibleModule(argument_spec, supports_check_mode=True)
205 pattern = re.compile("^[a-zA-Z0-9]([a-zA-Z0-9_]{0,54}[a-zA-Z0-9])?$")
206 if module.params["issuer"]:
207 if not pattern.match(module.params["issuer"]):
208 module.fail_json(
209 msg="API Client Issuer name {0} does not conform to required naming convention".format(
210 module.params["issuer"]
211 )
212 )
213 if not pattern.match(module.params["name"]):
214 module.fail_json(
215 msg="Object Store Virtual Host name {0} does not conform to required naming convention".format(
216 module.params["name"]
217 )
218 )
219 if not HAS_PURESTORAGE:
220 module.fail_json(msg="py-pure-client sdk is required for this module")
221
222 blade = get_system(module)
223 state = module.params["state"]
224
225 exists = bool(
226 blade.get_api_clients(names=[module.params["name"]]).status_code == 200
227 )
228 if exists:
229 client = list(blade.get_api_clients(names=[module.params["name"]]).items)[0]
230
231 if not exists and state == "present":
232 create_client(module, blade)
233 elif exists and state == "present":
234 update_client(module, blade, client)
235 elif exists and state == "absent":
236 delete_client(module, blade)
237
238 module.exit_json(changed=False)
239
240
241 if __name__ == "__main__":
242 main()