catocli 2.0.4__py3-none-any.whl → 2.0.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of catocli might be problematic. Click here for more details.

Files changed (290) hide show
  1. build/lib/catocli/Utils/clidriver.py +268 -0
  2. build/lib/catocli/Utils/profile_manager.py +188 -0
  3. build/lib/catocli/Utils/version_checker.py +192 -0
  4. build/lib/catocli/__init__.py +2 -0
  5. build/lib/catocli/__main__.py +12 -0
  6. build/lib/catocli/parsers/configure/__init__.py +115 -0
  7. build/lib/catocli/parsers/configure/configure.py +307 -0
  8. build/lib/catocli/parsers/custom/__init__.py +57 -0
  9. build/lib/catocli/parsers/custom/customLib.py +561 -0
  10. build/lib/catocli/parsers/custom/export_rules/__init__.py +42 -0
  11. build/lib/catocli/parsers/custom/export_rules/export_rules.py +234 -0
  12. build/lib/catocli/parsers/custom/export_sites/__init__.py +21 -0
  13. build/lib/catocli/parsers/custom/export_sites/export_sites.py +372 -0
  14. build/lib/catocli/parsers/custom/import_rules_to_tf/__init__.py +58 -0
  15. build/lib/catocli/parsers/custom/import_rules_to_tf/import_rules_to_tf.py +451 -0
  16. build/lib/catocli/parsers/custom/import_sites_to_tf/__init__.py +45 -0
  17. build/lib/catocli/parsers/custom/import_sites_to_tf/import_sites_to_tf.py +891 -0
  18. build/lib/catocli/parsers/mutation_accountManagement/__init__.py +48 -0
  19. build/lib/catocli/parsers/mutation_admin/__init__.py +48 -0
  20. build/lib/catocli/parsers/mutation_container/__init__.py +138 -0
  21. build/lib/catocli/parsers/mutation_hardware/__init__.py +22 -0
  22. build/lib/catocli/parsers/mutation_policy/__init__.py +1305 -0
  23. build/lib/catocli/parsers/mutation_sandbox/__init__.py +35 -0
  24. build/lib/catocli/parsers/mutation_site/__init__.py +373 -0
  25. build/lib/catocli/parsers/mutation_sites/__init__.py +373 -0
  26. build/lib/catocli/parsers/mutation_xdr/__init__.py +48 -0
  27. build/lib/catocli/parsers/parserApiClient.py +513 -0
  28. build/lib/catocli/parsers/query_accountBySubdomain/__init__.py +16 -0
  29. build/lib/catocli/parsers/query_accountManagement/__init__.py +16 -0
  30. build/lib/catocli/parsers/query_accountMetrics/__init__.py +16 -0
  31. build/lib/catocli/parsers/query_accountRoles/__init__.py +16 -0
  32. build/lib/catocli/parsers/query_accountSnapshot/__init__.py +16 -0
  33. build/lib/catocli/parsers/query_admin/__init__.py +16 -0
  34. build/lib/catocli/parsers/query_admins/__init__.py +16 -0
  35. build/lib/catocli/parsers/query_appStats/__init__.py +16 -0
  36. build/lib/catocli/parsers/query_appStatsTimeSeries/__init__.py +16 -0
  37. build/lib/catocli/parsers/query_auditFeed/__init__.py +16 -0
  38. build/lib/catocli/parsers/query_catalogs/__init__.py +16 -0
  39. build/lib/catocli/parsers/query_container/__init__.py +16 -0
  40. build/lib/catocli/parsers/query_devices/__init__.py +16 -0
  41. build/lib/catocli/parsers/query_entityLookup/__init__.py +16 -0
  42. build/lib/catocli/parsers/query_events/__init__.py +16 -0
  43. build/lib/catocli/parsers/query_eventsFeed/__init__.py +16 -0
  44. build/lib/catocli/parsers/query_eventsTimeSeries/__init__.py +16 -0
  45. build/lib/catocli/parsers/query_hardware/__init__.py +16 -0
  46. build/lib/catocli/parsers/query_hardwareManagement/__init__.py +16 -0
  47. build/lib/catocli/parsers/query_licensing/__init__.py +16 -0
  48. build/lib/catocli/parsers/query_policy/__init__.py +161 -0
  49. build/lib/catocli/parsers/query_sandbox/__init__.py +16 -0
  50. build/lib/catocli/parsers/query_site/__init__.py +100 -0
  51. build/lib/catocli/parsers/query_siteLocation/__init__.py +13 -0
  52. build/lib/catocli/parsers/query_subDomains/__init__.py +16 -0
  53. build/lib/catocli/parsers/query_xdr/__init__.py +35 -0
  54. build/lib/catocli/parsers/raw/__init__.py +12 -0
  55. build/lib/graphql_client/__init__.py +11 -0
  56. build/lib/graphql_client/api/__init__.py +3 -0
  57. build/lib/graphql_client/api/call_api.py +84 -0
  58. build/lib/graphql_client/api_client.py +192 -0
  59. build/lib/graphql_client/api_client_types.py +409 -0
  60. build/lib/graphql_client/configuration.py +232 -0
  61. build/lib/graphql_client/models/__init__.py +13 -0
  62. build/lib/graphql_client/models/no_schema.py +71 -0
  63. build/lib/schema/catolib.py +1141 -0
  64. build/lib/schema/importSchema.py +60 -0
  65. build/lib/schema/remove_policyid.py +89 -0
  66. build/lib/schema/remove_policyid_mutations.py +89 -0
  67. build/lib/scripts/catolib.py +62 -0
  68. build/lib/scripts/export_if_rules_to_json.py +188 -0
  69. build/lib/scripts/export_wf_rules_to_json.py +111 -0
  70. build/lib/scripts/import_wf_rules_to_tfstate.py +331 -0
  71. build/lib/vendor/certifi/__init__.py +4 -0
  72. build/lib/vendor/certifi/__main__.py +12 -0
  73. build/lib/vendor/certifi/core.py +114 -0
  74. build/lib/vendor/certifi/py.typed +0 -0
  75. build/lib/vendor/six.py +998 -0
  76. build/lib/vendor/urllib3/__init__.py +211 -0
  77. build/lib/vendor/urllib3/_base_connection.py +172 -0
  78. build/lib/vendor/urllib3/_collections.py +483 -0
  79. build/lib/vendor/urllib3/_request_methods.py +278 -0
  80. build/lib/vendor/urllib3/_version.py +16 -0
  81. build/lib/vendor/urllib3/connection.py +1033 -0
  82. build/lib/vendor/urllib3/connectionpool.py +1182 -0
  83. build/lib/vendor/urllib3/contrib/__init__.py +0 -0
  84. build/lib/vendor/urllib3/contrib/emscripten/__init__.py +18 -0
  85. build/lib/vendor/urllib3/contrib/emscripten/connection.py +254 -0
  86. build/lib/vendor/urllib3/contrib/emscripten/fetch.py +418 -0
  87. build/lib/vendor/urllib3/contrib/emscripten/request.py +22 -0
  88. build/lib/vendor/urllib3/contrib/emscripten/response.py +285 -0
  89. build/lib/vendor/urllib3/contrib/pyopenssl.py +552 -0
  90. build/lib/vendor/urllib3/contrib/socks.py +228 -0
  91. build/lib/vendor/urllib3/exceptions.py +321 -0
  92. build/lib/vendor/urllib3/fields.py +341 -0
  93. build/lib/vendor/urllib3/filepost.py +89 -0
  94. build/lib/vendor/urllib3/http2/__init__.py +53 -0
  95. build/lib/vendor/urllib3/http2/connection.py +356 -0
  96. build/lib/vendor/urllib3/http2/probe.py +87 -0
  97. build/lib/vendor/urllib3/poolmanager.py +637 -0
  98. build/lib/vendor/urllib3/py.typed +2 -0
  99. build/lib/vendor/urllib3/response.py +1265 -0
  100. build/lib/vendor/urllib3/util/__init__.py +42 -0
  101. build/lib/vendor/urllib3/util/connection.py +137 -0
  102. build/lib/vendor/urllib3/util/proxy.py +43 -0
  103. build/lib/vendor/urllib3/util/request.py +256 -0
  104. build/lib/vendor/urllib3/util/response.py +101 -0
  105. build/lib/vendor/urllib3/util/retry.py +533 -0
  106. build/lib/vendor/urllib3/util/ssl_.py +513 -0
  107. build/lib/vendor/urllib3/util/ssl_match_hostname.py +159 -0
  108. build/lib/vendor/urllib3/util/ssltransport.py +276 -0
  109. build/lib/vendor/urllib3/util/timeout.py +275 -0
  110. build/lib/vendor/urllib3/util/url.py +471 -0
  111. build/lib/vendor/urllib3/util/util.py +42 -0
  112. build/lib/vendor/urllib3/util/wait.py +124 -0
  113. catocli/Utils/clidriver.py +1 -4
  114. catocli/__init__.py +1 -1
  115. catocli/parsers/custom/export_sites/export_sites.py +2 -2
  116. catocli/parsers/mutation_container/__init__.py +116 -0
  117. catocli/parsers/mutation_container_fqdn/README.md +7 -0
  118. catocli/parsers/mutation_container_fqdn_addValues/README.md +17 -0
  119. catocli/parsers/mutation_container_fqdn_createFromFile/README.md +17 -0
  120. catocli/parsers/mutation_container_fqdn_removeValues/README.md +17 -0
  121. catocli/parsers/mutation_container_fqdn_updateFromFile/README.md +17 -0
  122. catocli/parsers/mutation_container_ipAddressRange/README.md +7 -0
  123. catocli/parsers/mutation_container_ipAddressRange_addValues/README.md +17 -0
  124. catocli/parsers/mutation_container_ipAddressRange_createFromFile/README.md +17 -0
  125. catocli/parsers/mutation_container_ipAddressRange_removeValues/README.md +17 -0
  126. catocli/parsers/mutation_container_ipAddressRange_updateFromFile/README.md +17 -0
  127. catocli/parsers/mutation_policy_internetFirewall_addRule/README.md +1 -1
  128. catocli/parsers/mutation_policy_internetFirewall_updateRule/README.md +1 -1
  129. catocli/parsers/mutation_policy_wanFirewall_addRule/README.md +1 -1
  130. catocli/parsers/mutation_policy_wanFirewall_updateRule/README.md +1 -1
  131. catocli/parsers/parserApiClient.py +25 -11
  132. catocli/parsers/query_policy/README.md +0 -17
  133. catocli/parsers/query_policy/__init__.py +153 -8
  134. catocli/parsers/query_policy_appTenantRestriction/README.md +7 -0
  135. catocli/parsers/query_policy_appTenantRestriction_policy/README.md +17 -0
  136. catocli/parsers/query_policy_dynamicIpAllocation/README.md +7 -0
  137. catocli/parsers/query_policy_dynamicIpAllocation_policy/README.md +17 -0
  138. catocli/parsers/query_policy_internetFirewall/README.md +7 -0
  139. catocli/parsers/query_policy_internetFirewall_policy/README.md +17 -0
  140. catocli/parsers/query_policy_remotePortFwd/README.md +7 -0
  141. catocli/parsers/query_policy_remotePortFwd_policy/README.md +17 -0
  142. catocli/parsers/query_policy_socketLan/README.md +7 -0
  143. catocli/parsers/query_policy_socketLan_policy/README.md +17 -0
  144. catocli/parsers/query_policy_terminalServer/README.md +7 -0
  145. catocli/parsers/query_policy_terminalServer_policy/README.md +17 -0
  146. catocli/parsers/query_policy_wanFirewall/README.md +7 -0
  147. catocli/parsers/query_policy_wanFirewall_policy/README.md +17 -0
  148. catocli/parsers/query_policy_wanNetwork/README.md +7 -0
  149. catocli/parsers/query_policy_wanNetwork_policy/README.md +17 -0
  150. catocli/parsers/query_site/README.md +0 -16
  151. catocli/parsers/query_site/__init__.py +92 -8
  152. catocli/parsers/query_site_availableVersionList/README.md +17 -0
  153. catocli/parsers/query_site_bgpPeer/README.md +17 -0
  154. catocli/parsers/query_site_bgpPeerList/README.md +17 -0
  155. catocli/parsers/query_site_cloudInterconnectConnectionConnectivity/README.md +17 -0
  156. catocli/parsers/query_site_cloudInterconnectPhysicalConnection/README.md +17 -0
  157. catocli/parsers/query_site_cloudInterconnectPhysicalConnectionId/README.md +17 -0
  158. catocli/parsers/query_site_siteBgpStatus/README.md +17 -0
  159. catocli/parsers/raw/README.md +0 -14
  160. catocli/parsers/raw/__init__.py +0 -2
  161. {catocli-2.0.4.dist-info → catocli-2.0.5.dist-info}/METADATA +1 -1
  162. {catocli-2.0.4.dist-info → catocli-2.0.5.dist-info}/RECORD +290 -120
  163. {catocli-2.0.4.dist-info → catocli-2.0.5.dist-info}/top_level.txt +1 -0
  164. graphql_client/api/call_api.py +4 -3
  165. models/mutation.container.fqdn.addValues.json +866 -0
  166. models/mutation.container.fqdn.createFromFile.json +819 -0
  167. models/mutation.container.fqdn.removeValues.json +866 -0
  168. models/mutation.container.fqdn.updateFromFile.json +1045 -0
  169. models/mutation.container.ipAddressRange.addValues.json +1020 -0
  170. models/mutation.container.ipAddressRange.createFromFile.json +819 -0
  171. models/mutation.container.ipAddressRange.removeValues.json +1020 -0
  172. models/mutation.container.ipAddressRange.updateFromFile.json +1045 -0
  173. models/mutation.policy.appTenantRestriction.addRule.json +8 -8
  174. models/mutation.policy.appTenantRestriction.addSection.json +1 -1
  175. models/mutation.policy.appTenantRestriction.createPolicyRevision.json +2 -2
  176. models/mutation.policy.appTenantRestriction.discardPolicyRevision.json +2 -2
  177. models/mutation.policy.appTenantRestriction.moveRule.json +2 -2
  178. models/mutation.policy.appTenantRestriction.moveSection.json +1 -1
  179. models/mutation.policy.appTenantRestriction.publishPolicyRevision.json +2 -2
  180. models/mutation.policy.appTenantRestriction.removeRule.json +2 -2
  181. models/mutation.policy.appTenantRestriction.removeSection.json +1 -1
  182. models/mutation.policy.appTenantRestriction.updatePolicy.json +2 -2
  183. models/mutation.policy.appTenantRestriction.updateRule.json +8 -8
  184. models/mutation.policy.appTenantRestriction.updateSection.json +1 -1
  185. models/mutation.policy.dynamicIpAllocation.addRule.json +1 -1
  186. models/mutation.policy.dynamicIpAllocation.addSection.json +1 -1
  187. models/mutation.policy.dynamicIpAllocation.createPolicyRevision.json +1 -1
  188. models/mutation.policy.dynamicIpAllocation.discardPolicyRevision.json +1 -1
  189. models/mutation.policy.dynamicIpAllocation.moveRule.json +1 -1
  190. models/mutation.policy.dynamicIpAllocation.moveSection.json +1 -1
  191. models/mutation.policy.dynamicIpAllocation.publishPolicyRevision.json +1 -1
  192. models/mutation.policy.dynamicIpAllocation.removeRule.json +1 -1
  193. models/mutation.policy.dynamicIpAllocation.removeSection.json +1 -1
  194. models/mutation.policy.dynamicIpAllocation.updatePolicy.json +1 -1
  195. models/mutation.policy.dynamicIpAllocation.updateRule.json +1 -1
  196. models/mutation.policy.dynamicIpAllocation.updateSection.json +1 -1
  197. models/mutation.policy.internetFirewall.addRule.json +502 -55
  198. models/mutation.policy.internetFirewall.addSection.json +1 -1
  199. models/mutation.policy.internetFirewall.createPolicyRevision.json +127 -10
  200. models/mutation.policy.internetFirewall.discardPolicyRevision.json +127 -10
  201. models/mutation.policy.internetFirewall.moveRule.json +127 -10
  202. models/mutation.policy.internetFirewall.moveSection.json +1 -1
  203. models/mutation.policy.internetFirewall.publishPolicyRevision.json +127 -10
  204. models/mutation.policy.internetFirewall.removeRule.json +127 -10
  205. models/mutation.policy.internetFirewall.removeSection.json +1 -1
  206. models/mutation.policy.internetFirewall.updatePolicy.json +127 -10
  207. models/mutation.policy.internetFirewall.updateRule.json +493 -55
  208. models/mutation.policy.internetFirewall.updateSection.json +1 -1
  209. models/mutation.policy.remotePortFwd.addRule.json +5 -5
  210. models/mutation.policy.remotePortFwd.addSection.json +1 -1
  211. models/mutation.policy.remotePortFwd.createPolicyRevision.json +2 -2
  212. models/mutation.policy.remotePortFwd.discardPolicyRevision.json +2 -2
  213. models/mutation.policy.remotePortFwd.moveRule.json +2 -2
  214. models/mutation.policy.remotePortFwd.moveSection.json +1 -1
  215. models/mutation.policy.remotePortFwd.publishPolicyRevision.json +2 -2
  216. models/mutation.policy.remotePortFwd.removeRule.json +2 -2
  217. models/mutation.policy.remotePortFwd.removeSection.json +1 -1
  218. models/mutation.policy.remotePortFwd.updatePolicy.json +2 -2
  219. models/mutation.policy.remotePortFwd.updateRule.json +5 -5
  220. models/mutation.policy.remotePortFwd.updateSection.json +1 -1
  221. models/mutation.policy.socketLan.addRule.json +16 -16
  222. models/mutation.policy.socketLan.addSection.json +1 -1
  223. models/mutation.policy.socketLan.createPolicyRevision.json +4 -4
  224. models/mutation.policy.socketLan.discardPolicyRevision.json +4 -4
  225. models/mutation.policy.socketLan.moveRule.json +4 -4
  226. models/mutation.policy.socketLan.moveSection.json +1 -1
  227. models/mutation.policy.socketLan.publishPolicyRevision.json +4 -4
  228. models/mutation.policy.socketLan.removeRule.json +4 -4
  229. models/mutation.policy.socketLan.removeSection.json +1 -1
  230. models/mutation.policy.socketLan.updatePolicy.json +4 -4
  231. models/mutation.policy.socketLan.updateRule.json +16 -16
  232. models/mutation.policy.socketLan.updateSection.json +1 -1
  233. models/mutation.policy.terminalServer.addRule.json +1 -1
  234. models/mutation.policy.terminalServer.addSection.json +1 -1
  235. models/mutation.policy.terminalServer.createPolicyRevision.json +1 -1
  236. models/mutation.policy.terminalServer.discardPolicyRevision.json +1 -1
  237. models/mutation.policy.terminalServer.moveRule.json +1 -1
  238. models/mutation.policy.terminalServer.moveSection.json +1 -1
  239. models/mutation.policy.terminalServer.publishPolicyRevision.json +1 -1
  240. models/mutation.policy.terminalServer.removeRule.json +1 -1
  241. models/mutation.policy.terminalServer.removeSection.json +1 -1
  242. models/mutation.policy.terminalServer.updatePolicy.json +1 -1
  243. models/mutation.policy.terminalServer.updateRule.json +1 -1
  244. models/mutation.policy.terminalServer.updateSection.json +1 -1
  245. models/mutation.policy.wanFirewall.addRule.json +500 -53
  246. models/mutation.policy.wanFirewall.addSection.json +1 -1
  247. models/mutation.policy.wanFirewall.createPolicyRevision.json +128 -11
  248. models/mutation.policy.wanFirewall.discardPolicyRevision.json +128 -11
  249. models/mutation.policy.wanFirewall.moveRule.json +128 -11
  250. models/mutation.policy.wanFirewall.moveSection.json +1 -1
  251. models/mutation.policy.wanFirewall.publishPolicyRevision.json +128 -11
  252. models/mutation.policy.wanFirewall.removeRule.json +128 -11
  253. models/mutation.policy.wanFirewall.removeSection.json +1 -1
  254. models/mutation.policy.wanFirewall.updatePolicy.json +128 -11
  255. models/mutation.policy.wanFirewall.updateRule.json +491 -53
  256. models/mutation.policy.wanFirewall.updateSection.json +1 -1
  257. models/mutation.policy.wanNetwork.addRule.json +13 -13
  258. models/mutation.policy.wanNetwork.addSection.json +1 -1
  259. models/mutation.policy.wanNetwork.createPolicyRevision.json +1 -1
  260. models/mutation.policy.wanNetwork.discardPolicyRevision.json +1 -1
  261. models/mutation.policy.wanNetwork.moveRule.json +1 -1
  262. models/mutation.policy.wanNetwork.moveSection.json +1 -1
  263. models/mutation.policy.wanNetwork.publishPolicyRevision.json +1 -1
  264. models/mutation.policy.wanNetwork.removeRule.json +1 -1
  265. models/mutation.policy.wanNetwork.removeSection.json +1 -1
  266. models/mutation.policy.wanNetwork.updatePolicy.json +1 -1
  267. models/mutation.policy.wanNetwork.updateRule.json +13 -13
  268. models/mutation.policy.wanNetwork.updateSection.json +1 -1
  269. models/query.policy.appTenantRestriction.policy.json +3086 -0
  270. models/query.policy.dynamicIpAllocation.policy.json +1934 -0
  271. models/query.policy.internetFirewall.policy.json +7833 -0
  272. models/query.policy.json +233 -0
  273. models/query.policy.remotePortFwd.policy.json +2387 -0
  274. models/query.policy.socketLan.policy.json +7140 -0
  275. models/query.policy.terminalServer.policy.json +1632 -0
  276. models/query.policy.wanFirewall.policy.json +9212 -0
  277. models/query.policy.wanNetwork.policy.json +8010 -0
  278. models/query.site.availableVersionList.json +365 -0
  279. models/query.site.bgpPeer.json +1917 -0
  280. models/query.site.bgpPeerList.json +2076 -0
  281. models/query.site.cloudInterconnectConnectionConnectivity.json +298 -0
  282. models/query.site.cloudInterconnectPhysicalConnection.json +728 -0
  283. models/query.site.cloudInterconnectPhysicalConnectionId.json +660 -0
  284. models/query.site.siteBgpStatus.json +869 -0
  285. schema/catolib.py +13 -6
  286. schema/remove_policyid.py +89 -0
  287. schema/remove_policyid_mutations.py +89 -0
  288. {catocli-2.0.4.dist-info → catocli-2.0.5.dist-info}/LICENSE +0 -0
  289. {catocli-2.0.4.dist-info → catocli-2.0.5.dist-info}/WHEEL +0 -0
  290. {catocli-2.0.4.dist-info → catocli-2.0.5.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,58 @@
1
+ import catocli.parsers.custom.import_rules_to_tf.import_rules_to_tf as import_rules_to_tf
2
+
3
+ def rule_import_parse(subparsers):
4
+ """Create import command parsers"""
5
+
6
+ # Create the main import parser
7
+ import_parser = subparsers.add_parser('import', help='Import data from various sources', usage='catocli import <operation> [options]')
8
+ import_subparsers = import_parser.add_subparsers(description='valid import operations', help='additional help')
9
+
10
+ # Add if_rules_to_tf command
11
+ if_rules_parser = import_subparsers.add_parser(
12
+ 'if_rules_to_tf',
13
+ help='Import Internet Firewall rules to Terraform state',
14
+ usage='catocli import if_rules_to_tf <json_file> --module-name <module_name> [options]\n\nexample: catocli import if_rules_to_tf config_data/all_wf_rules_and_sections.json --module-name module.if_rules'
15
+ )
16
+
17
+ if_rules_parser.add_argument('json_file', help='Path to the JSON file containing IFW rules and sections')
18
+ if_rules_parser.add_argument('--module-name', required=True,
19
+ help='Terraform module name to import resources into')
20
+ if_rules_parser.add_argument('-accountID', help='Account ID (required by CLI framework but not used for import)', required=False)
21
+ if_rules_parser.add_argument('--batch-size', type=int, default=10,
22
+ help='Number of imports per batch (default: 10)')
23
+ if_rules_parser.add_argument('--delay', type=int, default=2,
24
+ help='Delay between batches in seconds (default: 2)')
25
+ if_rules_parser.add_argument('--rules-only', action='store_true',
26
+ help='Import only rules, skip sections')
27
+ if_rules_parser.add_argument('--sections-only', action='store_true',
28
+ help='Import only sections, skip rules')
29
+ if_rules_parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
30
+ if_rules_parser.add_argument('--auto-approve', action='store_true', help='Skip confirmation prompt and proceed automatically')
31
+
32
+ if_rules_parser.set_defaults(func=import_rules_to_tf.import_if_rules_to_tf)
33
+
34
+ # Add wf_rules_to_tf command
35
+ wf_rules_parser = import_subparsers.add_parser(
36
+ 'wf_rules_to_tf',
37
+ help='Import WAN Firewall rules to Terraform state',
38
+ usage='catocli import wf_rules_to_tf <json_file> --module-name <module_name> [options]\n\nexample: catocli import wf_rules_to_tf config_data/all_wf_rules_and_sections.json --module-name module.wf_rules'
39
+ )
40
+
41
+ wf_rules_parser.add_argument('json_file', help='Path to the JSON file containing WF rules and sections')
42
+ wf_rules_parser.add_argument('--module-name', required=True,
43
+ help='Terraform module name to import resources into')
44
+ wf_rules_parser.add_argument('-accountID', help='Account ID (required by CLI framework but not used for import)', required=False)
45
+ wf_rules_parser.add_argument('--batch-size', type=int, default=10,
46
+ help='Number of imports per batch (default: 10)')
47
+ wf_rules_parser.add_argument('--delay', type=int, default=2,
48
+ help='Delay between batches in seconds (default: 2)')
49
+ wf_rules_parser.add_argument('--rules-only', action='store_true',
50
+ help='Import only rules, skip sections')
51
+ wf_rules_parser.add_argument('--sections-only', action='store_true',
52
+ help='Import only sections, skip rules')
53
+ wf_rules_parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
54
+ wf_rules_parser.add_argument('--auto-approve', action='store_true', help='Skip confirmation prompt and proceed automatically')
55
+
56
+ wf_rules_parser.set_defaults(func=import_rules_to_tf.import_wf_rules_to_tf)
57
+
58
+ return import_parser
@@ -0,0 +1,451 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Direct Terraform Import Script using Python
4
+ Imports firewall rules and sections directly using subprocess calls to terraform import
5
+ Reads from JSON structure exported from Cato API
6
+ Adapted from scripts/import_if_rules_to_tfstate.py for CLI usage
7
+ """
8
+
9
+ import json
10
+ import subprocess
11
+ import sys
12
+ import re
13
+ import time
14
+ import glob
15
+ from pathlib import Path
16
+ from ..customLib import validate_terraform_environment
17
+
18
+
19
+ def load_json_data(json_file):
20
+ """Load firewall data from JSON file"""
21
+ try:
22
+ with open(json_file, 'r') as f:
23
+ data = json.load(f)
24
+ return data['data']['policy']['internetFirewall']['policy']
25
+ except FileNotFoundError:
26
+ print(f"Error: JSON file '{json_file}' not found")
27
+ sys.exit(1)
28
+ except json.JSONDecodeError as e:
29
+ print(f"Error: Invalid JSON in '{json_file}': {e}")
30
+ sys.exit(1)
31
+ except KeyError as e:
32
+ print(f"Error: Expected JSON structure not found in '{json_file}': {e}")
33
+ sys.exit(1)
34
+
35
+
36
+ def sanitize_name_for_terraform(name):
37
+ """Sanitize rule/section name to create valid Terraform resource key"""
38
+ # Replace spaces and special characters with underscores
39
+ sanitized = re.sub(r'[^a-zA-Z0-9_-]', '_', name)
40
+ # Remove multiple consecutive underscores
41
+ sanitized = re.sub(r'_+', '_', sanitized)
42
+ # Remove leading/trailing underscores
43
+ sanitized = sanitized.strip('_')
44
+ return sanitized
45
+
46
+
47
+ def extract_rules_and_sections(policy_data):
48
+ """Extract rules and sections from the policy data"""
49
+ rules = []
50
+ sections = []
51
+
52
+ # Extract rules
53
+ for rule_entry in policy_data.get('rules', []):
54
+ rule = rule_entry.get('rule', {})
55
+ if rule.get('id') and rule.get('name'):
56
+ rules.append({
57
+ 'id': rule['id'],
58
+ 'name': rule['name'],
59
+ 'index': rule.get('index', 0),
60
+ 'section_name': rule.get('section', {}).get('name', 'Default')
61
+ })
62
+
63
+ # Extract sections
64
+ for section in policy_data.get('sections', []):
65
+ if section.get('section_name'):
66
+ sections.append({
67
+ 'section_name': section['section_name'],
68
+ 'section_index': section.get('section_index', 0),
69
+ 'section_id': section.get('section_id', '')
70
+ })
71
+ return rules, sections
72
+
73
+
74
+ def run_terraform_import(resource_address, resource_id, timeout=60, verbose=False):
75
+ """
76
+ Run a single terraform import command
77
+
78
+ Args:
79
+ resource_address: The terraform resource address
80
+ resource_id: The actual resource ID to import
81
+ timeout: Command timeout in seconds
82
+ verbose: Whether to show verbose output
83
+
84
+ Returns:
85
+ tuple: (success: bool, output: str, error: str)
86
+ """
87
+ cmd = ['terraform', 'import', resource_address, resource_id]
88
+ if verbose:
89
+ print(f"Command: {' '.join(cmd)}")
90
+
91
+ try:
92
+ print(f"Importing: {resource_address} <- {resource_id}")
93
+
94
+ result = subprocess.run(
95
+ cmd,
96
+ capture_output=True,
97
+ text=True,
98
+ timeout=timeout,
99
+ cwd=Path.cwd()
100
+ )
101
+
102
+ if result.returncode == 0:
103
+ print(f"Success: {resource_address}")
104
+ return True, result.stdout, result.stderr
105
+ else:
106
+ print(f"Failed: {resource_address}")
107
+ print(f"Error: {result.stderr}")
108
+ return False, result.stdout, result.stderr
109
+
110
+ except subprocess.TimeoutExpired:
111
+ print(f"Timeout: {resource_address} (exceeded {timeout}s)")
112
+ return False, "", f"Command timed out after {timeout} seconds"
113
+ except Exception as e:
114
+ print(f"Unexpected error for {resource_address}: {e}")
115
+ return False, "", str(e)
116
+
117
+
118
+ def find_rule_index(rules, rule_name):
119
+ """Find rule index by name."""
120
+ for index, rule in enumerate(rules):
121
+ if rule['name'] == rule_name:
122
+ return index
123
+ return None
124
+
125
+
126
+ def import_sections(sections, module_name, resource_type,
127
+ resource_name="sections", verbose=False):
128
+ """Import all sections"""
129
+ print("\nStarting section imports...")
130
+ total_sections = len(sections)
131
+ successful_imports = 0
132
+ failed_imports = 0
133
+
134
+ for i, section in enumerate(sections):
135
+ section_id = section['section_id']
136
+ section_name = section['section_name']
137
+ section_index = section['section_index']
138
+ resource_address = f'{module_name}.{resource_type}.{resource_name}["{section_name}"]'
139
+ print(f"\n[{i+1}/{total_sections}] Section: {section_name} (index: {section_index})")
140
+
141
+ # For sections, we use the section name as the ID since that's how Cato identifies them
142
+ success, stdout, stderr = run_terraform_import(resource_address, section_id, verbose=verbose)
143
+
144
+ if success:
145
+ successful_imports += 1
146
+ else:
147
+ failed_imports += 1
148
+
149
+ print(f"\nSection Import Summary: {successful_imports} successful, {failed_imports} failed")
150
+ return successful_imports, failed_imports
151
+
152
+
153
+ def import_rules(rules, module_name, verbose=False,
154
+ resource_type="cato_if_rule", resource_name="rules",
155
+ batch_size=10, delay_between_batches=2, auto_approve=False):
156
+ """Import all rules in batches"""
157
+ print("\nStarting rule imports...")
158
+ successful_imports = 0
159
+ failed_imports = 0
160
+ total_rules = len(rules)
161
+
162
+ for i, rule in enumerate(rules):
163
+ rule_id = rule['id']
164
+ rule_name = rule['name']
165
+ rule_index = find_rule_index(rules, rule_name)
166
+ terraform_key = sanitize_name_for_terraform(rule_name)
167
+
168
+ # Use array index syntax instead of rule ID
169
+ resource_address = f'{module_name}.{resource_type}.{resource_name}["{str(rule_name)}"]'
170
+ print(f"\n[{i+1}/{total_rules}] Rule: {rule_name} (index: {rule_index})")
171
+
172
+ success, stdout, stderr = run_terraform_import(resource_address, rule_id, verbose=verbose)
173
+
174
+ if success:
175
+ successful_imports += 1
176
+ else:
177
+ failed_imports += 1
178
+
179
+ # Ask user if they want to continue on failure (unless auto-approved)
180
+ if failed_imports <= 3 and not auto_approve: # Only prompt for first few failures
181
+ response = input(f"\nContinue with remaining imports? (y/n): ").lower()
182
+ if response == 'n':
183
+ print("Import process stopped by user.")
184
+ break
185
+
186
+ # Delay between batches
187
+ if (i + 1) % batch_size == 0 and i < total_rules - 1:
188
+ print(f"\n Batch complete. Waiting {delay_between_batches}s before next batch...")
189
+ time.sleep(delay_between_batches)
190
+
191
+ print(f"\n Rule Import Summary: {successful_imports} successful, {failed_imports} failed")
192
+ return successful_imports, failed_imports
193
+
194
+
195
+ def import_if_rules_to_tf(args, configuration):
196
+ """Main function to orchestrate the import process"""
197
+ try:
198
+ print(" Terraform Import Tool - Cato IFW Rules & Sections")
199
+ print("=" * 60)
200
+
201
+ # Load data
202
+ print(f" Loading data from {args.json_file}...")
203
+ policy_data = load_json_data(args.json_file)
204
+
205
+ # Extract rules and sections
206
+ rules, sections = extract_rules_and_sections(policy_data)
207
+
208
+ if hasattr(args, 'verbose') and args.verbose:
209
+ print(f"section_ids: {json.dumps(policy_data.get('section_ids', {}), indent=2)}")
210
+
211
+ print(f" Found {len(rules)} rules")
212
+ print(f" Found {len(sections)} sections")
213
+
214
+ if not rules and not sections:
215
+ print(" No rules or sections found. Exiting.")
216
+ return [{"success": False, "error": "No rules or sections found"}]
217
+
218
+ # Validate Terraform environment before proceeding
219
+ validate_terraform_environment(args.module_name, verbose=args.verbose)
220
+
221
+ # Ask for confirmation (unless auto-approved)
222
+ if not args.rules_only and not args.sections_only:
223
+ print(f"\n Ready to import {len(sections)} sections and {len(rules)} rules.")
224
+ elif args.rules_only:
225
+ print(f"\n Ready to import {len(rules)} rules only.")
226
+ elif args.sections_only:
227
+ print(f"\n Ready to import {len(sections)} sections only.")
228
+
229
+ if hasattr(args, 'auto_approve') and args.auto_approve:
230
+ print("\nAuto-approve enabled, proceeding with import...")
231
+ else:
232
+ confirm = input(f"\nProceed with import? (y/n): ").lower()
233
+ if confirm != 'y':
234
+ print("Import cancelled.")
235
+ return [{"success": False, "error": "Import cancelled by user"}]
236
+
237
+ total_successful = 0
238
+ total_failed = 0
239
+
240
+ # Import sections first (if not skipped)
241
+ if not args.rules_only and sections:
242
+ successful, failed = import_sections(sections, module_name=args.module_name, resource_type="cato_if_section", verbose=args.verbose)
243
+ total_successful += successful
244
+ total_failed += failed
245
+
246
+ # Import rules (if not skipped)
247
+ if not args.sections_only and rules:
248
+ successful, failed = import_rules(rules, module_name=args.module_name,
249
+ verbose=args.verbose, batch_size=args.batch_size,
250
+ delay_between_batches=args.delay,
251
+ auto_approve=getattr(args, 'auto_approve', False))
252
+ total_successful += successful
253
+ total_failed += failed
254
+
255
+ # Final summary
256
+ print("\n" + "=" * 60)
257
+ print(" FINAL IMPORT SUMMARY")
258
+ print("=" * 60)
259
+ print(f" Total successful imports: {total_successful}")
260
+ print(f" Total failed imports: {total_failed}")
261
+ print(f" Overall success rate: {(total_successful / (total_successful + total_failed) * 100):.1f}%" if (total_successful + total_failed) > 0 else "N/A")
262
+ print("\n Import process completed!")
263
+
264
+ return [{
265
+ "success": True,
266
+ "total_successful": total_successful,
267
+ "total_failed": total_failed,
268
+ "module_name": args.module_name
269
+ }]
270
+
271
+ except Exception as e:
272
+ print(f"ERROR: {str(e)}")
273
+ return [{"success": False, "error": str(e)}]
274
+
275
+
276
+ def load_wf_json_data(json_file):
277
+ """Load WAN Firewall data from JSON file"""
278
+ try:
279
+ with open(json_file, 'r') as f:
280
+ data = json.load(f)
281
+ return data['data']['policy']['wanFirewall']['policy']
282
+ except FileNotFoundError:
283
+ print(f"Error: JSON file '{json_file}' not found")
284
+ sys.exit(1)
285
+ except json.JSONDecodeError as e:
286
+ print(f"Error: Invalid JSON in '{json_file}': {e}")
287
+ sys.exit(1)
288
+ except KeyError as e:
289
+ print(f"Error: Expected JSON structure not found in '{json_file}': {e}")
290
+ sys.exit(1)
291
+
292
+
293
+ def import_wf_sections(sections, module_name, verbose=False,
294
+ resource_type="cato_wf_section", resource_name="sections"):
295
+ """Import all WAN Firewall sections"""
296
+ print("\nStarting WAN Firewall section imports...")
297
+ total_sections = len(sections)
298
+ successful_imports = 0
299
+ failed_imports = 0
300
+
301
+ for i, section in enumerate(sections):
302
+ section_id = section['section_id']
303
+ section_name = section['section_name']
304
+ section_index = section['section_index']
305
+ # Add module. prefix if not present
306
+ if not module_name.startswith('module.'):
307
+ module_name = f'module.{module_name}'
308
+ resource_address = f'{module_name}.{resource_type}.{resource_name}["{section_name}"]'
309
+ print(f"\n[{i+1}/{total_sections}] Section: {section_name} (index: {section_index})")
310
+
311
+ # For sections, we use the section name as the ID since that's how Cato identifies them
312
+ success, stdout, stderr = run_terraform_import(resource_address, section_id, verbose=verbose)
313
+
314
+ if success:
315
+ successful_imports += 1
316
+ else:
317
+ failed_imports += 1
318
+
319
+ print(f"\nWAN Firewall Section Import Summary: {successful_imports} successful, {failed_imports} failed")
320
+ return successful_imports, failed_imports
321
+
322
+
323
+ def import_wf_rules(rules, module_name, verbose=False,
324
+ resource_type="cato_wf_rule", resource_name="rules",
325
+ batch_size=10, delay_between_batches=2, auto_approve=False):
326
+ """Import all WAN Firewall rules in batches"""
327
+ print("\nStarting WAN Firewall rule imports...")
328
+ successful_imports = 0
329
+ failed_imports = 0
330
+ total_rules = len(rules)
331
+
332
+ for i, rule in enumerate(rules):
333
+ rule_id = rule['id']
334
+ rule_name = rule['name']
335
+ rule_index = find_rule_index(rules, rule_name)
336
+ terraform_key = sanitize_name_for_terraform(rule_name)
337
+
338
+ # Add module. prefix if not present
339
+ if not module_name.startswith('module.'):
340
+ module_name = f'module.{module_name}'
341
+
342
+ # Use array index syntax instead of rule ID
343
+ resource_address = f'{module_name}.{resource_type}.{resource_name}["{str(rule_name)}"]'
344
+ print(f"\n[{i+1}/{total_rules}] Rule: {rule_name} (index: {rule_index})")
345
+
346
+ success, stdout, stderr = run_terraform_import(resource_address, rule_id, verbose=verbose)
347
+
348
+ if success:
349
+ successful_imports += 1
350
+ else:
351
+ failed_imports += 1
352
+
353
+ # Ask user if they want to continue on failure (unless auto-approved)
354
+ if failed_imports <= 3 and not auto_approve: # Only prompt for first few failures
355
+ response = input(f"\nContinue with remaining imports? (y/n): ").lower()
356
+ if response == 'n':
357
+ print("Import process stopped by user.")
358
+ break
359
+
360
+ # Delay between batches
361
+ if (i + 1) % batch_size == 0 and i < total_rules - 1:
362
+ print(f"\n Batch complete. Waiting {delay_between_batches}s before next batch...")
363
+ time.sleep(delay_between_batches)
364
+
365
+ print(f"\nWAN Firewall Rule Import Summary: {successful_imports} successful, {failed_imports} failed")
366
+ return successful_imports, failed_imports
367
+
368
+
369
+ def import_wf_rules_to_tf(args, configuration):
370
+ """Main function to orchestrate the WAN Firewall import process"""
371
+ try:
372
+ print(" Terraform Import Tool - Cato WF Rules & Sections")
373
+ print("=" * 60)
374
+
375
+ # Load data
376
+ print(f" Loading data from {args.json_file}...")
377
+ policy_data = load_wf_json_data(args.json_file)
378
+
379
+ # Extract rules and sections
380
+ rules, sections = extract_rules_and_sections(policy_data)
381
+
382
+ if hasattr(args, 'verbose') and args.verbose:
383
+ print(f"section_ids: {json.dumps(policy_data.get('section_ids', {}), indent=2)}")
384
+
385
+ print(f" Found {len(rules)} rules")
386
+ print(f" Found {len(sections)} sections")
387
+
388
+ if not rules and not sections:
389
+ print(" No rules or sections found. Exiting.")
390
+ return [{"success": False, "error": "No rules or sections found"}]
391
+
392
+ # Add module. prefix if not present
393
+ module_name = args.module_name
394
+ if not module_name.startswith('module.'):
395
+ module_name = f'module.{module_name}'
396
+ # Validate Terraform environment before proceeding
397
+ validate_terraform_environment(module_name, verbose=args.verbose)
398
+
399
+ # Ask for confirmation (unless auto-approved)
400
+ if not args.rules_only and not args.sections_only:
401
+ print(f"\n Ready to import {len(sections)} sections and {len(rules)} rules.")
402
+ elif args.rules_only:
403
+ print(f"\n Ready to import {len(rules)} rules only.")
404
+ elif args.sections_only:
405
+ print(f"\n Ready to import {len(sections)} sections only.")
406
+
407
+ if hasattr(args, 'auto_approve') and args.auto_approve:
408
+ print("\nAuto-approve enabled, proceeding with import...")
409
+ else:
410
+ confirm = input(f"\nProceed with import? (y/n): ").lower()
411
+ if confirm != 'y':
412
+ print("Import cancelled.")
413
+ return [{"success": False, "error": "Import cancelled by user"}]
414
+
415
+ total_successful = 0
416
+ total_failed = 0
417
+
418
+ # Import sections first (if not skipped)
419
+ if not args.rules_only and sections:
420
+ successful, failed = import_wf_sections(sections, module_name=args.module_name, verbose=args.verbose)
421
+ total_successful += successful
422
+ total_failed += failed
423
+
424
+ # Import rules (if not skipped)
425
+ if not args.sections_only and rules:
426
+ successful, failed = import_wf_rules(rules, module_name=args.module_name,
427
+ verbose=args.verbose, batch_size=args.batch_size,
428
+ delay_between_batches=args.delay,
429
+ auto_approve=getattr(args, 'auto_approve', False))
430
+ total_successful += successful
431
+ total_failed += failed
432
+
433
+ # Final summary
434
+ print("\n" + "=" * 60)
435
+ print(" FINAL IMPORT SUMMARY")
436
+ print("=" * 60)
437
+ print(f" Total successful imports: {total_successful}")
438
+ print(f" Total failed imports: {total_failed}")
439
+ print(f" Overall success rate: {(total_successful / (total_successful + total_failed) * 100):.1f}%" if (total_successful + total_failed) > 0 else "N/A")
440
+ print("\n Import process completed!")
441
+
442
+ return [{
443
+ "success": True,
444
+ "total_successful": total_successful,
445
+ "total_failed": total_failed,
446
+ "module_name": args.module_name
447
+ }]
448
+
449
+ except Exception as e:
450
+ print(f"ERROR: {str(e)}")
451
+ return [{"success": False, "error": str(e)}]
@@ -0,0 +1,45 @@
1
+ import catocli.parsers.custom.import_sites_to_tf.import_sites_to_tf as import_sites_to_tf
2
+
3
+ def site_import_parse(subparsers, import_parser):
4
+ """Add socket sites import command to existing import parser"""
5
+
6
+ if import_parser is None:
7
+ raise ValueError("Import parser not found. Make sure rule_import_parse is called before site_import_parse.")
8
+
9
+ # Get the existing subparsers from the import parser
10
+ import_subparsers = None
11
+ for action in import_parser._subparsers._group_actions:
12
+ if hasattr(action, 'choices'):
13
+ import_subparsers = action
14
+ break
15
+
16
+ if import_subparsers is None:
17
+ raise ValueError("Import subparsers not found in existing import parser.")
18
+
19
+ # Add socket_sites_to_tf command
20
+ socket_sites_parser = import_subparsers.add_parser(
21
+ 'socket_sites_to_tf',
22
+ help='Import socket sites to Terraform state',
23
+ usage='catocli import socket_sites_to_tf <json_file> --module-name <module_name> [options]\n\nexample: catocli import socket_sites_to_tf config_data/socket_sites_11484.json --module-name module.sites'
24
+ )
25
+
26
+ socket_sites_parser.add_argument('json_file', help='Path to the JSON file containing socket sites data')
27
+ socket_sites_parser.add_argument('--module-name', required=True,
28
+ help='Terraform module name to import resources into')
29
+ socket_sites_parser.add_argument('-accountID', help='Account ID (required by CLI framework but not used for import)', required=False)
30
+ socket_sites_parser.add_argument('--batch-size', type=int, default=10,
31
+ help='Number of imports per batch (default: 10)')
32
+ socket_sites_parser.add_argument('--delay', type=int, default=2,
33
+ help='Delay between batches in seconds (default: 2)')
34
+ socket_sites_parser.add_argument('--sites-only', action='store_true',
35
+ help='Import only sites, skip interfaces and network ranges')
36
+ socket_sites_parser.add_argument('--interfaces-only', action='store_true',
37
+ help='Import only WAN interfaces, skip sites and network ranges')
38
+ socket_sites_parser.add_argument('--network-ranges-only', action='store_true',
39
+ help='Import only network ranges, skip sites and interfaces')
40
+ socket_sites_parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
41
+ socket_sites_parser.add_argument('--auto-approve', action='store_true', help='Skip confirmation prompt and proceed automatically')
42
+
43
+ socket_sites_parser.set_defaults(func=import_sites_to_tf.import_socket_sites_to_tf)
44
+
45
+ return import_parser