Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2023, Dominik Kukacka <[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: "ipbase_info"
11 version_added: "7.0.0"
12 short_description: "Retrieve IP geolocation and other facts of a host's IP address using the ipbase.com API"
13 description:
14 - Retrieve IP geolocation and other facts of a host's IP address using the ipbase.com API.
15 author: "Dominik Kukacka (@dominikkukacka)"
16 extends_documentation_fragment:
17 - "community.general._attributes"
18 - "community.general._attributes.info_module"
19 options:
20 ip:
21 description:
22 - The IP you want to get the info for. If not specified the API detects the IP automatically.
23 type: str
24 apikey:
25 description:
26 - The API key for the request if you need more requests.
27 type: str
28 hostname:
29 description:
30 - If the O(hostname) parameter is set to V(true), the API response contains the hostname of the IP.
31 type: bool
32 default: false
33 language:
34 description:
35 - An ISO Alpha 2 Language Code for localizing the IP data.
36 type: str
37 default: "en"
38 notes:
39 - Check U(https://ipbase.com/) for more information.
40 """
41
42 EXAMPLES = r"""
43 - name: "Get IP geolocation information of the primary outgoing IP"
44 community.general.ipbase_info:
45 register: my_ip_info
46
47 - name: "Get IP geolocation information of a specific IP"
48 community.general.ipbase_info:
49 ip: "8.8.8.8"
50 register: my_ip_info
51
52
53 - name: "Get IP geolocation information of a specific IP with all other possible parameters"
54 community.general.ipbase_info:
55 ip: "8.8.8.8"
56 apikey: "xxxxxxxxxxxxxxxxxxxxxx"
57 hostname: true
58 language: "de"
59 register: my_ip_info
60 """
61
62 RETURN = r"""
63 data:
64 description: "JSON parsed response from ipbase.com. Please refer to U(https://ipbase.com/docs/info) for the detailed structure
65 of the response."
66 returned: success
67 type: dict
68 sample:
69 {
70 "ip": "1.1.1.1",
71 "hostname": "one.one.one.one",
72 "type": "v4",
73 "range_type": {
74 "type": "PUBLIC",
75 "description": "Public address"
76 },
77 "connection": {
78 "asn": 13335,
79 "organization": "Cloudflare, Inc.",
80 "isp": "APNIC Research and Development",
81 "range": "1.1.1.1/32"
82 },
83 "location": {
84 "geonames_id": 5332870,
85 "latitude": 34.053611755371094,
86 "longitude": -118.24549865722656,
87 "zip": "90012",
88 "continent": {
89 "code": "NA",
90 "name": "North America",
91 "name_translated": "North America"
92 },
93 "country": {
94 "alpha2": "US",
95 "alpha3": "USA",
96 "calling_codes": [
97 "+1"
98 ],
99 "currencies": [
100 {
101 "symbol": "$",
102 "name": "US Dollar",
103 "symbol_native": "$",
104 "decimal_digits": 2,
105 "rounding": 0,
106 "code": "USD",
107 "name_plural": "US dollars"
108 }
109 ],
110 "emoji": "...",
111 "ioc": "USA",
112 "languages": [
113 {
114 "name": "English",
115 "name_native": "English"
116 }
117 ],
118 "name": "United States",
119 "name_translated": "United States",
120 "timezones": [
121 "America/New_York",
122 "America/Detroit",
123 "America/Kentucky/Louisville",
124 "America/Kentucky/Monticello",
125 "America/Indiana/Indianapolis",
126 "America/Indiana/Vincennes",
127 "America/Indiana/Winamac",
128 "America/Indiana/Marengo",
129 "America/Indiana/Petersburg",
130 "America/Indiana/Vevay",
131 "America/Chicago",
132 "America/Indiana/Tell_City",
133 "America/Indiana/Knox",
134 "America/Menominee",
135 "America/North_Dakota/Center",
136 "America/North_Dakota/New_Salem",
137 "America/North_Dakota/Beulah",
138 "America/Denver",
139 "America/Boise",
140 "America/Phoenix",
141 "America/Los_Angeles",
142 "America/Anchorage",
143 "America/Juneau",
144 "America/Sitka",
145 "America/Metlakatla",
146 "America/Yakutat",
147 "America/Nome",
148 "America/Adak",
149 "Pacific/Honolulu"
150 ],
151 "is_in_european_union": false,
152 "fips": "US",
153 "geonames_id": 6252001,
154 "hasc_id": "US",
155 "wikidata_id": "Q30"
156 },
157 "city": {
158 "fips": "644000",
159 "alpha2": null,
160 "geonames_id": 5368753,
161 "hasc_id": null,
162 "wikidata_id": "Q65",
163 "name": "Los Angeles",
164 "name_translated": "Los Angeles"
165 },
166 "region": {
167 "fips": "US06",
168 "alpha2": "US-CA",
169 "geonames_id": 5332921,
170 "hasc_id": "US.CA",
171 "wikidata_id": "Q99",
172 "name": "California",
173 "name_translated": "California"
174 }
175 },
176 "tlds": [
177 ".us"
178 ],
179 "timezone": {
180 "id": "America/Los_Angeles",
181 "current_time": "2023-05-04T04:30:28-07:00",
182 "code": "PDT",
183 "is_daylight_saving": true,
184 "gmt_offset": -25200
185 },
186 "security": {
187 "is_anonymous": false,
188 "is_datacenter": false,
189 "is_vpn": false,
190 "is_bot": false,
191 "is_abuser": true,
192 "is_known_attacker": true,
193 "is_proxy": false,
194 "is_spam": false,
195 "is_tor": false,
196 "is_icloud_relay": false,
197 "threat_score": 100
198 },
199 "domains": {
200 "count": 10943,
201 "domains": [
202 "eliwise.academy",
203 "accountingprose.academy",
204 "pistola.academy",
205 "1and1-test-ntlds-fr.accountant",
206 "omnergy.africa"
207 ]
208 }
209 }
210 """
211
212 from urllib.parse import urlencode
213
214 from ansible.module_utils.basic import AnsibleModule
215 from ansible.module_utils.urls import fetch_url
216
217 USER_AGENT = "ansible-community.general.ipbase_info/0.1.0"
218 BASE_URL = "https://api.ipbase.com/v2/info"
219
220
221 class IpbaseInfo:
222 def __init__(self, module):
223 self.module = module
224
225 def _get_url_data(self, url):
226 response, info = fetch_url(
227 self.module,
228 url,
229 force=True,
230 timeout=10,
231 headers={
232 "Accept": "application/json",
233 "User-Agent": USER_AGENT,
234 },
235 )
236
237 if info["status"] != 200:
238 self.module.fail_json(msg=f"The API request to ipbase.com returned an error status code {info['status']}")
239 else:
240 try:
241 content = response.read()
242 result = self.module.from_json(content.decode("utf8"))
243 except ValueError:
244 self.module.fail_json(msg=f"Failed to parse the ipbase.com response: {url} {content}")
245 else:
246 return result
247
248 def info(self):
249 ip = self.module.params["ip"]
250 apikey = self.module.params["apikey"]
251 hostname = self.module.params["hostname"]
252 language = self.module.params["language"]
253
254 url = BASE_URL
255
256 params = {}
257 if ip:
258 params["ip"] = ip
259
260 if apikey:
261 params["apikey"] = apikey
262
263 if hostname:
264 params["hostname"] = 1
265
266 if language:
267 params["language"] = language
268
269 if params:
270 url += f"?{urlencode(params)}"
271
272 return self._get_url_data(url)
273
274
275 def main():
276 module_args = dict(
277 ip=dict(type="str", no_log=False),
278 apikey=dict(type="str", no_log=True),
279 hostname=dict(type="bool", no_log=False, default=False),
280 language=dict(type="str", no_log=False, default="en"),
281 )
282
283 module = AnsibleModule(
284 argument_spec=module_args,
285 supports_check_mode=True,
286 )
287
288 ipbase = IpbaseInfo(module)
289 module.exit_json(**ipbase.info())
290
291
292 if __name__ == "__main__":
293 main()