Debian Codegraph @

ansible_collections/community/general/plugins/modules/pagerduty_user.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2020, Zainab Alsaffar <[email protected]>
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 annotations
8
9 DOCUMENTATION = r"""
10 module: pagerduty_user
11 short_description: Manage a user account on PagerDuty
12 description:
13 - This module manages the creation/removal of a user account on PagerDuty.
14 version_added: '1.3.0'
15 author: Zainab Alsaffar (@zanssa)
16 requirements:
17 - pdpyras python module = 4.1.1
18 - PagerDuty API Access
19 extends_documentation_fragment:
20 - community.general._attributes
21 attributes:
22 check_mode:
23 support: full
24 diff_mode:
25 support: none
26 options:
27 access_token:
28 description:
29 - An API access token to authenticate with the PagerDuty REST API.
30 required: true
31 type: str
32 pd_user:
33 description:
34 - Name of the user in PagerDuty.
35 required: true
36 type: str
37 pd_email:
38 description:
39 - The user's email address.
40 - O(pd_email) is the unique identifier used and cannot be updated using this module.
41 required: true
42 type: str
43 pd_role:
44 description:
45 - The user's role.
46 choices: ['global_admin', 'manager', 'responder', 'observer', 'stakeholder', 'limited_stakeholder', 'restricted_access']
47 default: 'responder'
48 type: str
49 state:
50 description:
51 - State of the user.
52 - On V(present), it creates a user if the user does not exist.
53 - On V(absent), it removes a user if the account exists.
54 choices: ['present', 'absent']
55 default: 'present'
56 type: str
57 pd_teams:
58 description:
59 - The teams to which the user belongs.
60 - Required if O(state=present).
61 type: list
62 elements: str
63 """
64
65 EXAMPLES = r"""
66 - name: Create a user account on PagerDuty
67 community.general.pagerduty_user:
68 access_token: 'Your_Access_token'
69 pd_user: user_full_name
70 pd_email: user_email
71 pd_role: user_pd_role
72 pd_teams: user_pd_teams
73 state: "present"
74
75 - name: Remove a user account from PagerDuty
76 community.general.pagerduty_user:
77 access_token: 'Your_Access_token'
78 pd_user: user_full_name
79 pd_email: user_email
80 state: "absent"
81 """
82
83 RETURN = r""" # """
84
85 from os import path
86
87 from ansible.module_utils.basic import AnsibleModule
88
89 from ansible_collections.community.general.plugins.module_utils import _deps as deps
90
91 with deps.declare("pdpyras", url="https://github.com/PagerDuty/pdpyras"):
92 from pdpyras import APISession, PDClientError
93
94
95 class PagerDutyUser:
96 def __init__(self, module, session):
97 self._module = module
98 self._apisession = session
99
100 # check if the user exists
101 def does_user_exist(self, pd_email):
102 for user in self._apisession.iter_all("users"):
103 if user["email"] == pd_email:
104 return user["id"]
105
106 # create a user account on PD
107 def add_pd_user(self, pd_name, pd_email, pd_role):
108 try:
109 user = self._apisession.persist(
110 "users",
111 "email",
112 {
113 "name": pd_name,
114 "email": pd_email,
115 "type": "user",
116 "role": pd_role,
117 },
118 )
119 return user
120
121 except PDClientError as e:
122 if e.response.status_code == 400:
123 self._module.fail_json(msg=f"Failed to add {pd_name} due to invalid argument")
124 if e.response.status_code == 401:
125 self._module.fail_json(msg=f"Failed to add {pd_name} due to invalid API key")
126 if e.response.status_code == 402:
127 self._module.fail_json(
128 msg=f"Failed to add {pd_name} due to inability to perform the action within the API token"
129 )
130 if e.response.status_code == 403:
131 self._module.fail_json(
132 msg=f"Failed to add {pd_name} due to inability to review the requested resource within the API token"
133 )
134 if e.response.status_code == 429:
135 self._module.fail_json(msg=f"Failed to add {pd_name} due to reaching the limit of making requests")
136
137 # delete a user account from PD
138 def delete_user(self, pd_user_id, pd_name):
139 try:
140 user_path = path.join("/users/", pd_user_id)
141 self._apisession.rdelete(user_path)
142
143 except PDClientError as e:
144 if e.response.status_code == 404:
145 self._module.fail_json(msg=f"Failed to remove {pd_name} as user was not found")
146 if e.response.status_code == 403:
147 self._module.fail_json(
148 msg=f"Failed to remove {pd_name} due to inability to review the requested resource within the API token"
149 )
150 if e.response.status_code == 401:
151 # print out the list of incidents
152 pd_incidents = self.get_incidents_assigned_to_user(pd_user_id)
153 self._module.fail_json(msg=f"Failed to remove {pd_name} as user has assigned incidents {pd_incidents}")
154 if e.response.status_code == 429:
155 self._module.fail_json(msg=f"Failed to remove {pd_name} due to reaching the limit of making requests")
156
157 # get incidents assigned to a user
158 def get_incidents_assigned_to_user(self, pd_user_id):
159 incident_info = {}
160 incidents = self._apisession.list_all("incidents", params={"user_ids[]": [pd_user_id]})
161
162 for incident in incidents:
163 incident_info = {"title": incident["title"], "key": incident["incident_key"], "status": incident["status"]}
164 return incident_info
165
166 # add a user to a team/teams
167 def add_user_to_teams(self, pd_user_id, pd_teams, pd_role):
168 updated_team = None
169 for team in pd_teams:
170 team_info = self._apisession.find("teams", team, attribute="name")
171 if team_info is not None:
172 try:
173 updated_team = self._apisession.rput(
174 f"/teams/{team_info['id']}/users/{pd_user_id}", json={"role": pd_role}
175 )
176 except PDClientError:
177 updated_team = None
178 return updated_team
179
180
181 def main():
182 module = AnsibleModule(
183 argument_spec=dict(
184 access_token=dict(type="str", required=True, no_log=True),
185 pd_user=dict(type="str", required=True),
186 pd_email=dict(type="str", required=True),
187 state=dict(type="str", default="present", choices=["present", "absent"]),
188 pd_role=dict(
189 type="str",
190 default="responder",
191 choices=[
192 "global_admin",
193 "manager",
194 "responder",
195 "observer",
196 "stakeholder",
197 "limited_stakeholder",
198 "restricted_access",
199 ],
200 ),
201 pd_teams=dict(type="list", elements="str"),
202 ),
203 required_if=[
204 ["state", "present", ["pd_teams"]],
205 ],
206 supports_check_mode=True,
207 )
208
209 deps.validate(module)
210
211 access_token = module.params["access_token"]
212 pd_user = module.params["pd_user"]
213 pd_email = module.params["pd_email"]
214 state = module.params["state"]
215 pd_role = module.params["pd_role"]
216 pd_teams = module.params["pd_teams"]
217
218 if pd_role:
219 pd_role_gui_value = {
220 "global_admin": "admin",
221 "manager": "user",
222 "responder": "limited_user",
223 "observer": "observer",
224 "stakeholder": "read_only_user",
225 "limited_stakeholder": "read_only_limited_user",
226 "restricted_access": "restricted_access",
227 }
228 pd_role = pd_role_gui_value[pd_role]
229
230 # authenticate with PD API
231 try:
232 session = APISession(access_token)
233 except PDClientError as e:
234 module.fail_json(msg=f"Failed to authenticate with PagerDuty: {e}")
235
236 user = PagerDutyUser(module, session)
237
238 user_exists = user.does_user_exist(pd_email)
239
240 if user_exists:
241 if state == "absent":
242 # remove user
243 if not module.check_mode:
244 user.delete_user(user_exists, pd_user)
245 module.exit_json(changed=True, result=f"Successfully deleted user {pd_user}")
246 else:
247 module.exit_json(changed=False, result=f"User {pd_user} already exists.")
248
249 # in case that the user does not exist
250 else:
251 if state == "absent":
252 module.exit_json(changed=False, result=f"User {pd_user} was not found.")
253
254 else:
255 # add user, adds user with the default notification rule and contact info (email)
256 if not module.check_mode:
257 user.add_pd_user(pd_user, pd_email, pd_role)
258 # get user's id
259 pd_user_id = user.does_user_exist(pd_email)
260 # add a user to the team/s
261 user.add_user_to_teams(pd_user_id, pd_teams, pd_role)
262 module.exit_json(changed=True, result=f"Successfully created & added user {pd_user} to team {pd_teams}")
263
264
265 if __name__ == "__main__":
266 main()