Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # Copyright Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: bigpanda
10 author: "Hagai Kariti (@hkariti)"
11 short_description: Notify BigPanda about deployments
12 description:
13 - Notify BigPanda when deployments start and end (successfully or not). Returns a deployment object containing all the parameters
14 for future module calls.
15 extends_documentation_fragment:
16 - community.general._attributes
17 attributes:
18 check_mode:
19 support: full
20 diff_mode:
21 support: none
22 options:
23 component:
24 type: str
25 description:
26 - 'The name of the component being deployed. Ex: V(billing).'
27 required: true
28 aliases: ['name']
29 version:
30 type: str
31 description:
32 - The deployment version.
33 required: true
34 token:
35 type: str
36 description:
37 - API token.
38 required: true
39 state:
40 type: str
41 description:
42 - State of the deployment.
43 required: true
44 choices: ['started', 'finished', 'failed']
45 hosts:
46 type: str
47 description:
48 - Name of affected host name. Can be a list.
49 - If not specified, it defaults to the remote system's hostname.
50 aliases: ['host']
51 env:
52 type: str
53 description:
54 - The environment name, typically V(production), V(staging), and so on.
55 owner:
56 type: str
57 description:
58 - The person responsible for the deployment.
59 description:
60 type: str
61 description:
62 - Free text description of the deployment.
63 url:
64 type: str
65 description:
66 - Base URL of the API server.
67 default: "https://api.bigpanda.io"
68 validate_certs:
69 description:
70 - If V(false), SSL certificates for the target URL are not validated. This should only be used on personally controlled
71 sites using self-signed certificates.
72 default: true
73 type: bool
74 deployment_message:
75 type: str
76 description:
77 - Message about the deployment.
78 version_added: '0.2.0'
79 source_system:
80 type: str
81 description:
82 - Source system used in the requests to the API.
83 default: ansible
84
85 # informational: requirements for nodes
86 requirements: []
87 """
88
89 EXAMPLES = r"""
90 - name: Notify BigPanda about a deployment
91 community.general.bigpanda:
92 component: myapp
93 version: '1.3'
94 token: '{{ bigpanda_token }}'
95 state: started
96
97 - name: Notify BigPanda about a deployment
98 community.general.bigpanda:
99 component: myapp
100 version: '1.3'
101 token: '{{ bigpanda_token }}'
102 state: finished
103
104 # If outside servers aren't reachable from your machine, use delegate_to and override hosts:
105 - name: Notify BigPanda about a deployment
106 community.general.bigpanda:
107 component: myapp
108 version: '1.3'
109 token: '{{ bigpanda_token }}'
110 hosts: '{{ ansible_hostname }}'
111 state: started
112 delegate_to: localhost
113 register: deployment
114
115 - name: Notify BigPanda about a deployment
116 community.general.bigpanda:
117 component: '{{ deployment.component }}'
118 version: '{{ deployment.version }}'
119 token: '{{ deployment.token }}'
120 state: finished
121 delegate_to: localhost
122 """
123
124 # ===========================================
125 # Module execution.
126 #
127 import json
128 import socket
129 import traceback
130
131 from ansible.module_utils.basic import AnsibleModule
132 from ansible.module_utils.urls import fetch_url
133
134
135 def main():
136 module = AnsibleModule(
137 argument_spec=dict(
138 component=dict(required=True, aliases=["name"]),
139 version=dict(required=True),
140 token=dict(required=True, no_log=True),
141 state=dict(required=True, choices=["started", "finished", "failed"]),
142 hosts=dict(aliases=["host"]),
143 env=dict(),
144 owner=dict(),
145 description=dict(),
146 deployment_message=dict(),
147 source_system=dict(default="ansible"),
148 validate_certs=dict(default=True, type="bool"),
149 url=dict(default="https://api.bigpanda.io"),
150 ),
151 supports_check_mode=True,
152 )
153
154 token = module.params["token"]
155 state = module.params["state"]
156 url = module.params["url"]
157
158 # Build the common request body
159 body = dict()
160 for k in ("component", "version", "hosts"):
161 v = module.params[k]
162 if v is not None:
163 body[k] = v
164 if body.get("hosts") is None:
165 body["hosts"] = [socket.gethostname()]
166
167 if not isinstance(body["hosts"], list):
168 body["hosts"] = [body["hosts"]]
169
170 # Insert state-specific attributes to body
171 if state == "started":
172 for k in ("source_system", "env", "owner", "description"):
173 v = module.params[k]
174 if v is not None:
175 body[k] = v
176
177 request_url = f"{url}/data/events/deployments/start"
178 else:
179 message = module.params["deployment_message"]
180 if message is not None:
181 body["errorMessage"] = message
182
183 if state == "finished":
184 body["status"] = "success"
185 else:
186 body["status"] = "failure"
187
188 request_url = f"{url}/data/events/deployments/end"
189
190 # Build the deployment object we return
191 deployment = dict(token=token, url=url)
192 deployment.update(body)
193 if "errorMessage" in deployment:
194 message = deployment.pop("errorMessage")
195 deployment["message"] = message
196
197 # If we're in check mode, just exit pretending like we succeeded
198 if module.check_mode:
199 module.exit_json(changed=True, **deployment)
200
201 # Send the data to bigpanda
202 data = json.dumps(body)
203 headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
204 try:
205 response, info = fetch_url(module, request_url, data=data, headers=headers)
206 if info["status"] == 200:
207 module.exit_json(changed=True, **deployment)
208 else:
209 module.fail_json(msg=json.dumps(info))
210 except Exception as e:
211 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
212
213
214 if __name__ == "__main__":
215 main()