Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2014-2015, Epic Games, Inc.
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: circonus_annotation
11 short_description: Create an annotation in Circonus
12 description:
13 - Create an annotation event with a given category, title and description. Optionally start, end or durations can be provided.
14 author: "Nick Harring (@NickatEpic)"
15 requirements:
16 - requests >= 2.0.0
17 extends_documentation_fragment:
18 - community.general._attributes
19 attributes:
20 check_mode:
21 support: none
22 diff_mode:
23 support: none
24 options:
25 api_key:
26 type: str
27 description:
28 - Circonus API key.
29 required: true
30 category:
31 type: str
32 description:
33 - Annotation Category.
34 required: true
35 description:
36 type: str
37 description:
38 - Description of annotation.
39 required: true
40 title:
41 type: str
42 description:
43 - Title of annotation.
44 required: true
45 start:
46 type: int
47 description:
48 - Unix timestamp of event start.
49 - If not specified, it defaults to "now".
50 stop:
51 type: int
52 description:
53 - Unix timestamp of event end.
54 - If not specified, it defaults to "now" + O(duration).
55 duration:
56 type: int
57 description:
58 - Duration in seconds of annotation.
59 default: 0
60 """
61 EXAMPLES = r"""
62 - name: Create a simple annotation event with a source, defaults to start and end time of now
63 community.general.circonus_annotation:
64 api_key: XXXXXXXXXXXXXXXXX
65 title: App Config Change
66 description: This is a detailed description of the config change
67 category: This category groups like annotations
68
69 - name: Create an annotation with a duration of 5 minutes and a default start time of now
70 community.general.circonus_annotation:
71 api_key: XXXXXXXXXXXXXXXXX
72 title: App Config Change
73 description: This is a detailed description of the config change
74 category: This category groups like annotations
75 duration: 300
76
77 - name: Create an annotation with a start_time and end_time
78 community.general.circonus_annotation:
79 api_key: XXXXXXXXXXXXXXXXX
80 title: App Config Change
81 description: This is a detailed description of the config change
82 category: This category groups like annotations
83 start_time: 1395940006
84 end_time: 1395954407
85 """
86
87 RETURN = r"""
88 annotation:
89 description: Details about the created annotation.
90 returned: success
91 type: complex
92 contains:
93 _cid:
94 description: Annotation identifier.
95 returned: success
96 type: str
97 sample: /annotation/100000
98 _created:
99 description: Creation timestamp.
100 returned: success
101 type: int
102 sample: 1502236928
103 _last_modified:
104 description: Last modification timestamp.
105 returned: success
106 type: int
107 sample: 1502236928
108 _last_modified_by:
109 description: Last modified by.
110 returned: success
111 type: str
112 sample: /user/1000
113 category:
114 description: Category of the created annotation.
115 returned: success
116 type: str
117 sample: alerts
118 title:
119 description: Title of the created annotation.
120 returned: success
121 type: str
122 sample: WARNING
123 description:
124 description: Description of the created annotation.
125 returned: success
126 type: str
127 sample: Host is down.
128 start:
129 description: Timestamp, since annotation applies.
130 returned: success
131 type: int
132 sample: Host is down.
133 stop:
134 description: Timestamp, since annotation ends.
135 returned: success
136 type: str
137 sample: Host is down.
138 rel_metrics:
139 description: Array of metrics related to this annotation, each metrics is a string.
140 returned: success
141 type: list
142 sample:
143 - 54321_kbps
144 """
145
146 import json
147 import time
148 import traceback
149
150 from ansible_collections.community.general.plugins.module_utils._version import LooseVersion
151
152 REQUESTS_IMP_ERR = None
153 try:
154 import requests
155
156 HAS_REQUESTS = True
157 except ImportError:
158 REQUESTS_IMP_ERR = traceback.format_exc()
159 HAS_REQUESTS = False
160
161 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
162
163
164 def check_requests_dep(module):
165 """Check if an adequate requests version is available"""
166 if not HAS_REQUESTS:
167 module.fail_json(msg=missing_required_lib("requests"), exception=REQUESTS_IMP_ERR)
168 else:
169 required_version = "2.0.0"
170 if LooseVersion(requests.__version__) < LooseVersion(required_version):
171 module.fail_json(
172 msg=f"'requests' library version should be >= {required_version}, found: {requests.__version__}."
173 )
174
175
176 def post_annotation(annotation, api_key):
177 """Takes annotation dict and api_key string"""
178 base_url = "https://api.circonus.com/v2"
179 anootate_post_endpoint = "/annotation"
180 resp = requests.post(base_url + anootate_post_endpoint, headers=build_headers(api_key), data=json.dumps(annotation))
181 resp.raise_for_status()
182 return resp
183
184
185 def create_annotation(module):
186 """Takes ansible module object"""
187 annotation = {}
188 duration = module.params["duration"]
189 if module.params["start"] is not None:
190 start = module.params["start"]
191 else:
192 start = int(time.time())
193 if module.params["stop"] is not None:
194 stop = module.params["stop"]
195 else:
196 stop = int(time.time()) + duration
197 annotation["start"] = start
198 annotation["stop"] = stop
199 annotation["category"] = module.params["category"]
200 annotation["description"] = module.params["description"]
201 annotation["title"] = module.params["title"]
202 return annotation
203
204
205 def build_headers(api_token):
206 """Takes api token, returns headers with it included."""
207 headers = {
208 "X-Circonus-App-Name": "ansible",
209 "Host": "api.circonus.com",
210 "X-Circonus-Auth-Token": api_token,
211 "Accept": "application/json",
212 }
213 return headers
214
215
216 def main():
217 """Main function, dispatches logic"""
218 module = AnsibleModule(
219 argument_spec=dict(
220 start=dict(type="int"),
221 stop=dict(type="int"),
222 category=dict(required=True),
223 title=dict(required=True),
224 description=dict(required=True),
225 duration=dict(default=0, type="int"),
226 api_key=dict(required=True, no_log=True),
227 )
228 )
229
230 check_requests_dep(module)
231
232 annotation = create_annotation(module)
233 try:
234 resp = post_annotation(annotation, module.params["api_key"])
235 except requests.exceptions.RequestException as e:
236 module.fail_json(msg="Request Failed", reason=f"{e}", exception=traceback.format_exc())
237 module.exit_json(changed=True, annotation=resp.json())
238
239
240 if __name__ == "__main__":
241 main()