├── .project ├── .pydevproject ├── .settings └── org.eclipse.core.resources.prefs ├── COPYING ├── README.md ├── docs ├── generate.sh ├── ranger_hbase_policies.txt ├── ranger_hdfs_policies.txt ├── ranger_hive_policies.txt ├── ranger_kafka_policies.txt ├── ranger_storm_policies.txt └── ranger_yarn_policies.txt ├── library ├── ranger_hbase_policies.py ├── ranger_hdfs_policies.py ├── ranger_hive_policies.py ├── ranger_kafka_policies.py ├── ranger_storm_policies.py └── ranger_yarn_policies.py ├── meta └── main.yml └── tasks └── main.yml /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | ranger_modules 4 | 5 | 6 | 7 | 8 | 9 | org.python.pydev.PyDevBuilder 10 | 11 | 12 | 13 | 14 | 15 | org.python.pydev.pythonNature 16 | 17 | 18 | -------------------------------------------------------------------------------- /.pydevproject: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | /${PROJECT_DIR_NAME} 7 | 8 | 9 | 10 | python 2.7 11 | 12 | hadeploy 13 | 14 | 15 | -------------------------------------------------------------------------------- /.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//library/ranger_hbase_policies.py=utf-8 3 | encoding//library/ranger_hdfs_policies.py=utf-8 4 | encoding//library/ranger_hive_policies.py=utf-8 5 | encoding//library/ranger_kafka_policies.py=utf-8 6 | encoding//library/ranger_storm_policies.py=utf-8 7 | encoding//library/ranger_yarn_policies.py=utf-8 8 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ranger_modules 2 | 3 | This ansible role host a set of modules aimed to manipulate policies on Apache Ranger. 4 | 5 | * ranger\_hdfs\_policies: Allow creation/deletion/update of HDFS Ranger policies. Doc [at this location](docs/ranger_hdfs_policies.txt) 6 | 7 | * ranger\_hbase\_policies: Allow creation/deletion/update of HBase Ranger policies. Doc [at this location](docs/ranger_hbase_policies.txt) 8 | 9 | * ranger\_kafka\_policies: Allow creation/deletion/update of Kafka Ranger policies. Doc [at this location](docs/ranger_kafka_policies.txt) 10 | 11 | * ranger\_yarn\_policies: Allow creation/deletion/update of Yarn Ranger policies. Doc [at this location](docs/ranger_yarn_policies.txt) 12 | 13 | * ranger\_storm\_policies: Allow creation/deletion/update of Storm Ranger policies. Doc [at this location](docs/ranger_storm_policies.txt) 14 | 15 | ## Requirements 16 | 17 | These modules need the python-requests package to be present on the remote node. 18 | 19 | # Example Playbook 20 | 21 | # Grant full rights for user 'coxi' on folders '/apps/coxi01' and '/user/coxi01', in a recursive way 22 | 23 | - hosts: edge_node1 24 | roles: 25 | - ranger_modules 26 | tasks: 27 | - ranger_hdfs_policies: 28 | state: present 29 | admin_url: http://ranger.mycompany.com:6080 30 | admin_username: admin 31 | admin_password: admin 32 | policies: 33 | - name: "coxi01" 34 | paths: 35 | - "/apps/coxi01" 36 | - "/user/coxi01" 37 | permissions: 38 | - users: 39 | - coxi 40 | accesses: 41 | - Write 42 | - read 43 | - execute 44 | 45 | # License 46 | 47 | GNU GPL 48 | 49 | Click on the [Link](COPYING) to see the full text. 50 | 51 | -------------------------------------------------------------------------------- /docs/generate.sh: -------------------------------------------------------------------------------- 1 | 2 | ansible-doc -M ../library/ ranger_kafka_policies 2>/dev/null | sed 's/[(].*ranger_modules[/]library.*[)]//' >ranger_kafka_policies.txt 3 | ansible-doc -M ../library/ ranger_hbase_policies 2>/dev/null | sed 's/[(].*ranger_modules[/]library.*[)]//' >ranger_hbase_policies.txt 4 | ansible-doc -M ../library/ ranger_hdfs_policies 2>/dev/null | sed 's/[(].*ranger_modules[/]library.*[)]//' >ranger_hdfs_policies.txt 5 | ansible-doc -M ../library/ ranger_hive_policies 2>/dev/null | sed 's/[(].*ranger_modules[/]library.*[)]//' >ranger_hive_policies.txt 6 | ansible-doc -M ../library/ ranger_yarn_policies 2>/dev/null | sed 's/[(].*ranger_modules[/]library.*[)]//' >ranger_yarn_policies.txt 7 | ansible-doc -M ../library/ ranger_storm_policies 2>/dev/null | sed 's/[(].*ranger_modules[/]library.*[)]//' >ranger_storm_policies.txt 8 | -------------------------------------------------------------------------------- /docs/ranger_hbase_policies.txt: -------------------------------------------------------------------------------- 1 | > RANGER_HBASE_POLICIES 2 | 3 | This module will allow you to manage HBase policy in Apache Ranger. Please refer to Apache Ranger documentation for 4 | authorization policy concept and usage. 5 | 6 | OPTIONS (= is mandatory): 7 | 8 | = admin_password 9 | The password associated with the admin_username 10 | [Default: None] 11 | 12 | = admin_url 13 | The Ranger base URL to access Ranger API. Same host:port as the Ranger Admin GUI. Typically 14 | http://myranger.server.com:6080 or https://myranger.server.com:6182 15 | [Default: None] 16 | 17 | = admin_username 18 | The user name to log on the Ranger Admin. Must have enough rights to manage policies. 19 | Also accepts the special value `KERBEROS'. In such case, a valid Kerberos ticket must exist for the ansible_user account 20 | on the target system. (A `kinit' must be issued under this account). Then HDFS operation will be performed on behalf of 21 | the user defined by the Kerberos ticket. 22 | [Default: None] 23 | 24 | - ca_bundle_file 25 | Useful if Ranger Admin connection is using SSL. Allow to specify a CA_BUNDLE file, a file that contains root and 26 | intermediate certificates to validate the Ranger Admin certificate. 27 | In its simplest case, it could be a file containing the server certificate in .pem format. 28 | This file will be looked up on the remote system, on which this module will be executed. 29 | [Default: None] 30 | 31 | = policies 32 | The list of policies you want to be defined by this operation. 33 | [Default: None] 34 | 35 | - policies[0..n].audit 36 | Whether this policy is audited 37 | [Default: True] 38 | 39 | = policies[0..n].column_families 40 | A list of HBase column families this policy will apply on. Accept wildcard characters '*' and '?'. 41 | [Default: None] 42 | 43 | = policies[0..n].columns 44 | A list of HBase columns this policy will apply on. Accept wildcard characters '*' and '?' 45 | [Default: None] 46 | 47 | - policies[0..n].enabled 48 | Whether this policy is enabled. 49 | [Default: True] 50 | 51 | = policies[0..n].name 52 | The name of the policy. Must be unique across the system. 53 | [Default: None] 54 | 55 | = policies[0..n].permissions 56 | A list of permissions associated to this policy 57 | [Default: None] 58 | 59 | = policies[0..n].permissions[0..n].accesses 60 | A list of access right granted by this permission. 61 | [Default: None] 62 | 63 | - policies[0..n].permissions[0..n].delegate_admin 64 | When a policy is assigned to a user or a group of users those users become the delegated admin. The delegated admin can 65 | update, delete the policies. 66 | [Default: False] 67 | 68 | - policies[0..n].permissions[0..n].groups 69 | A list of groups this permission will apply on. 70 | [Default: None] 71 | 72 | - policies[0..n].permissions[0..n].users 73 | A list of users this permission will apply on. 74 | [Default: None] 75 | 76 | = policies[0..n].tables 77 | A list of HBase tables this policy will apply on. Accept wildcard characters '*' and '?' 78 | [Default: None] 79 | 80 | - service_name 81 | In most cases, you should not need to set this parameter. It define the Ranger Admin HBase service, typically 82 | _hbase. 83 | It must be set if there are several such services defined in your Ranger Admin configuration, to select the one you 84 | intend to use. 85 | [Default: None] 86 | 87 | - state 88 | Whether to install (present) or remove (absent) these policies 89 | (Choices: present, absent)[Default: present] 90 | 91 | - validate_certs 92 | Useful if Ranger Admin connection is using SSL. If no, SSL certificates will not be validated. This should only be used 93 | on personally controlled sites using self-signed certificates. 94 | [Default: True] 95 | 96 | 97 | AUTHOR: Serge ALEXANDRE 98 | 99 | EXAMPLES: 100 | # This playbook snippet will: 101 | # - Grant full rights to user 'user1' on all table in namespace 'ns1' ('ns1:*'). Including table creation and delegate admin. 102 | # - Grant RW rights to all users of group 'users' on the table 't1' of this namespace 'ns1' 103 | # 104 | # Note also how we handle Certificate bundle, by first copying it on the remote site. 105 | # 106 | - hosts: edge_node1 107 | roles: 108 | - ranger_modules 109 | tasks: 110 | - name: Copy ca_bundle 111 | copy: src=../rangersrv_cert.pem dest=/etc/security/rangersrc_cert.pem owner=root mode=0400 112 | - name: Apply ranger HBase policy 113 | ranger_hbase_policies: 114 | state: present 115 | admin_url: https://ranger.mycompany.com:6182 116 | admin_username: admin 117 | admin_password: admin 118 | validate_certs: yes 119 | ca_bundle_file: /etc/security/rangersrv_cert.pem 120 | policies: 121 | - name: "[ns1]" 122 | tables: [ "ns1:*" ] 123 | column_families: [ "*" ] 124 | columns: [ "*" ] 125 | permissions: 126 | - users: [ "user1" ] 127 | accesses: [ "read", "write", "create", "admin" ] 128 | delegate_admin: True 129 | - name: "[ns1:t1]" 130 | tables: [ "ns1:t1" ] 131 | column_families: [ "*" ] 132 | columns: [ "*" ] 133 | permissions: 134 | - groups: [ "users" ] 135 | accesses: [ "read", "write" ] 136 | 137 | -------------------------------------------------------------------------------- /docs/ranger_hdfs_policies.txt: -------------------------------------------------------------------------------- 1 | > RANGER_HDFS_POLICIES 2 | 3 | This module will allow you to manage HDFS policy in Apache Ranger. Please refer to Apache Ranger documentation for 4 | authorization policy concept and usage. 5 | 6 | OPTIONS (= is mandatory): 7 | 8 | = admin_password 9 | The password associated with the admin_username 10 | [Default: None] 11 | 12 | = admin_url 13 | The Ranger base URL to access Ranger API. Same host:port as the Ranger Admin GUI. Typically 14 | http://myranger.server.com:6080 or https://myranger.server.com:6182 15 | [Default: None] 16 | 17 | = admin_username 18 | The user name to log on the Ranger Admin. Must have enough rights to manage policies. 19 | Also accepts the special value `KERBEROS'. In such case, a valid Kerberos ticket must exist for the ansible_user account 20 | on the target system. (A `kinit' must be issued under this account). Then HDFS operation will be performed on behalf of 21 | the user defined by the Kerberos ticket. 22 | [Default: None] 23 | 24 | - ca_bundle_file 25 | Useful if Ranger Admin connection is using SSL. Allow to specify a CA_BUNDLE file, a file that contains root and 26 | intermediate certificates to validate the Ranger Admin certificate. 27 | In its simplest case, it could be a file containing the server certificate in .pem format. 28 | This file will be looked up on the remote system, on which this module will be executed. 29 | [Default: None] 30 | 31 | = policies 32 | The list of policies you want to be defined by this operation. 33 | [Default: None] 34 | 35 | - policies[0..n].audit 36 | Whether this policy is audited 37 | [Default: True] 38 | 39 | - policies[0..n].enabled 40 | Whether this policy is enabled. 41 | [Default: True] 42 | 43 | = policies[0..n].name 44 | The name of the policy. Must be unique across the system. 45 | [Default: None] 46 | 47 | = policies[0..n].paths 48 | A list of HDFS path this policy will apply on. Accept wildcard characters '*' and '?' 49 | [Default: None] 50 | 51 | = policies[0..n].permissions 52 | A list of permissions associated to this policy 53 | [Default: None] 54 | 55 | = policies[0..n].permissions[0..n].accesses 56 | A list of access right granted by this permission. 57 | [Default: None] 58 | 59 | - policies[0..n].permissions[0..n].delegate_admin 60 | When a policy is assigned to a user or a group of users those users become the delegated admin. The delegated admin can 61 | update, delete the policies. 62 | [Default: False] 63 | 64 | - policies[0..n].permissions[0..n].groups 65 | A list of groups this permission will apply on. 66 | [Default: None] 67 | 68 | - policies[0..n].permissions[0..n].users 69 | A list of users this permission will apply on. 70 | [Default: None] 71 | 72 | - policies[0..n].recursive 73 | Whether this policy is recursive 74 | [Default: True] 75 | 76 | - service_name 77 | In most cases, you should not need to set this parameter. It define the Ranger Admin HDFS service, typically 78 | _hadoop. 79 | It must be set if there are several such services defined in your Ranger Admin configuration, to select the one you 80 | intend to use. 81 | [Default: None] 82 | 83 | - state 84 | Whether to install (present) or remove (absent) these policies 85 | (Choices: present, absent)[Default: present] 86 | 87 | - validate_certs 88 | Useful if Ranger Admin connection is using SSL. If no, SSL certificates will not be validated. This should only be used 89 | on personally controlled sites using self-signed certificates. 90 | [Default: True] 91 | 92 | 93 | AUTHOR: Serge ALEXANDRE 94 | 95 | EXAMPLES: 96 | # Grant full rights for user 'coxi' on folders '/apps/coxi01' and '/user/coxi01', in a recursive way 97 | 98 | - hosts: edge_node1 99 | roles: 100 | - ranger_modules 101 | tasks: 102 | - ranger_hdfs_policies: 103 | state: present 104 | admin_url: http://ranger.mycompany.com:6080 105 | admin_username: admin 106 | admin_password: admin 107 | policies: 108 | - name: "coxi01" 109 | paths: 110 | - "/apps/coxi01" 111 | - "/user/coxi01" 112 | permissions: 113 | - users: 114 | - coxi 115 | accesses: 116 | - Write 117 | - read 118 | - execute 119 | 120 | -------------------------------------------------------------------------------- /docs/ranger_hive_policies.txt: -------------------------------------------------------------------------------- 1 | > RANGER_HIVE_POLICIES 2 | 3 | This module will allow you to manage Hive policy in Apache Ranger. Please refer to Apache Ranger documentation for 4 | authorization policy concept and usage. 5 | 6 | OPTIONS (= is mandatory): 7 | 8 | = admin_password 9 | The password associated with the admin_username 10 | [Default: None] 11 | 12 | = admin_url 13 | The Ranger base URL to access Ranger API. Same host:port as the Ranger Admin GUI. Typically 14 | http://myranger.server.com:6080 or https://myranger.server.com:6182 15 | [Default: None] 16 | 17 | = admin_username 18 | The user name to log on the Ranger Admin. Must have enough rights to manage policies. 19 | Also accepts the special value `KERBEROS'. In such case, a valid Kerberos ticket must exist for the ansible_user account 20 | on the target system. (A `kinit' must be issued under this account). Then HDFS operation will be performed on behalf of 21 | the user defined by the Kerberos ticket. 22 | [Default: None] 23 | 24 | - ca_bundle_file 25 | Useful if Ranger Admin connection is using SSL. Allow to specify a CA_BUNDLE file, a file that contains root and 26 | intermediate certificates to validate the Ranger Admin certificate. 27 | In its simplest case, it could be a file containing the server certificate in .pem format. 28 | This file will be looked up on the remote system, on which this module will be executed. 29 | [Default: None] 30 | 31 | = policies 32 | The list of policies you want to be defined by this operation. 33 | [Default: None] 34 | 35 | - policies[0..n].audit 36 | Whether this policy is audited 37 | [Default: True] 38 | 39 | = policies[0..n].columns 40 | A list of Hive columns this policy will apply on. Accept wildcard characters '*' and '?'. This is exclusive of 'udfs' 41 | [Default: None] 42 | 43 | = policies[0..n].databases 44 | A list of Hive databases this policy will apply on. Accept wildcard characters '*' and '?' 45 | [Default: None] 46 | 47 | - policies[0..n].enabled 48 | Whether this policy is enabled. 49 | [Default: True] 50 | 51 | = policies[0..n].name 52 | The name of the policy. Must be unique across the system. 53 | [Default: None] 54 | 55 | = policies[0..n].permissions 56 | A list of permissions associated to this policy 57 | [Default: None] 58 | 59 | = policies[0..n].permissions[0..n].accesses 60 | A list of access right granted by this permission. 61 | [Default: None] 62 | 63 | - policies[0..n].permissions[0..n].delegate_admin 64 | When a policy is assigned to a user or a group of users those users become the delegated admin. The delegated admin can 65 | update, delete the policies. 66 | [Default: False] 67 | 68 | - policies[0..n].permissions[0..n].groups 69 | A list of groups this permission will apply on. 70 | [Default: None] 71 | 72 | - policies[0..n].permissions[0..n].users 73 | A list of users this permission will apply on. 74 | [Default: None] 75 | 76 | = policies[0..n].tables 77 | A list of Hive tables this policy will apply on. Accept wildcard characters '*' and '?'. This is exclusive of 'udfs' 78 | [Default: None] 79 | 80 | = policies[0..n].udfs 81 | A list of Hive UDFs this policy will apply on. Accept wildcard characters '*' and '?'. This is exclusive of 'tables' and 82 | 'columns' 83 | [Default: None] 84 | 85 | - service_name 86 | In most cases, you should not need to set this parameter. It define the Ranger Admin Hive service, typically 87 | _hive. 88 | It must be set if there are several such services defined in your Ranger Admin configuration, to select the one you 89 | intend to use. 90 | [Default: None] 91 | 92 | - state 93 | Whether to install (present) or remove (absent) these policies 94 | (Choices: present, absent)[Default: present] 95 | 96 | - validate_certs 97 | Useful if Ranger Admin connection is using SSL. If no, SSL certificates will not be validated. This should only be used 98 | on personally controlled sites using self-signed certificates. 99 | [Default: True] 100 | 101 | 102 | AUTHOR: Serge ALEXANDRE 103 | 104 | EXAMPLES: 105 | # This playbook snippet will: 106 | # - For all columns of all tables of databases mydb and mydb2: 107 | # - select, and update on all users of group 'users' 108 | # - Full accesses including admin rights to the user 'admin' 109 | # 110 | # Note also how we handle Certificate bundle, by first copying it on the remote site. 111 | # 112 | - hosts: edge_node1 113 | roles: 114 | - ranger_modules 115 | tasks: 116 | - name: Copy ca_bundle 117 | copy: src=../rangersrv_cert.pem dest=/etc/security/rangersrc_cert.pem owner=root mode=0400 118 | - name: Apply ranger Hive policy 119 | ranger_hive_policies: 120 | state: present 121 | admin_url: https://ranger.mycompany.com:6182 122 | admin_username: admin 123 | admin_password: admin 124 | validate_certs: yes 125 | ca_bundle_file: /etc/security/rangersrv_cert.pem 126 | policies: 127 | - name: "testdb_testtable1" 128 | databases: 129 | - mydb 130 | - mydb2 131 | tables: 132 | - "*" 133 | columns: 134 | - "*" 135 | audit: false 136 | enabled: false 137 | permissions: 138 | - groups: 139 | - users 140 | accesses: 141 | - select 142 | - update 143 | - users: 144 | - admin 145 | accesses: 146 | - all 147 | delegate_admin: true 148 | 149 | -------------------------------------------------------------------------------- /docs/ranger_kafka_policies.txt: -------------------------------------------------------------------------------- 1 | > RANGER_KAFKA_POLICIES 2 | 3 | This module will allow you to manage Kafka policy in Apache Ranger. Please refer to Apache Ranger documentation for 4 | authorization policy concept and usage. 5 | 6 | OPTIONS (= is mandatory): 7 | 8 | = admin_password 9 | The password associated with the admin_username 10 | [Default: None] 11 | 12 | = admin_url 13 | The Ranger base URL to access Ranger API. Same host:port as the Ranger Admin GUI. Typically 14 | http://myranger.server.com:6080 or https://myranger.server.com:6182 15 | [Default: None] 16 | 17 | = admin_username 18 | The user name to log on the Ranger Admin. Must have enough rights to manage policies. 19 | Also accepts the special value `KERBEROS'. In such case, a valid Kerberos ticket must exist for the ansible_user account 20 | on the target system. (A `kinit' must be issued under this account). Then HDFS operation will be performed on behalf of 21 | the user defined by the Kerberos ticket. 22 | [Default: None] 23 | 24 | - ca_bundle_file 25 | Useful if Ranger Admin connection is using SSL. Allow to specify a CA_BUNDLE file, a file that contains root and 26 | intermediate certificates to validate the Ranger Admin certificate. 27 | In its simplest case, it could be a file containing the server certificate in .pem format. 28 | This file will be looked up on the remote system, on which this module will be executed. 29 | [Default: None] 30 | 31 | = policies 32 | The list of policies you want to be defined by this operation. 33 | [Default: None] 34 | 35 | - policies[0..n].audit 36 | Whether this policy is audited 37 | [Default: True] 38 | 39 | - policies[0..n].enabled 40 | Whether this policy is enabled. 41 | [Default: True] 42 | 43 | = policies[0..n].name 44 | The name of the policy. Must be unique across the system. 45 | [Default: None] 46 | 47 | = policies[0..n].permissions 48 | A list of permissions associated to this policy 49 | [Default: None] 50 | 51 | = policies[0..n].permissions[0..n].accesses 52 | A list of access right granted by this permission. 53 | [Default: None] 54 | 55 | - policies[0..n].permissions[0..n].delegate_admin 56 | When a policy is assigned to a user or a group of users those users become the delegated admin. The delegated admin can 57 | update, delete the policies. 58 | [Default: False] 59 | 60 | - policies[0..n].permissions[0..n].groups 61 | A list of groups this permission will apply on. 62 | [Default: None] 63 | 64 | - policies[0..n].permissions[0..n].ip_addresses 65 | A list of source IP addresses to be bound to this permission 66 | [Default: None] 67 | 68 | - policies[0..n].permissions[0..n].users 69 | A list of users this permission will apply on. 70 | [Default: None] 71 | 72 | = policies[0..n].topics 73 | A list of Kafka topics this policy will apply on. Accept wildcard characters '*' and '?' 74 | [Default: None] 75 | 76 | - service_name 77 | In most cases, you should not need to set this parameter. It define the Ranger Admin Kafka service, typically 78 | _kafka. 79 | It must be set if there are several such services defined in your Ranger Admin configuration, to select the one you 80 | intend to use. 81 | [Default: None] 82 | 83 | - state 84 | Whether to install (present) or remove (absent) these policies 85 | (Choices: present, absent)[Default: present] 86 | 87 | - validate_certs 88 | Useful if Ranger Admin connection is using SSL. If no, SSL certificates will not be validated. This should only be used 89 | on personally controlled sites using self-signed certificates. 90 | [Default: True] 91 | 92 | 93 | AUTHOR: Serge ALEXANDRE 94 | 95 | EXAMPLES: 96 | # Allow user 'app1' to publish to Kafka topic 'topic1'. And allow user 'app2' and all users belonging to groups 'grp1 and grp2 to consume. 97 | 98 | - hosts: edge_node1 99 | roles: 100 | - ranger_modules 101 | tasks: 102 | - ranger_kafka_policies: 103 | state: present 104 | admin_url: https://ranger.mycompany.com:6182 105 | admin_username: admin 106 | admin_password: admin 107 | validate_certs: no 108 | policies: 109 | - name: "kpolicy1" 110 | topics: 111 | - "topic1" 112 | permissions: 113 | - users: 114 | - app1 115 | accesses: 116 | - Publish 117 | - users: 118 | - app2 119 | groups: 120 | - grp1 121 | - grp2 122 | accesses: 123 | - consume 124 | 125 | 126 | 127 | # Same result, expressed in a different way 128 | - hosts: en1 129 | vars: 130 | policy1: 131 | { name: kpolicy1, topics: [ topic1 ], permissions: [ { users: [ app1 ], accesses: [ publish ] }, { users: [ app2 ], groups: [ grp1, grp2 ], accesses: [ consume ] } ] } 132 | roles: 133 | - ranger_modules 134 | tasks: 135 | - ranger_kafka_policies: 136 | state: present 137 | admin_url: https://nn1.hdp13.bsa.broadsoftware.com:6182 138 | admin_username: admin 139 | admin_password: admin 140 | validate_certs: no 141 | policies: 142 | - "{{ policy1 }}" 143 | 144 | -------------------------------------------------------------------------------- /docs/ranger_storm_policies.txt: -------------------------------------------------------------------------------- 1 | > RANGER_STORM_POLICIES 2 | 3 | This module will allow you to manage Storm policies in Apache Ranger. Please refer to Apache Ranger documentation for 4 | authorization policy concept and usage. 5 | 6 | OPTIONS (= is mandatory): 7 | 8 | = admin_password 9 | The password associated with the admin_username 10 | [Default: None] 11 | 12 | = admin_url 13 | The Ranger base URL to access Ranger API. Same host:port as the Ranger Admin GUI. Typically 14 | http://myranger.server.com:6080 or https://myranger.server.com:6182 15 | [Default: None] 16 | 17 | = admin_username 18 | The user name to log on the Ranger Admin. Must have enough rights to manage policies. 19 | Also accepts the special value `KERBEROS'. In such case, a valid Kerberos ticket must exist for the ansible_user account 20 | on the target system. (A `kinit' must be issued under this account). Then HDFS operation will be performed on behalf of 21 | the user defined by the Kerberos ticket. 22 | [Default: None] 23 | 24 | - ca_bundle_file 25 | Useful if Ranger Admin connection is using SSL. Allow to specify a CA_BUNDLE file, a file that contains root and 26 | intermediate certificates to validate the Ranger Admin certificate. 27 | In its simplest case, it could be a file containing the server certificate in .pem format. 28 | This file will be looked up on the remote system, on which this module will be executed. 29 | [Default: None] 30 | 31 | = policies 32 | The list of policies you want to be defined by this operation. 33 | [Default: None] 34 | 35 | - policies[0..n].audit 36 | Whether this policy is audited 37 | [Default: True] 38 | 39 | - policies[0..n].enabled 40 | Whether this policy is enabled. 41 | [Default: True] 42 | 43 | = policies[0..n].name 44 | The name of the policy. Must be unique across the system. 45 | [Default: None] 46 | 47 | = policies[0..n].permissions 48 | A list of permissions associated to this policy 49 | [Default: None] 50 | 51 | = policies[0..n].permissions[0..n].accesses 52 | A list of access right granted by this permission. 53 | [Default: None] 54 | 55 | - policies[0..n].permissions[0..n].delegate_admin 56 | When a policy is assigned to a user or a group of users those users become the delegated admin. The delegated admin can 57 | update, delete the policies. 58 | [Default: False] 59 | 60 | - policies[0..n].permissions[0..n].groups 61 | A list of groups this permission will apply on. 62 | [Default: None] 63 | 64 | - policies[0..n].permissions[0..n].users 65 | A list of users this permission will apply on. 66 | [Default: None] 67 | 68 | = policies[0..n].topologies 69 | A list of Storm topologies this policy will apply on. Accept wildcard characters '*' and '?' 70 | [Default: None] 71 | 72 | - service_name 73 | In most cases, you should not need to set this parameter. It define the Ranger Admin Storm service, typically 74 | _storm. 75 | It must be set if there are several such services defined in your Ranger Admin configuration, to select the one you 76 | intend to use. 77 | [Default: None] 78 | 79 | - state 80 | Whether to install (present) or remove (absent) these policies 81 | (Choices: present, absent)[Default: present] 82 | 83 | - validate_certs 84 | Useful if Ranger Admin connection is using SSL. If no, SSL certificates will not be validated. This should only be used 85 | on personally controlled sites using self-signed certificates. 86 | [Default: True] 87 | 88 | 89 | AUTHOR: Serge ALEXANDRE 90 | 91 | EXAMPLES: 92 | - hosts: edge_node1 93 | vars: 94 | stormAdminAccesses: 95 | - 'submitTopology' 96 | - 'fileUpload' 97 | - 'fileDownload' 98 | - 'killTopology' 99 | - 'rebalance' 100 | - 'activate' 101 | - 'deactivate' 102 | - 'getTopologyConf' 103 | - 'getTopology' 104 | - 'getUserTopology' 105 | - 'getTopologyInfo' 106 | - 'uploadNewCredentials' 107 | roles: 108 | - ranger_modules 109 | tasks: 110 | - name: Copy ca_bundle 111 | copy: src=../hdp13_ranger_cert.pem dest=/etc/security/hdp13_ranger_cert.pem owner=root mode=0400 112 | 113 | - name: Test ranger_yarn 114 | ranger_storm_policies: 115 | state: present 116 | admin_url: https://ranger.mycompany.com:6182 117 | admin_username: admin 118 | admin_password: admin 119 | validate_certs: no 120 | policies: 121 | - name: test3 122 | topologies: 123 | - topology1 124 | audit: true 125 | enabled: true 126 | permissions: 127 | - users: 128 | - jim 129 | - john 130 | groups: 131 | - grp1 132 | accesses: 133 | - submitTopology 134 | - killTopology 135 | - activate 136 | - deactivate 137 | - getTopology 138 | - users: 139 | - admin 140 | accesses: "{{ stormAdminAccesses }}" 141 | delegate_admin: true 142 | no_log: True 143 | 144 | -------------------------------------------------------------------------------- /docs/ranger_yarn_policies.txt: -------------------------------------------------------------------------------- 1 | > RANGER_YARN_POLICIES 2 | 3 | This module will allow you to manage Yarn policy in Apache Ranger. Please refer to Apache Ranger documentation for 4 | authorization policy concept and usage. 5 | 6 | OPTIONS (= is mandatory): 7 | 8 | = admin_password 9 | The password associated with the admin_username 10 | [Default: None] 11 | 12 | = admin_url 13 | The Ranger base URL to access Ranger API. Same host:port as the Ranger Admin GUI. Typically 14 | http://myranger.server.com:6080 or https://myranger.server.com:6182 15 | [Default: None] 16 | 17 | = admin_username 18 | The user name to log on the Ranger Admin. Must have enough rights to manage policies. 19 | Also accepts the special value `KERBEROS'. In such case, a valid Kerberos ticket must exist for the ansible_user account 20 | on the target system. (A `kinit' must be issued under this account). Then HDFS operation will be performed on behalf of 21 | the user defined by the Kerberos ticket. 22 | [Default: None] 23 | 24 | - ca_bundle_file 25 | Useful if Ranger Admin connection is using SSL. Allow to specify a CA_BUNDLE file, a file that contains root and 26 | intermediate certificates to validate the Ranger Admin certificate. 27 | In its simplest case, it could be a file containing the server certificate in .pem format. 28 | This file will be looked up on the remote system, on which this module will be executed. 29 | [Default: None] 30 | 31 | = policies 32 | The list of policies you want to be defined by this operation. 33 | [Default: None] 34 | 35 | - policies[0..n].audit 36 | Whether this policy is audited 37 | [Default: True] 38 | 39 | - policies[0..n].enabled 40 | Whether this policy is enabled. 41 | [Default: True] 42 | 43 | = policies[0..n].name 44 | The name of the policy. Must be unique across the system. 45 | [Default: None] 46 | 47 | = policies[0..n].permissions 48 | A list of permissions associated to this policy 49 | [Default: None] 50 | 51 | = policies[0..n].permissions[0..n].accesses 52 | A list of access right granted by this permission. 53 | [Default: None] 54 | 55 | - policies[0..n].permissions[0..n].delegate_admin 56 | When a policy is assigned to a user or a group of users those users become the delegated admin. The delegated admin can 57 | update, delete the policies. 58 | [Default: False] 59 | 60 | - policies[0..n].permissions[0..n].groups 61 | A list of groups this permission will apply on. 62 | [Default: None] 63 | 64 | - policies[0..n].permissions[0..n].users 65 | A list of users this permission will apply on. 66 | [Default: None] 67 | 68 | = policies[0..n].queues 69 | A list of Yarn queues this policy will apply on. Accept wildcard characters '*' and '?' 70 | [Default: None] 71 | 72 | - policies[0..n].recursive 73 | Whether this policy is recursive 74 | [Default: True] 75 | 76 | - service_name 77 | In most cases, you should not need to set this parameter. It define the Ranger Admin Yarn service, typically 78 | _yarn. 79 | It must be set if there are several such services defined in your Ranger Admin configuration, to select the one you 80 | intend to use. 81 | [Default: None] 82 | 83 | - state 84 | Whether to install (present) or remove (absent) these policies 85 | (Choices: present, absent)[Default: present] 86 | 87 | - validate_certs 88 | Useful if Ranger Admin connection is using SSL. If no, SSL certificates will not be validated. This should only be used 89 | on personally controlled sites using self-signed certificates. 90 | [Default: True] 91 | 92 | 93 | AUTHOR: Serge ALEXANDRE 94 | 95 | EXAMPLES: 96 | # This playbook snippet will: 97 | # - Allow all members of group 'users' to submit jobs on queue 'sales'. 98 | # - Grant admin rights fir user 'admin' on the same queue. 99 | # 100 | # Note also how we handle Certificate bundle, by first copying it on the remote site. 101 | # 102 | - hosts: edge_node1 103 | roles: 104 | - ranger_modules 105 | tasks: 106 | - name: Copy ca_bundle 107 | copy: src=../rangersrv_cert.pem dest=/etc/security/rangersrc_cert.pem owner=root mode=0400 108 | - name: Apply ranger Yarn policy 109 | ranger_yarn_policies: 110 | state: present 111 | admin_url: https://ranger.mycompany.com:6182 112 | admin_username: admin 113 | admin_password: admin 114 | validate_certs: yes 115 | ca_bundle_file: /etc/security/rangersrv_cert.pem 116 | policies: 117 | - name: "testyarn2" 118 | queues: 119 | - sales 120 | permissions: 121 | - groups: 122 | - users 123 | accesses: 124 | - submit-app 125 | - users: 126 | - admin 127 | accesses: 128 | - submit-app 129 | - admin-queue 130 | delegate_admin: true 131 | 132 | -------------------------------------------------------------------------------- /library/ranger_hbase_policies.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | # (c) 2017, BROADSoftware 5 | # 6 | # This software is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This software is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this software. If not, see . 18 | 19 | 20 | DOCUMENTATION = ''' 21 | --- 22 | module: ranger_hbase_policies 23 | short_description: Manage definition of HBase Policy in Apache Ranger 24 | description: 25 | - This module will allow you to manage HBase policy in Apache Ranger. 26 | - Please refer to Apache Ranger documentation for authorization policy concept and usage. 27 | options: 28 | admin_url: 29 | description: 30 | - The Ranger base URL to access Ranger API. Same host:port as the Ranger Admin GUI. Typically http://myranger.server.com:6080 or https://myranger.server.com:6182 31 | required: true 32 | default: None 33 | aliases: [] 34 | admin_username: 35 | description: 36 | - The user name to log on the Ranger Admin. Must have enough rights to manage policies. 37 | - Also accepts the special value C(KERBEROS). In such case, a valid Kerberos ticket must exist for the ansible_user account on the target system. (A C(kinit) must be issued under this account). 38 | Then HDFS operation will be performed on behalf of the user defined by the Kerberos ticket. 39 | required: true 40 | default: None 41 | aliases: [] 42 | admin_password: 43 | description: 44 | - The password associated with the admin_username 45 | required: true 46 | default: None 47 | aliases: [] 48 | validate_certs: 49 | description: 50 | - Useful if Ranger Admin connection is using SSL. If no, SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates. 51 | required: false 52 | default: True 53 | aliases: [] 54 | ca_bundle_file: 55 | description: 56 | - Useful if Ranger Admin connection is using SSL. Allow to specify a CA_BUNDLE file, a file that contains root and intermediate certificates to validate the Ranger Admin certificate. 57 | - In its simplest case, it could be a file containing the server certificate in .pem format. 58 | - This file will be looked up on the remote system, on which this module will be executed. 59 | required: false 60 | default: None 61 | aliases: [] 62 | service_name: 63 | description: 64 | - In most cases, you should not need to set this parameter. It define the Ranger Admin HBase service, typically _hbase. 65 | - It must be set if there are several such services defined in your Ranger Admin configuration, to select the one you intend to use. 66 | required: false 67 | default: None 68 | aliases: [] 69 | state: 70 | description: 71 | - Whether to install (present) or remove (absent) these policies 72 | required: false 73 | default: present 74 | choices: [ present, absent ] 75 | policies: 76 | description: 77 | - The list of policies you want to be defined by this operation. 78 | required: true 79 | default: None 80 | aliases: [] 81 | policies[0..n].name: 82 | description: 83 | - The name of the policy. Must be unique across the system. 84 | required: true 85 | default: None 86 | aliases: [] 87 | policies[0..n].tables: 88 | description: 89 | - A list of HBase tables this policy will apply on. Accept wildcard characters '*' and '?' 90 | required: true 91 | default: None 92 | aliases: [] 93 | policies[0..n].column_families: 94 | description: 95 | - A list of HBase column families this policy will apply on. Accept wildcard characters '*' and '?'. 96 | required: true 97 | default: None 98 | aliases: [] 99 | policies[0..n].columns: 100 | description: 101 | - A list of HBase columns this policy will apply on. Accept wildcard characters '*' and '?' 102 | required: true 103 | default: None 104 | aliases: [] 105 | policies[0..n].enabled: 106 | description: 107 | - Whether this policy is enabled. 108 | required: false 109 | default: True 110 | aliases: [] 111 | policies[0..n].audit: 112 | description: 113 | - Whether this policy is audited 114 | required: false 115 | default: True 116 | aliases: [] 117 | policies[0..n].permissions: 118 | description: 119 | - A list of permissions associated to this policy 120 | required: True 121 | default: None 122 | aliases: [] 123 | policies[0..n].permissions[0..n].users: 124 | description: 125 | - A list of users this permission will apply on. 126 | required: false 127 | default: None 128 | aliases: [] 129 | policies[0..n].permissions[0..n].groups: 130 | description: 131 | - A list of groups this permission will apply on. 132 | required: false 133 | default: None 134 | aliases: [] 135 | policies[0..n].permissions[0..n].accesses: 136 | description: 137 | - A list of access right granted by this permission. 138 | required: True 139 | default: None 140 | aliases: [] 141 | policies[0..n].permissions[0..n].delegate_admin: 142 | description: 143 | - When a policy is assigned to a user or a group of users those users become the delegated admin. The delegated admin can update, delete the policies. 144 | required: false 145 | default: False 146 | aliases: [] 147 | 148 | author: 149 | - "Serge ALEXANDRE" 150 | 151 | ''' 152 | 153 | 154 | EXAMPLES = ''' 155 | 156 | # This playbook snippet will: 157 | # - Grant full rights to user 'user1' on all table in namespace 'ns1' ('ns1:*'). Including table creation and delegate admin. 158 | # - Grant RW rights to all users of group 'users' on the table 't1' of this namespace 'ns1' 159 | # 160 | # Note also how we handle Certificate bundle, by first copying it on the remote site. 161 | # 162 | - hosts: edge_node1 163 | roles: 164 | - ranger_modules 165 | tasks: 166 | - name: Copy ca_bundle 167 | copy: src=../rangersrv_cert.pem dest=/etc/security/rangersrc_cert.pem owner=root mode=0400 168 | - name: Apply ranger HBase policy 169 | ranger_hbase_policies: 170 | state: present 171 | admin_url: https://ranger.mycompany.com:6182 172 | admin_username: admin 173 | admin_password: admin 174 | validate_certs: yes 175 | ca_bundle_file: /etc/security/rangersrv_cert.pem 176 | policies: 177 | - name: "[ns1]" 178 | tables: [ "ns1:*" ] 179 | column_families: [ "*" ] 180 | columns: [ "*" ] 181 | permissions: 182 | - users: [ "user1" ] 183 | accesses: [ "read", "write", "create", "admin" ] 184 | delegate_admin: True 185 | - name: "[ns1:t1]" 186 | tables: [ "ns1:t1" ] 187 | column_families: [ "*" ] 188 | columns: [ "*" ] 189 | permissions: 190 | - groups: [ "users" ] 191 | accesses: [ "read", "write" ] 192 | 193 | 194 | ''' 195 | import warnings 196 | from sets import Set 197 | 198 | HAS_REQUESTS = False 199 | try: 200 | import requests 201 | from requests.auth import HTTPBasicAuth 202 | HAS_REQUESTS = True 203 | except (ImportError, AttributeError): 204 | # AttributeError if __version__ is not present 205 | pass 206 | 207 | HAS_KERBEROS = False 208 | try: 209 | from requests_kerberos import HTTPKerberosAuth 210 | HAS_KERBEROS = True 211 | except ImportError: 212 | pass 213 | 214 | # Global, to allow access from error 215 | module = None 216 | logs = [] 217 | logLevel = 'None' 218 | 219 | def log(level, message): 220 | x = level+':' + message 221 | logs.append(x) 222 | 223 | def debug(message): 224 | if logLevel == 'debug': 225 | log("DEBUG", message) 226 | 227 | def info(message): 228 | if logLevel == "info" or logLevel == "debug": 229 | log("INFO", message) 230 | 231 | class RangerAPI: 232 | 233 | def __init__(self, endpoint, username, password, verify): 234 | self.endpoint = endpoint 235 | self.username = username 236 | self.password = password 237 | self.verify = verify 238 | self.serviceNamesByType = None 239 | if self.username == "KERBEROS": 240 | if not HAS_KERBEROS: 241 | error("'python-requests-kerberos' package is not installed") 242 | else: 243 | self.auth = HTTPKerberosAuth() 244 | else: 245 | self.auth = HTTPBasicAuth(self.username, self.password) 246 | warnings.filterwarnings("ignore", ".*Unverified HTTPS.*") 247 | warnings.filterwarnings("ignore", ".*Certificate has no `subjectAltName`.*") 248 | 249 | def get(self, path): 250 | url = self.endpoint + "/" + path 251 | resp = requests.get(url, auth = self.auth, verify=self.verify) 252 | debug("HTTP GET({}) --> {}".format(url, resp.status_code)) 253 | if resp.status_code == 200: # Warning: Failing auth may trigger a 200 with an HTML login page. 254 | contentType = resp.headers["content-type"] if ("content-type" in resp.headers) else "unknow" 255 | debug("Response content-type:{}".format(contentType)) 256 | if "json" in contentType: 257 | result = resp.json() 258 | return result 259 | elif contentType.startswith("text/html"): 260 | error("HTML content received. May be Ranger login or password is invalid!") 261 | else: 262 | error("Invalid 'content-type' ({}) in response".format(contentType)) 263 | elif resp.status_code == 401 and self.username == "KERBEROS": 264 | error("KERBEROS authentication failed! (Did you perform kinit ?)") 265 | else: 266 | error("Invalid returned http code '{0}' when calling GET on '{1}'".format(resp.status_code, url)) 267 | 268 | def getServiceNameByType(self, stype, candidate=None): 269 | if self.serviceNamesByType == None: 270 | self.serviceNamesByType = {} 271 | services = self.get("service/public/v2/api/service") 272 | for service in services: 273 | if not service["type"] in self.serviceNamesByType: 274 | self.serviceNamesByType[service['type']] = [] 275 | self.serviceNamesByType[service['type']].append(service['name']) 276 | #logger.debug(self.serviceNamesByType) 277 | if stype not in self.serviceNamesByType: 278 | error("Service type '{0}' is not defined in this Ranger instance".format(stype) ) 279 | serviceNames = self.serviceNamesByType[stype] 280 | if candidate != None: 281 | if candidate not in serviceNames: 282 | error("Service {0} is not defined on this Ranger instance".format(candidate)) 283 | return candidate 284 | else: 285 | if len(serviceNames) != 1: 286 | error("There is several choice for '{0}' service: {1}. Please configure one explicitly!".format(stype, serviceNames)) 287 | return serviceNames[0] 288 | 289 | def getPolicy(self, service, policyName): 290 | return self.get("service/public/v2/api/service/{0}/policy?policyName={1}".format(service, policyName)) 291 | 292 | def createPolicy(self, policy): 293 | url = self.endpoint + '/service/public/v2/api/policy' 294 | resp = requests.post(url, auth = self.auth, json=policy, headers={'content-type': 'application/json'}, verify=self.verify) 295 | debug("HTTP POST({}) --> {}".format(url, resp.status_code)) 296 | if resp.status_code != 200: 297 | error("Invalid returned http code '{0}' when calling POST on '{1}': {2}".format(resp.status_code, url, resp.text)) 298 | 299 | def deletePolicy(self, pid): 300 | url = "{0}/service/public/v2/api/policy/{1}".format(self.endpoint, pid) 301 | resp = requests.delete(url, auth = self.auth, verify=self.verify) 302 | debug("HTTP DELETE({}) --> {}".format(url, resp.status_code)) 303 | if resp.status_code < 200 or resp.status_code > 299: 304 | error("Invalid returned http code '{0}' when calling DELETE on '{1}: {2}'".format(resp.status_code, url, resp.text)) 305 | 306 | def updatePolicy(self, policy): 307 | url = "{0}/service/public/v2/api/policy/{1}".format(self.endpoint, policy["id"]) 308 | resp = requests.put(url, auth = self.auth, json=policy, headers={'content-type': 'application/json'}, verify=self.verify) 309 | debug("HTTP PUT({}) --> {}".format(url, resp.status_code)) 310 | if resp.status_code != 200: 311 | error("Invalid returned http code '{0}' when calling PUT on '{1}': {2}".format(resp.status_code, url, resp.text)) 312 | 313 | def close(self): 314 | pass 315 | 316 | # --------------------------------------------------------------------------------- 317 | 318 | 319 | def digdiff(left, right): 320 | result = { 321 | "missingOnLeft": [], 322 | "missingOnRight": [], 323 | "differsByValue": [], 324 | "differsByType": [] 325 | } 326 | diffValue(left, right, "", result) 327 | return result 328 | 329 | 330 | def diffValue(left, right, path, result): 331 | #print "diffValue(left:{0} right:{1})".format(left, right) 332 | if right == None: 333 | if left != None: 334 | result["differsByValue"].append(path) 335 | else: 336 | pass 337 | else: 338 | if left == None: 339 | result["differsByValue"].append(path) 340 | elif isinstance(left, dict): 341 | if isinstance(right, dict): 342 | diffDict(left, right, path, result) 343 | else: 344 | result["differsByType"].append(path) 345 | elif isinstance(left, list): 346 | if isinstance(right, list): 347 | diffList(left, right, path, result) 348 | else: 349 | result["differsByType"].append(path) 350 | else: 351 | # left is a scalar 352 | left = normalizeType(left) 353 | right = normalizeType(right) 354 | if type(left) != type(right): 355 | #print "********************* type(left):{0} type(right):{1}".format(type(left), type(right)) 356 | result["differsByType"].append(path) 357 | else: 358 | if left != right: 359 | result["differsByValue"].append(path) 360 | else: 361 | pass 362 | 363 | def normalizeType(value): 364 | """ 365 | Try to normalize o type, to be able to compare them 366 | """ 367 | if isinstance(value, unicode): 368 | return str(value) 369 | else: 370 | return value 371 | 372 | 373 | 374 | def diffDict(left, right, path, result): 375 | #print "diffDict(left:{0} right:{1})".format(left, right) 376 | for kl in left: 377 | path2 = path + "." + kl 378 | if kl in right: 379 | diffValue(left[kl], right[kl], path2, result) 380 | else: 381 | result['missingOnRight'].append(path2) 382 | for kr in right: 383 | path2 = path + "." + kr 384 | if kr in left: 385 | pass 386 | else: 387 | result['missingOnLeft'].append(path2) 388 | 389 | 390 | def diffList(left, right, path, result): 391 | for x in range(len(left)): 392 | path2 = path + '[' + str(x) + ']' 393 | if x >= len(right): 394 | result['missingOnRight'].append(path2) 395 | else: 396 | diffValue(left[x], right[x], path2, result) 397 | for x in range(len(left), len(right)): 398 | path2 = path + '[' + str(x) + ']' 399 | result['missingOnLeft'].append(path2) 400 | 401 | 402 | 403 | # --------------------------------------------------------------------------------- 404 | 405 | 406 | ALLOWED_MISSING_ON_RIGHT = Set([".version", ".policyType", ".guid"]) 407 | 408 | def isPolicyIdentical(old, new): 409 | result = digdiff(old, new) 410 | #misc.ppprint(old) 411 | #misc.ppprint(new) 412 | debug("missingOnLeft:{}".format(result['missingOnLeft'])) 413 | debug("missingOnRight:{}".format(result['missingOnRight'])) 414 | debug("differsByType:{}".format(result['differsByType'])) 415 | debug("differsByValue:{}".format(result['differsByValue'])) 416 | if len(result['missingOnLeft']) > 0 or len(result['differsByType']) > 0 or len(result['differsByValue']) > 0: 417 | return False 418 | else: 419 | for missing in result["missingOnRight"]: 420 | if not missing in ALLOWED_MISSING_ON_RIGHT: 421 | return False 422 | return True 423 | 424 | 425 | 426 | # --------------------------------------------------------- Grooming helper function 427 | 428 | def checkListOfStrNotEmpty(base, attr, prefix): 429 | if attr not in base: 430 | error("{0}: Missing attribute '{1}'".format(prefix, attr)) 431 | if not isinstance(base[attr], list): 432 | error("{0}: Attribute '{1}' if of wrong type. Must by a list".format(prefix, attr)) 433 | if len(base[attr]) == 0: 434 | error("{0}: Attribute '{1}': Must have at least one items".format(prefix, attr)) 435 | for v in base[attr]: 436 | if not isinstance(v, basestring) or len(v) == 0: 437 | error("{0}: All items of list '{1}' must be non null string".format(prefix, attr)) 438 | 439 | 440 | def checkListOfStr(base, attr, prefix): 441 | if attr not in base: 442 | base[attr] = [] 443 | else: 444 | if not isinstance(base[attr], list): 445 | error("{0}: Attribute '{1}' if of wrong type. Must by a list".format(prefix, attr)) 446 | for v in base[attr]: 447 | if not isinstance(v, basestring) or len(v) == 0: 448 | error("{0}: All items of list '{1}' must be non null string".format(prefix, attr)) 449 | 450 | def checkTypeWithDefault(base, attr, typ, default, prefix): 451 | if attr not in base: 452 | base[attr] = default 453 | else: 454 | if not isinstance(base[attr], typ): 455 | error("{0}: Attribute '{1}' if of wrong type. Must by a {2}".format(prefix, attr, typ)) 456 | 457 | def checkEnumWithDefault(base, attr, candidates, default, prefix): 458 | if attr not in base: 459 | base[attr] = default 460 | else: 461 | if not isinstance(base[attr], basestring): 462 | error("{0}: Attribute '{1}' if of wrong type. Must by a string".format(prefix, attr)) 463 | else: 464 | if not base[attr] in candidates: 465 | error("{0}: Attribute '{1}' must be one of the following: {2}".format(prefix, attr, candidates)) 466 | 467 | def checkValidAttr(base, validAttrSet, prefix): 468 | for attr in base: 469 | if attr not in validAttrSet: 470 | error("{0}: Invalid attribute '{1}'. Must be one of {2}".format(prefix, attr, validAttrSet)) 471 | 472 | 473 | def groom(policy): 474 | """ 475 | Check and Normalize target policy expression 476 | """ 477 | if 'name' not in policy: 478 | error("There is at least one HBase policy without name!") 479 | if not isinstance(policy["name"], basestring): 480 | error("HBase policy: Attribute 'name' if of wrong type. Must by a string") 481 | prefix = "HBase policy '{0}': ".format(policy['name']) 482 | 483 | checkValidAttr(policy, ['name', 'tables', 'column_families', 'columns', 'audit', 'enabled', 'permissions'], prefix) 484 | 485 | checkListOfStrNotEmpty(policy, "tables", prefix) 486 | checkListOfStrNotEmpty(policy, "column_families", prefix) 487 | checkListOfStrNotEmpty(policy, "columns", prefix) 488 | 489 | checkTypeWithDefault(policy, "audit", bool, True, prefix) 490 | checkTypeWithDefault(policy, "enabled", bool, True, prefix) 491 | 492 | checkTypeWithDefault(policy, "permissions", list, [], prefix) 493 | 494 | for permission in policy['permissions']: 495 | checkValidAttr(permission, ['users', 'groups', 'accesses', 'delegate_admin'], prefix) 496 | checkListOfStr(permission, 'users', prefix) 497 | checkListOfStr(permission, 'groups', prefix) 498 | checkListOfStr(permission, 'accesses', prefix) 499 | checkTypeWithDefault(permission, 'delegate_admin', bool, False, prefix) 500 | 501 | 502 | def newPolicy(tgtPolicy, service): 503 | policy = { 504 | 'allowExceptions': [], 505 | 'dataMaskPolicyItems': [], 506 | 'denyExceptions': [], 507 | 'denyPolicyItems': [], 508 | 'isAuditEnabled': tgtPolicy['audit'], 509 | 'isEnabled': tgtPolicy['enabled'], 510 | 'name': tgtPolicy['name'], 511 | 'policyItems': [], 512 | 'resources': { 513 | "column": { 514 | "isExcludes": False, 515 | "isRecursive": False, 516 | "values": tgtPolicy["columns"] 517 | }, 518 | "column-family": { 519 | "isExcludes": False, 520 | "isRecursive": False, 521 | "values": tgtPolicy["column_families"] 522 | }, 523 | "table": { 524 | "isExcludes": False, 525 | "isRecursive": False, 526 | "values": tgtPolicy["tables"] 527 | } 528 | }, 529 | 'rowFilterPolicyItems': [], 530 | 'service': service 531 | } 532 | for p in tgtPolicy['permissions']: 533 | tp = {} 534 | tp['accesses'] = [] 535 | tp['conditions'] = [] 536 | tp['delegateAdmin'] = p['delegate_admin'] 537 | tp['groups'] = p['groups'] 538 | tp['users'] = p['users'] 539 | for a in p['accesses']: 540 | tp['accesses'].append({ "isAllowed": True, "type": a.lower() }) 541 | policy['policyItems'].append(tp) 542 | return policy 543 | 544 | 545 | rangerAPI = None 546 | 547 | def cleanup(): 548 | if rangerAPI != None: 549 | rangerAPI.close() 550 | 551 | 552 | def error(message): 553 | cleanup() 554 | module.fail_json(msg = message, logs=logs) 555 | 556 | class Parameters: 557 | pass 558 | 559 | 560 | def checkParameters(p): 561 | pass 562 | 563 | def main(): 564 | 565 | global module 566 | module = AnsibleModule( 567 | argument_spec = dict( 568 | state = dict(required=False, choices=['present','absent'], default="present"), 569 | admin_url = dict(required=True, type='str'), 570 | admin_username = dict(required=True, type='str'), 571 | admin_password = dict(required=True, type='str'), 572 | validate_certs = dict(required=False, type='bool', default=True), 573 | ca_bundle_file = dict(required=False, type='str'), 574 | service_name = dict(required=False, type='str'), 575 | policies = dict(required=True, type='list'), 576 | log_level = dict(required=False, default="None") 577 | ), 578 | supports_check_mode=False 579 | ) 580 | 581 | if not HAS_REQUESTS: 582 | module.fail_json(msg="python-requests package is not installed") 583 | 584 | p = Parameters() 585 | p.state = module.params['state'] 586 | p.adminUrl = module.params['admin_url'] 587 | p.adminUsername = module.params['admin_username'] 588 | p.adminPassword = module.params['admin_password'] 589 | p.validateCerts = module.params['validate_certs'] 590 | p.ca_bundleFile = module.params['ca_bundle_file'] 591 | p.serviceName = module.params['service_name'] 592 | p.policies = module.params['policies'] 593 | p.logLevel = module.params['log_level'] 594 | p.changed = False 595 | 596 | global logLevel 597 | logLevel = p.logLevel 598 | 599 | checkParameters(p) 600 | 601 | if p.ca_bundleFile != None: 602 | verify = p.ca_bundleFile 603 | else: 604 | verify = p.validateCerts 605 | 606 | global rangerAPI 607 | rangerAPI = RangerAPI(p.adminUrl, p.adminUsername , p.adminPassword , verify) 608 | 609 | result = {} 610 | hbaseServiceName = rangerAPI.getServiceNameByType("hbase", p.serviceName) 611 | # Perform check before effective operation 612 | for tgtPolicy in p.policies: 613 | groom(tgtPolicy) 614 | for tgtPolicy in p.policies: 615 | policyName = tgtPolicy['name'] 616 | result[policyName] = {} 617 | oldPolicies = rangerAPI.getPolicy(hbaseServiceName, policyName) 618 | debug("oldPolicies: " + repr(oldPolicies)) 619 | #misc.ppprint(oldPolicies) 620 | if len(oldPolicies) > 1: 621 | error("More than one policy with name '{0}' !".format(policyName)) 622 | if p.state == 'present': 623 | if len(oldPolicies) == 0: 624 | policy = newPolicy(tgtPolicy, hbaseServiceName) 625 | #misc.ppprint(p) 626 | rangerAPI.createPolicy(policy) 627 | result[policyName]['action'] = "created" 628 | p.changed = True 629 | else: 630 | oldPolicy = oldPolicies[0] 631 | pid = oldPolicy["id"] 632 | policy = newPolicy(tgtPolicy, hbaseServiceName) 633 | policy["id"] = pid 634 | result[policyName]['id'] = pid 635 | if isPolicyIdentical(oldPolicy, policy): 636 | result[policyName]['action'] = "none" 637 | else: 638 | result[policyName]['action'] = "updated" 639 | rangerAPI.updatePolicy(policy) 640 | p.changed = True 641 | #misc.ppprint(oldPolicy) 642 | elif p.state == 'absent': 643 | if len(oldPolicies) == 1: 644 | rangerAPI.deletePolicy(oldPolicies[0]["id"]) 645 | result[policyName]['action'] = "deleted" 646 | p.changed = True 647 | else: 648 | result[policyName]['action'] = "none" 649 | 650 | cleanup() 651 | module.exit_json( 652 | changed = p.changed, 653 | policies = result, 654 | logs = logs 655 | ) 656 | 657 | 658 | 659 | from ansible.module_utils.basic import * #@UnusedWildImport 660 | 661 | if __name__ == '__main__': 662 | main() 663 | 664 | -------------------------------------------------------------------------------- /library/ranger_hdfs_policies.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | # (c) 2017, BROADSoftware 5 | # 6 | # This software is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This software is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this software. If not, see . 18 | 19 | 20 | DOCUMENTATION = ''' 21 | --- 22 | module: ranger_hdfs_policies 23 | short_description: Manage definition of HDFS Policy in Apache Ranger 24 | description: 25 | - This module will allow you to manage HDFS policy in Apache Ranger. 26 | - Please refer to Apache Ranger documentation for authorization policy concept and usage. 27 | options: 28 | admin_url: 29 | description: 30 | - The Ranger base URL to access Ranger API. Same host:port as the Ranger Admin GUI. Typically http://myranger.server.com:6080 or https://myranger.server.com:6182 31 | required: true 32 | default: None 33 | aliases: [] 34 | admin_username: 35 | description: 36 | - The user name to log on the Ranger Admin. Must have enough rights to manage policies. 37 | - Also accepts the special value C(KERBEROS). In such case, a valid Kerberos ticket must exist for the ansible_user account on the target system. (A C(kinit) must be issued under this account). 38 | Then HDFS operation will be performed on behalf of the user defined by the Kerberos ticket. 39 | required: true 40 | default: None 41 | aliases: [] 42 | admin_password: 43 | description: 44 | - The password associated with the admin_username 45 | required: true 46 | default: None 47 | aliases: [] 48 | validate_certs: 49 | description: 50 | - Useful if Ranger Admin connection is using SSL. If no, SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates. 51 | required: false 52 | default: True 53 | aliases: [] 54 | ca_bundle_file: 55 | description: 56 | - Useful if Ranger Admin connection is using SSL. Allow to specify a CA_BUNDLE file, a file that contains root and intermediate certificates to validate the Ranger Admin certificate. 57 | - In its simplest case, it could be a file containing the server certificate in .pem format. 58 | - This file will be looked up on the remote system, on which this module will be executed. 59 | required: false 60 | default: None 61 | aliases: [] 62 | service_name: 63 | description: 64 | - In most cases, you should not need to set this parameter. It define the Ranger Admin HDFS service, typically _hadoop. 65 | - It must be set if there are several such services defined in your Ranger Admin configuration, to select the one you intend to use. 66 | required: false 67 | default: None 68 | aliases: [] 69 | state: 70 | description: 71 | - Whether to install (present) or remove (absent) these policies 72 | required: false 73 | default: present 74 | choices: [ present, absent ] 75 | policies: 76 | description: 77 | - The list of policies you want to be defined by this operation. 78 | required: true 79 | default: None 80 | aliases: [] 81 | policies[0..n].name: 82 | description: 83 | - The name of the policy. Must be unique across the system. 84 | required: true 85 | default: None 86 | aliases: [] 87 | policies[0..n].paths: 88 | description: 89 | - A list of HDFS path this policy will apply on. Accept wildcard characters '*' and '?' 90 | required: true 91 | default: None 92 | aliases: [] 93 | policies[0..n].enabled: 94 | description: 95 | - Whether this policy is enabled. 96 | required: false 97 | default: True 98 | aliases: [] 99 | policies[0..n].audit: 100 | description: 101 | - Whether this policy is audited 102 | required: false 103 | default: True 104 | aliases: [] 105 | policies[0..n].recursive: 106 | description: 107 | - Whether this policy is recursive 108 | required: false 109 | default: True 110 | aliases: [] 111 | policies[0..n].permissions: 112 | description: 113 | - A list of permissions associated to this policy 114 | required: True 115 | default: None 116 | aliases: [] 117 | policies[0..n].permissions[0..n].users: 118 | description: 119 | - A list of users this permission will apply on. 120 | required: false 121 | default: None 122 | aliases: [] 123 | policies[0..n].permissions[0..n].groups: 124 | description: 125 | - A list of groups this permission will apply on. 126 | required: false 127 | default: None 128 | aliases: [] 129 | policies[0..n].permissions[0..n].accesses: 130 | description: 131 | - A list of access right granted by this permission. 132 | required: True 133 | default: None 134 | aliases: [] 135 | policies[0..n].permissions[0..n].delegate_admin: 136 | description: 137 | - When a policy is assigned to a user or a group of users those users become the delegated admin. The delegated admin can update, delete the policies. 138 | required: false 139 | default: False 140 | aliases: [] 141 | 142 | 143 | 144 | 145 | 146 | 147 | author: 148 | - "Serge ALEXANDRE" 149 | 150 | ''' 151 | 152 | 153 | EXAMPLES = ''' 154 | 155 | # Grant full rights for user 'coxi' on folders '/apps/coxi01' and '/user/coxi01', in a recursive way 156 | 157 | - hosts: edge_node1 158 | roles: 159 | - ranger_modules 160 | tasks: 161 | - ranger_hdfs_policies: 162 | state: present 163 | admin_url: http://ranger.mycompany.com:6080 164 | admin_username: admin 165 | admin_password: admin 166 | policies: 167 | - name: "coxi01" 168 | paths: 169 | - "/apps/coxi01" 170 | - "/user/coxi01" 171 | permissions: 172 | - users: 173 | - coxi 174 | accesses: 175 | - Write 176 | - read 177 | - execute 178 | 179 | 180 | ''' 181 | import warnings 182 | from sets import Set 183 | 184 | HAS_REQUESTS = False 185 | try: 186 | import requests 187 | from requests.auth import HTTPBasicAuth 188 | HAS_REQUESTS = True 189 | except (ImportError, AttributeError): 190 | # AttributeError if __version__ is not present 191 | pass 192 | 193 | HAS_KERBEROS = False 194 | try: 195 | from requests_kerberos import HTTPKerberosAuth 196 | HAS_KERBEROS = True 197 | except ImportError: 198 | pass 199 | 200 | # Global, to allow access from error 201 | module = None 202 | logs = [] 203 | logLevel = 'None' 204 | 205 | def log(level, message): 206 | x = level+':' + message 207 | logs.append(x) 208 | 209 | def debug(message): 210 | if logLevel == 'debug': 211 | log("DEBUG", message) 212 | 213 | def info(message): 214 | if logLevel == "info" or logLevel == "debug": 215 | log("INFO", message) 216 | 217 | class RangerAPI: 218 | 219 | def __init__(self, endpoint, username, password, verify): 220 | self.endpoint = endpoint 221 | self.username = username 222 | self.password = password 223 | self.verify = verify 224 | self.serviceNamesByType = None 225 | if self.username == "KERBEROS": 226 | if not HAS_KERBEROS: 227 | error("'python-requests-kerberos' package is not installed") 228 | else: 229 | self.auth = HTTPKerberosAuth() 230 | else: 231 | self.auth = HTTPBasicAuth(self.username, self.password) 232 | warnings.filterwarnings("ignore", ".*Unverified HTTPS.*") 233 | warnings.filterwarnings("ignore", ".*Certificate has no `subjectAltName`.*") 234 | 235 | def get(self, path): 236 | url = self.endpoint + "/" + path 237 | resp = requests.get(url, auth = self.auth, verify=self.verify) 238 | debug("HTTP GET({}) --> {}".format(url, resp.status_code)) 239 | if resp.status_code == 200: # Warning: Failing auth may trigger a 200 with an HTML login page. 240 | contentType = resp.headers["content-type"] if ("content-type" in resp.headers) else "unknow" 241 | debug("Response content-type:{}".format(contentType)) 242 | if "json" in contentType: 243 | result = resp.json() 244 | return result 245 | elif contentType.startswith("text/html"): 246 | error("HTML content received. May be Ranger login or password is invalid!") 247 | else: 248 | error("Invalid 'content-type' ({}) in response".format(contentType)) 249 | elif resp.status_code == 401 and self.username == "KERBEROS": 250 | error("KERBEROS authentication failed! (Did you perform kinit ?)") 251 | else: 252 | error("Invalid returned http code '{0}' when calling GET on '{1}'".format(resp.status_code, url)) 253 | 254 | def getServiceNameByType(self, stype, candidate=None): 255 | if self.serviceNamesByType == None: 256 | self.serviceNamesByType = {} 257 | services = self.get("service/public/v2/api/service") 258 | for service in services: 259 | if not service["type"] in self.serviceNamesByType: 260 | self.serviceNamesByType[service['type']] = [] 261 | self.serviceNamesByType[service['type']].append(service['name']) 262 | #logger.debug(self.serviceNamesByType) 263 | if stype not in self.serviceNamesByType: 264 | error("Service type '{0}' is not defined in this Ranger instance".format(stype) ) 265 | serviceNames = self.serviceNamesByType[stype] 266 | if candidate != None: 267 | if candidate not in serviceNames: 268 | error("Service {0} is not defined on this Ranger instance".format(candidate)) 269 | return candidate 270 | else: 271 | if len(serviceNames) != 1: 272 | error("There is several choice for '{0}' service: {1}. Please configure one explicitly!".format(stype, serviceNames)) 273 | return serviceNames[0] 274 | 275 | def getPolicy(self, service, policyName): 276 | return self.get("service/public/v2/api/service/{0}/policy?policyName={1}".format(service, policyName)) 277 | 278 | def createPolicy(self, policy): 279 | url = self.endpoint + '/service/public/v2/api/policy' 280 | resp = requests.post(url, auth = self.auth, json=policy, headers={'content-type': 'application/json'}, verify=self.verify) 281 | debug("HTTP POST({}) --> {}".format(url, resp.status_code)) 282 | if resp.status_code != 200: 283 | error("Invalid returned http code '{0}' when calling POST on '{1}': {2}".format(resp.status_code, url, resp.text)) 284 | 285 | def deletePolicy(self, pid): 286 | url = "{0}/service/public/v2/api/policy/{1}".format(self.endpoint, pid) 287 | resp = requests.delete(url, auth = self.auth, verify=self.verify) 288 | debug("HTTP DELETE({}) --> {}".format(url, resp.status_code)) 289 | if resp.status_code < 200 or resp.status_code > 299: 290 | error("Invalid returned http code '{0}' when calling DELETE on '{1}: {2}'".format(resp.status_code, url, resp.text)) 291 | 292 | def updatePolicy(self, policy): 293 | url = "{0}/service/public/v2/api/policy/{1}".format(self.endpoint, policy["id"]) 294 | resp = requests.put(url, auth = self.auth, json=policy, headers={'content-type': 'application/json'}, verify=self.verify) 295 | debug("HTTP PUT({}) --> {}".format(url, resp.status_code)) 296 | if resp.status_code != 200: 297 | error("Invalid returned http code '{0}' when calling PUT on '{1}': {2}".format(resp.status_code, url, resp.text)) 298 | 299 | def close(self): 300 | pass 301 | 302 | # --------------------------------------------------------------------------------- 303 | 304 | 305 | def digdiff(left, right): 306 | result = { 307 | "missingOnLeft": [], 308 | "missingOnRight": [], 309 | "differsByValue": [], 310 | "differsByType": [] 311 | } 312 | diffValue(left, right, "", result) 313 | return result 314 | 315 | 316 | def diffValue(left, right, path, result): 317 | #print "diffValue(left:{0} right:{1})".format(left, right) 318 | if right == None: 319 | if left != None: 320 | result["differsByValue"].append(path) 321 | else: 322 | pass 323 | else: 324 | if left == None: 325 | result["differsByValue"].append(path) 326 | elif isinstance(left, dict): 327 | if isinstance(right, dict): 328 | diffDict(left, right, path, result) 329 | else: 330 | result["differsByType"].append(path) 331 | elif isinstance(left, list): 332 | if isinstance(right, list): 333 | diffList(left, right, path, result) 334 | else: 335 | result["differsByType"].append(path) 336 | else: 337 | # left is a scalar 338 | left = normalizeType(left) 339 | right = normalizeType(right) 340 | if type(left) != type(right): 341 | #print "********************* type(left):{0} type(right):{1}".format(type(left), type(right)) 342 | result["differsByType"].append(path) 343 | else: 344 | if left != right: 345 | result["differsByValue"].append(path) 346 | else: 347 | pass 348 | 349 | def normalizeType(value): 350 | """ 351 | Try to normalize o type, to be able to compare them 352 | """ 353 | if isinstance(value, unicode): 354 | return str(value) 355 | else: 356 | return value 357 | 358 | 359 | 360 | def diffDict(left, right, path, result): 361 | #print "diffDict(left:{0} right:{1})".format(left, right) 362 | for kl in left: 363 | path2 = path + "." + kl 364 | if kl in right: 365 | diffValue(left[kl], right[kl], path2, result) 366 | else: 367 | result['missingOnRight'].append(path2) 368 | for kr in right: 369 | path2 = path + "." + kr 370 | if kr in left: 371 | pass 372 | else: 373 | result['missingOnLeft'].append(path2) 374 | 375 | 376 | def diffList(left, right, path, result): 377 | for x in range(len(left)): 378 | path2 = path + '[' + str(x) + ']' 379 | if x >= len(right): 380 | result['missingOnRight'].append(path2) 381 | else: 382 | diffValue(left[x], right[x], path2, result) 383 | for x in range(len(left), len(right)): 384 | path2 = path + '[' + str(x) + ']' 385 | result['missingOnLeft'].append(path2) 386 | 387 | 388 | 389 | # --------------------------------------------------------------------------------- 390 | 391 | 392 | ALLOWED_MISSING_ON_RIGHT = Set([".version", ".policyType", ".guid"]) 393 | 394 | def isPolicyIdentical(old, new): 395 | result = digdiff(old, new) 396 | #misc.ppprint(old) 397 | #misc.ppprint(new) 398 | debug("missingOnLeft:{}".format(result['missingOnLeft'])) 399 | debug("missingOnRight:{}".format(result['missingOnRight'])) 400 | debug("differsByType:{}".format(result['differsByType'])) 401 | debug("differsByValue:{}".format(result['differsByValue'])) 402 | if len(result['missingOnLeft']) > 0 or len(result['differsByType']) > 0 or len(result['differsByValue']) > 0: 403 | return False 404 | else: 405 | for missing in result["missingOnRight"]: 406 | if not missing in ALLOWED_MISSING_ON_RIGHT: 407 | return False 408 | return True 409 | 410 | 411 | 412 | # --------------------------------------------------------- Grooming helper function 413 | 414 | def checkListOfStrNotEmpty(base, attr, prefix): 415 | if attr not in base: 416 | error("{0}: Missing attribute '{1}'".format(prefix, attr)) 417 | if not isinstance(base[attr], list): 418 | error("{0}: Attribute '{1}' if of wrong type. Must by a list".format(prefix, attr)) 419 | if len(base[attr]) == 0: 420 | error("{0}: Attribute '{1}': Must have at least one items".format(prefix, attr)) 421 | for v in base[attr]: 422 | if not isinstance(v, basestring) or len(v) == 0: 423 | error("{0}: All items of list '{1}' must be non null string".format(prefix, attr)) 424 | 425 | 426 | def checkListOfStr(base, attr, prefix): 427 | if attr not in base: 428 | base[attr] = [] 429 | else: 430 | if not isinstance(base[attr], list): 431 | error("{0}: Attribute '{1}' if of wrong type. Must by a list".format(prefix, attr)) 432 | for v in base[attr]: 433 | if not isinstance(v, basestring) or len(v) == 0: 434 | error("{0}: All items of list '{1}' must be non null string".format(prefix, attr)) 435 | 436 | def checkTypeWithDefault(base, attr, typ, default, prefix): 437 | if attr not in base: 438 | base[attr] = default 439 | else: 440 | if not isinstance(base[attr], typ): 441 | error("{0}: Attribute '{1}' if of wrong type. Must by a {2}".format(prefix, attr, typ)) 442 | 443 | def checkEnumWithDefault(base, attr, candidates, default, prefix): 444 | if attr not in base: 445 | base[attr] = default 446 | else: 447 | if not isinstance(base[attr], basestring): 448 | error("{0}: Attribute '{1}' if of wrong type. Must by a string".format(prefix, attr)) 449 | else: 450 | if not base[attr] in candidates: 451 | error("{0}: Attribute '{1}' must be one of the following: {2}".format(prefix, attr, candidates)) 452 | 453 | def checkValidAttr(base, validAttrSet, prefix): 454 | for attr in base: 455 | if attr not in validAttrSet: 456 | error("{0}: Invalid attribute '{1}'. Must be one of {2}".format(prefix, attr, validAttrSet)) 457 | 458 | 459 | def groom(policy): 460 | """ 461 | Normalize target policy expression 462 | """ 463 | if 'name' not in policy: 464 | error("There is at least one HDFS policy without name!") 465 | if not isinstance(policy["name"], basestring): 466 | error("HDFS policy: Attribute 'name' if of wrong type. Must by a string") 467 | prefix = "HDFS policy '{0}': ".format(policy['name']) 468 | 469 | checkValidAttr(policy, ['name', 'paths', 'recursive', 'audit', 'enabled', 'permissions'], prefix) 470 | 471 | checkListOfStrNotEmpty(policy, "paths", prefix) 472 | 473 | checkTypeWithDefault(policy, "recursive", bool, True, prefix) 474 | checkTypeWithDefault(policy, "audit", bool, True, prefix) 475 | checkTypeWithDefault(policy, "enabled", bool, True, prefix) 476 | 477 | checkTypeWithDefault(policy, "permissions", list, [], prefix) 478 | 479 | for permission in policy['permissions']: 480 | checkValidAttr(permission, ['users', 'groups', 'accesses', 'delegate_admin'], prefix) 481 | checkListOfStr(permission, 'users', prefix) 482 | checkListOfStr(permission, 'groups', prefix) 483 | checkListOfStr(permission, 'accesses', prefix) 484 | checkTypeWithDefault(permission, 'delegate_admin', bool, False, prefix) 485 | 486 | 487 | def newPolicy(tgtPolicy, service): 488 | policy = { 489 | 'allowExceptions': [], 490 | 'dataMaskPolicyItems': [], 491 | 'denyExceptions': [], 492 | 'denyPolicyItems': [], 493 | 'isAuditEnabled': tgtPolicy['audit'], 494 | 'isEnabled': tgtPolicy['enabled'], 495 | 'name': tgtPolicy['name'], 496 | 'policyItems': [], 497 | 'resources': { 498 | "path": { 499 | "isExcludes": False, 500 | "isRecursive": tgtPolicy["recursive"], 501 | "values": tgtPolicy["paths"] 502 | } 503 | }, 504 | 'rowFilterPolicyItems': [], 505 | 'service': service 506 | } 507 | for p in tgtPolicy['permissions']: 508 | tp = {} 509 | tp['accesses'] = [] 510 | tp['conditions'] = [] 511 | tp['delegateAdmin'] = p['delegate_admin'] 512 | tp['groups'] = p['groups'] 513 | tp['users'] = p['users'] 514 | for a in p['accesses']: 515 | tp['accesses'].append({ "isAllowed": True, "type": a.lower()}) 516 | policy['policyItems'].append(tp) 517 | return policy 518 | 519 | 520 | 521 | rangerAPI = None 522 | 523 | def cleanup(): 524 | if rangerAPI != None: 525 | rangerAPI.close() 526 | 527 | 528 | def error(message): 529 | cleanup() 530 | module.fail_json(msg = message, logs=logs) 531 | 532 | class Parameters: 533 | pass 534 | 535 | 536 | def checkParameters(p): 537 | pass 538 | 539 | def main(): 540 | 541 | global module 542 | module = AnsibleModule( 543 | argument_spec = dict( 544 | state = dict(required=False, choices=['present','absent'], default="present"), 545 | admin_url = dict(required=True, type='str'), 546 | admin_username = dict(required=True, type='str'), 547 | admin_password = dict(required=True, type='str'), 548 | validate_certs = dict(required=False, type='bool', default=True), 549 | ca_bundle_file = dict(required=False, type='str'), 550 | service_name = dict(required=False, type='str'), 551 | policies = dict(required=True, type='list'), 552 | log_level = dict(required=False, default="None") 553 | ), 554 | supports_check_mode=False 555 | ) 556 | 557 | if not HAS_REQUESTS: 558 | module.fail_json(msg="python-requests package is not installed") 559 | 560 | p = Parameters() 561 | p.state = module.params['state'] 562 | p.adminUrl = module.params['admin_url'] 563 | p.adminUsername = module.params['admin_username'] 564 | p.adminPassword = module.params['admin_password'] 565 | p.validateCerts = module.params['validate_certs'] 566 | p.ca_bundleFile = module.params['ca_bundle_file'] 567 | p.serviceName = module.params['service_name'] 568 | p.policies = module.params['policies'] 569 | p.logLevel = module.params['log_level'] 570 | p.changed = False 571 | 572 | global logLevel 573 | logLevel = p.logLevel 574 | 575 | checkParameters(p) 576 | 577 | if p.ca_bundleFile != None: 578 | verify = p.ca_bundleFile 579 | else: 580 | verify = p.validateCerts 581 | 582 | global rangerAPI 583 | rangerAPI = RangerAPI(p.adminUrl, p.adminUsername , p.adminPassword , verify) 584 | 585 | result = {} 586 | hdfsServiceName = rangerAPI.getServiceNameByType("hdfs", p.serviceName) 587 | # Perform check before effective operation 588 | for tgtPolicy in p.policies: 589 | groom(tgtPolicy) 590 | for tgtPolicy in p.policies: 591 | policyName = tgtPolicy['name'] 592 | result[policyName] = {} 593 | oldPolicies = rangerAPI.getPolicy(hdfsServiceName, policyName) 594 | debug("oldPolicies: " + repr(oldPolicies)) 595 | #misc.ppprint(oldPolicies) 596 | if len(oldPolicies) > 1: 597 | error("More than one policy with name '{0}' !".format(policyName)) 598 | if p.state == 'present': 599 | if len(oldPolicies) == 0: 600 | policy = newPolicy(tgtPolicy, hdfsServiceName) 601 | #misc.ppprint(p) 602 | rangerAPI.createPolicy(policy) 603 | result[policyName]['action'] = "created" 604 | p.changed = True 605 | else: 606 | oldPolicy = oldPolicies[0] 607 | pid = oldPolicy["id"] 608 | policy = newPolicy(tgtPolicy, hdfsServiceName) 609 | policy["id"] = pid 610 | result[policyName]['id'] = pid 611 | if isPolicyIdentical(oldPolicy, policy): 612 | result[policyName]['action'] = "none" 613 | else: 614 | result[policyName]['action'] = "updated" 615 | rangerAPI.updatePolicy(policy) 616 | p.changed = True 617 | #misc.ppprint(oldPolicy) 618 | elif p.state == 'absent': 619 | if len(oldPolicies) == 1: 620 | rangerAPI.deletePolicy(oldPolicies[0]["id"]) 621 | result[policyName]['action'] = "deleted" 622 | p.changed = True 623 | else: 624 | result[policyName]['action'] = "none" 625 | 626 | cleanup() 627 | module.exit_json( 628 | changed = p.changed, 629 | policies = result, 630 | logs = logs 631 | ) 632 | 633 | 634 | 635 | from ansible.module_utils.basic import * #@UnusedWildImport 636 | 637 | if __name__ == '__main__': 638 | main() 639 | 640 | -------------------------------------------------------------------------------- /library/ranger_hive_policies.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | # (c) 2017, BROADSoftware 5 | # 6 | # This software is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This software is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this software. If not, see . 18 | 19 | 20 | DOCUMENTATION = ''' 21 | --- 22 | module: ranger_hive_policies 23 | short_description: Manage definition of hive Policy in Apache Ranger 24 | description: 25 | - This module will allow you to manage Hive policy in Apache Ranger. 26 | - Please refer to Apache Ranger documentation for authorization policy concept and usage. 27 | options: 28 | admin_url: 29 | description: 30 | - The Ranger base URL to access Ranger API. Same host:port as the Ranger Admin GUI. Typically http://myranger.server.com:6080 or https://myranger.server.com:6182 31 | required: true 32 | default: None 33 | aliases: [] 34 | admin_username: 35 | description: 36 | - The user name to log on the Ranger Admin. Must have enough rights to manage policies. 37 | - Also accepts the special value C(KERBEROS). In such case, a valid Kerberos ticket must exist for the ansible_user account on the target system. (A C(kinit) must be issued under this account). 38 | Then HDFS operation will be performed on behalf of the user defined by the Kerberos ticket. 39 | required: true 40 | default: None 41 | aliases: [] 42 | admin_password: 43 | description: 44 | - The password associated with the admin_username 45 | required: true 46 | default: None 47 | aliases: [] 48 | validate_certs: 49 | description: 50 | - Useful if Ranger Admin connection is using SSL. If no, SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates. 51 | required: false 52 | default: True 53 | aliases: [] 54 | ca_bundle_file: 55 | description: 56 | - Useful if Ranger Admin connection is using SSL. Allow to specify a CA_BUNDLE file, a file that contains root and intermediate certificates to validate the Ranger Admin certificate. 57 | - In its simplest case, it could be a file containing the server certificate in .pem format. 58 | - This file will be looked up on the remote system, on which this module will be executed. 59 | required: false 60 | default: None 61 | aliases: [] 62 | service_name: 63 | description: 64 | - In most cases, you should not need to set this parameter. It define the Ranger Admin Hive service, typically _hive. 65 | - It must be set if there are several such services defined in your Ranger Admin configuration, to select the one you intend to use. 66 | required: false 67 | default: None 68 | aliases: [] 69 | state: 70 | description: 71 | - Whether to install (present) or remove (absent) these policies 72 | required: false 73 | default: present 74 | choices: [ present, absent ] 75 | policies: 76 | description: 77 | - The list of policies you want to be defined by this operation. 78 | required: true 79 | default: None 80 | aliases: [] 81 | policies[0..n].name: 82 | description: 83 | - The name of the policy. Must be unique across the system. 84 | required: true 85 | default: None 86 | aliases: [] 87 | policies[0..n].databases: 88 | description: 89 | - A list of Hive databases this policy will apply on. Accept wildcard characters '*' and '?' 90 | required: true 91 | default: None 92 | aliases: [] 93 | policies[0..n].tables: 94 | description: 95 | - A list of Hive tables this policy will apply on. Accept wildcard characters '*' and '?'. This is exclusive of 'udfs' 96 | required: true 97 | default: None 98 | aliases: [] 99 | policies[0..n].columns: 100 | description: 101 | - A list of Hive columns this policy will apply on. Accept wildcard characters '*' and '?'. This is exclusive of 'udfs' 102 | required: true 103 | default: None 104 | aliases: [] 105 | policies[0..n].udfs: 106 | description: 107 | - A list of Hive UDFs this policy will apply on. Accept wildcard characters '*' and '?'. This is exclusive of 'tables' and 'columns' 108 | required: true 109 | default: None 110 | aliases: [] 111 | policies[0..n].enabled: 112 | description: 113 | - Whether this policy is enabled. 114 | required: false 115 | default: True 116 | aliases: [] 117 | policies[0..n].audit: 118 | description: 119 | - Whether this policy is audited 120 | required: false 121 | default: True 122 | aliases: [] 123 | policies[0..n].permissions: 124 | description: 125 | - A list of permissions associated to this policy 126 | required: True 127 | default: None 128 | aliases: [] 129 | policies[0..n].permissions[0..n].users: 130 | description: 131 | - A list of users this permission will apply on. 132 | required: false 133 | default: None 134 | aliases: [] 135 | policies[0..n].permissions[0..n].groups: 136 | description: 137 | - A list of groups this permission will apply on. 138 | required: false 139 | default: None 140 | aliases: [] 141 | policies[0..n].permissions[0..n].accesses: 142 | description: 143 | - A list of access right granted by this permission. 144 | required: True 145 | default: None 146 | aliases: [] 147 | policies[0..n].permissions[0..n].delegate_admin: 148 | description: 149 | - When a policy is assigned to a user or a group of users those users become the delegated admin. The delegated admin can update, delete the policies. 150 | required: false 151 | default: False 152 | aliases: [] 153 | 154 | author: 155 | - "Serge ALEXANDRE" 156 | 157 | ''' 158 | 159 | 160 | EXAMPLES = ''' 161 | 162 | # This playbook snippet will: 163 | # - For all columns of all tables of databases mydb and mydb2: 164 | # - select, and update on all users of group 'users' 165 | # - Full accesses including admin rights to the user 'admin' 166 | # 167 | # Note also how we handle Certificate bundle, by first copying it on the remote site. 168 | # 169 | - hosts: edge_node1 170 | roles: 171 | - ranger_modules 172 | tasks: 173 | - name: Copy ca_bundle 174 | copy: src=../rangersrv_cert.pem dest=/etc/security/rangersrc_cert.pem owner=root mode=0400 175 | - name: Apply ranger Hive policy 176 | ranger_hive_policies: 177 | state: present 178 | admin_url: https://ranger.mycompany.com:6182 179 | admin_username: admin 180 | admin_password: admin 181 | validate_certs: yes 182 | ca_bundle_file: /etc/security/rangersrv_cert.pem 183 | policies: 184 | - name: "testdb_testtable1" 185 | databases: 186 | - mydb 187 | - mydb2 188 | tables: 189 | - "*" 190 | columns: 191 | - "*" 192 | audit: false 193 | enabled: false 194 | permissions: 195 | - groups: 196 | - users 197 | accesses: 198 | - select 199 | - update 200 | - users: 201 | - admin 202 | accesses: 203 | - all 204 | delegate_admin: true 205 | 206 | 207 | ''' 208 | import warnings 209 | from sets import Set 210 | 211 | HAS_REQUESTS = False 212 | try: 213 | import requests 214 | from requests.auth import HTTPBasicAuth 215 | HAS_REQUESTS = True 216 | except (ImportError, AttributeError): 217 | # AttributeError if __version__ is not present 218 | pass 219 | 220 | HAS_KERBEROS = False 221 | try: 222 | from requests_kerberos import HTTPKerberosAuth 223 | HAS_KERBEROS = True 224 | except ImportError: 225 | pass 226 | 227 | # Global, to allow access from error 228 | module = None 229 | logs = [] 230 | logLevel = 'None' 231 | 232 | def log(level, message): 233 | x = level+':' + message 234 | logs.append(x) 235 | 236 | def debug(message): 237 | if logLevel == 'debug': 238 | log("DEBUG", message) 239 | 240 | def info(message): 241 | if logLevel == "info" or logLevel == "debug": 242 | log("INFO", message) 243 | 244 | class RangerAPI: 245 | 246 | def __init__(self, endpoint, username, password, verify): 247 | self.endpoint = endpoint 248 | self.username = username 249 | self.password = password 250 | self.verify = verify 251 | self.serviceNamesByType = None 252 | if self.username == "KERBEROS": 253 | if not HAS_KERBEROS: 254 | error("'python-requests-kerberos' package is not installed") 255 | else: 256 | self.auth = HTTPKerberosAuth() 257 | else: 258 | self.auth = HTTPBasicAuth(self.username, self.password) 259 | warnings.filterwarnings("ignore", ".*Unverified HTTPS.*") 260 | warnings.filterwarnings("ignore", ".*Certificate has no `subjectAltName`.*") 261 | 262 | def get(self, path): 263 | url = self.endpoint + "/" + path 264 | resp = requests.get(url, auth = self.auth, verify=self.verify) 265 | debug("HTTP GET({}) --> {}".format(url, resp.status_code)) 266 | if resp.status_code == 200: # Warning: Failing auth may trigger a 200 with an HTML login page. 267 | contentType = resp.headers["content-type"] if ("content-type" in resp.headers) else "unknow" 268 | debug("Response content-type:{}".format(contentType)) 269 | if "json" in contentType: 270 | result = resp.json() 271 | return result 272 | elif contentType.startswith("text/html"): 273 | error("HTML content received. May be Ranger login or password is invalid!") 274 | else: 275 | error("Invalid 'content-type' ({}) in response".format(contentType)) 276 | elif resp.status_code == 401 and self.username == "KERBEROS": 277 | error("KERBEROS authentication failed! (Did you perform kinit ?)") 278 | else: 279 | error("Invalid returned http code '{0}' when calling GET on '{1}'".format(resp.status_code, url)) 280 | 281 | def getServiceNameByType(self, stype, candidate=None): 282 | if self.serviceNamesByType == None: 283 | self.serviceNamesByType = {} 284 | services = self.get("service/public/v2/api/service") 285 | for service in services: 286 | if not service["type"] in self.serviceNamesByType: 287 | self.serviceNamesByType[service['type']] = [] 288 | self.serviceNamesByType[service['type']].append(service['name']) 289 | #logger.debug(self.serviceNamesByType) 290 | if stype not in self.serviceNamesByType: 291 | error("Service type '{0}' is not defined in this Ranger instance".format(stype) ) 292 | serviceNames = self.serviceNamesByType[stype] 293 | if candidate != None: 294 | if candidate not in serviceNames: 295 | error("Service {0} is not defined on this Ranger instance".format(candidate)) 296 | return candidate 297 | else: 298 | if len(serviceNames) != 1: 299 | error("There is several choice for '{0}' service: {1}. Please configure one explicitly!".format(stype, serviceNames)) 300 | return serviceNames[0] 301 | 302 | def getPolicy(self, service, policyName): 303 | return self.get("service/public/v2/api/service/{0}/policy?policyName={1}".format(service, policyName)) 304 | 305 | def createPolicy(self, policy): 306 | url = self.endpoint + '/service/public/v2/api/policy' 307 | resp = requests.post(url, auth = self.auth, json=policy, headers={'content-type': 'application/json'}, verify=self.verify) 308 | debug("HTTP POST({}) --> {}".format(url, resp.status_code)) 309 | if resp.status_code != 200: 310 | error("Invalid returned http code '{0}' when calling POST on '{1}': {2}".format(resp.status_code, url, resp.text)) 311 | 312 | def deletePolicy(self, pid): 313 | url = "{0}/service/public/v2/api/policy/{1}".format(self.endpoint, pid) 314 | resp = requests.delete(url, auth = self.auth, verify=self.verify) 315 | debug("HTTP DELETE({}) --> {}".format(url, resp.status_code)) 316 | if resp.status_code < 200 or resp.status_code > 299: 317 | error("Invalid returned http code '{0}' when calling DELETE on '{1}: {2}'".format(resp.status_code, url, resp.text)) 318 | 319 | def updatePolicy(self, policy): 320 | url = "{0}/service/public/v2/api/policy/{1}".format(self.endpoint, policy["id"]) 321 | resp = requests.put(url, auth = self.auth, json=policy, headers={'content-type': 'application/json'}, verify=self.verify) 322 | debug("HTTP PUT({}) --> {}".format(url, resp.status_code)) 323 | if resp.status_code != 200: 324 | error("Invalid returned http code '{0}' when calling PUT on '{1}': {2}".format(resp.status_code, url, resp.text)) 325 | 326 | def close(self): 327 | pass 328 | 329 | # --------------------------------------------------------------------------------- 330 | 331 | 332 | def digdiff(left, right): 333 | result = { 334 | "missingOnLeft": [], 335 | "missingOnRight": [], 336 | "differsByValue": [], 337 | "differsByType": [] 338 | } 339 | diffValue(left, right, "", result) 340 | return result 341 | 342 | 343 | def diffValue(left, right, path, result): 344 | #print "diffValue(left:{0} right:{1})".format(left, right) 345 | if right == None: 346 | if left != None: 347 | result["differsByValue"].append(path) 348 | else: 349 | pass 350 | else: 351 | if left == None: 352 | result["differsByValue"].append(path) 353 | elif isinstance(left, dict): 354 | if isinstance(right, dict): 355 | diffDict(left, right, path, result) 356 | else: 357 | result["differsByType"].append(path) 358 | elif isinstance(left, list): 359 | if isinstance(right, list): 360 | diffList(left, right, path, result) 361 | else: 362 | result["differsByType"].append(path) 363 | else: 364 | # left is a scalar 365 | left = normalizeType(left) 366 | right = normalizeType(right) 367 | if type(left) != type(right): 368 | #print "********************* type(left):{0} type(right):{1}".format(type(left), type(right)) 369 | result["differsByType"].append(path) 370 | else: 371 | if left != right: 372 | result["differsByValue"].append(path) 373 | else: 374 | pass 375 | 376 | def normalizeType(value): 377 | """ 378 | Try to normalize o type, to be able to compare them 379 | """ 380 | if isinstance(value, unicode): 381 | return str(value) 382 | else: 383 | return value 384 | 385 | 386 | 387 | def diffDict(left, right, path, result): 388 | #print "diffDict(left:{0} right:{1})".format(left, right) 389 | for kl in left: 390 | path2 = path + "." + kl 391 | if kl in right: 392 | diffValue(left[kl], right[kl], path2, result) 393 | else: 394 | result['missingOnRight'].append(path2) 395 | for kr in right: 396 | path2 = path + "." + kr 397 | if kr in left: 398 | pass 399 | else: 400 | result['missingOnLeft'].append(path2) 401 | 402 | 403 | def diffList(left, right, path, result): 404 | for x in range(len(left)): 405 | path2 = path + '[' + str(x) + ']' 406 | if x >= len(right): 407 | result['missingOnRight'].append(path2) 408 | else: 409 | diffValue(left[x], right[x], path2, result) 410 | for x in range(len(left), len(right)): 411 | path2 = path + '[' + str(x) + ']' 412 | result['missingOnLeft'].append(path2) 413 | 414 | 415 | 416 | # --------------------------------------------------------------------------------- 417 | 418 | 419 | ALLOWED_MISSING_ON_RIGHT = Set([".version", ".policyType", ".guid"]) 420 | 421 | def isPolicyIdentical(old, new): 422 | result = digdiff(old, new) 423 | #misc.ppprint(old) 424 | #misc.ppprint(new) 425 | debug("missingOnLeft:{}".format(result['missingOnLeft'])) 426 | debug("missingOnRight:{}".format(result['missingOnRight'])) 427 | debug("differsByType:{}".format(result['differsByType'])) 428 | debug("differsByValue:{}".format(result['differsByValue'])) 429 | if len(result['missingOnLeft']) > 0 or len(result['differsByType']) > 0 or len(result['differsByValue']) > 0: 430 | return False 431 | else: 432 | for missing in result["missingOnRight"]: 433 | if not missing in ALLOWED_MISSING_ON_RIGHT: 434 | return False 435 | return True 436 | 437 | 438 | 439 | # --------------------------------------------------------- Grooming helper function 440 | 441 | def checkListOfStrNotEmpty(base, attr, prefix): 442 | if attr not in base: 443 | error("{0}: Missing attribute '{1}'".format(prefix, attr)) 444 | if not isinstance(base[attr], list): 445 | error("{0}: Attribute '{1}' if of wrong type. Must by a list".format(prefix, attr)) 446 | if len(base[attr]) == 0: 447 | error("{0}: Attribute '{1}': Must have at least one items".format(prefix, attr)) 448 | for v in base[attr]: 449 | if not isinstance(v, basestring) or len(v) == 0: 450 | error("{0}: All items of list '{1}' must be non null string".format(prefix, attr)) 451 | 452 | 453 | def checkListOfStr(base, attr, prefix): 454 | if attr not in base: 455 | base[attr] = [] 456 | else: 457 | if not isinstance(base[attr], list): 458 | error("{0}: Attribute '{1}' if of wrong type. Must by a list".format(prefix, attr)) 459 | for v in base[attr]: 460 | if not isinstance(v, basestring) or len(v) == 0: 461 | error("{0}: All items of list '{1}' must be non null string".format(prefix, attr)) 462 | 463 | def checkTypeWithDefault(base, attr, typ, default, prefix): 464 | if attr not in base: 465 | base[attr] = default 466 | else: 467 | if not isinstance(base[attr], typ): 468 | error("{0}: Attribute '{1}' if of wrong type. Must by a {2}".format(prefix, attr, typ)) 469 | 470 | def checkEnumWithDefault(base, attr, candidates, default, prefix): 471 | if attr not in base: 472 | base[attr] = default 473 | else: 474 | if not isinstance(base[attr], basestring): 475 | error("{0}: Attribute '{1}' if of wrong type. Must by a string".format(prefix, attr)) 476 | else: 477 | if not base[attr] in candidates: 478 | error("{0}: Attribute '{1}' must be one of the following: {2}".format(prefix, attr, candidates)) 479 | 480 | def checkValidAttr(base, validAttrSet, prefix): 481 | for attr in base: 482 | if attr not in validAttrSet: 483 | error("{0}: Invalid attribute '{1}'. Must be one of {2}".format(prefix, attr, validAttrSet)) 484 | 485 | 486 | def groom(policy): 487 | """ 488 | Check and Normalize target policy expression 489 | """ 490 | if 'name' not in policy: 491 | error("There is at least one Hive policy without name!") 492 | if not isinstance(policy["name"], basestring): 493 | error("Hive policy: Attribute 'name' if of wrong type. Must by a string") 494 | prefix = "Hive policy '{0}': ".format(policy['name']) 495 | 496 | 497 | checkValidAttr(policy, ['name', 'tables', 'udfs', 'databases', 'columns', 'state', 'audit', 'enabled', 'permissions'], prefix) 498 | 499 | checkListOfStrNotEmpty(policy, "databases", prefix) 500 | if 'tables' in policy: 501 | checkListOfStrNotEmpty(policy, "tables", prefix) 502 | checkListOfStrNotEmpty(policy, "columns", prefix) 503 | if 'udfs' in policy: 504 | error("{0}: 'tables' and 'udfs' are exclusive!".format(prefix)) 505 | else: 506 | if not 'udfs' in policy: 507 | error("{0}: One of 'tables' and 'udfs' must be defined!".format(prefix)) 508 | else: 509 | checkListOfStrNotEmpty(policy, "udfs", prefix) 510 | 511 | checkTypeWithDefault(policy, "audit", bool, True, prefix) 512 | checkTypeWithDefault(policy, "enabled", bool, True, prefix) 513 | 514 | checkTypeWithDefault(policy, "permissions", list, [], prefix) 515 | 516 | for permission in policy['permissions']: 517 | checkValidAttr(permission, ['users', 'groups', 'accesses', 'delegate_admin'], prefix) 518 | checkListOfStr(permission, 'users', prefix) 519 | checkListOfStr(permission, 'groups', prefix) 520 | checkListOfStr(permission, 'accesses', prefix) 521 | checkTypeWithDefault(permission, 'delegate_admin', bool, False, prefix) 522 | 523 | 524 | def newPolicy(tgtPolicy, service): 525 | policy = { 526 | 'allowExceptions': [], 527 | 'dataMaskPolicyItems': [], 528 | 'denyExceptions': [], 529 | 'denyPolicyItems': [], 530 | 'isAuditEnabled': tgtPolicy['audit'], 531 | 'isEnabled': tgtPolicy['enabled'], 532 | 'name': tgtPolicy['name'], 533 | 'policyItems': [], 534 | 'resources': { 535 | "database": { 536 | "isExcludes": False, 537 | "isRecursive": False, 538 | "values": tgtPolicy["databases"] 539 | } 540 | }, 541 | 'rowFilterPolicyItems': [], 542 | 'service': service 543 | } 544 | if 'udfs' in tgtPolicy and len(tgtPolicy['udfs']) > 0: 545 | policy['resources']['udf'] = { "isExcludes": False, "isRecursive": False, "values": tgtPolicy["udfs"] } 546 | if 'tables' in tgtPolicy and len(tgtPolicy['tables']) > 0: 547 | policy['resources']['table'] = { "isExcludes": False, "isRecursive": False, "values": tgtPolicy["tables"] } 548 | policy['resources']['column'] = { "isExcludes": False, "isRecursive": False, "values": tgtPolicy["columns"] } 549 | for p in tgtPolicy['permissions']: 550 | tp = {} 551 | tp['accesses'] = [] 552 | tp['conditions'] = [] 553 | tp['delegateAdmin'] = p['delegate_admin'] 554 | tp['groups'] = p['groups'] 555 | tp['users'] = p['users'] 556 | for a in p['accesses']: 557 | tp['accesses'].append({ "isAllowed": True, "type": a.lower() }) 558 | policy['policyItems'].append(tp) 559 | return policy 560 | 561 | 562 | rangerAPI = None 563 | 564 | def cleanup(): 565 | if rangerAPI != None: 566 | rangerAPI.close() 567 | 568 | 569 | def error(message): 570 | cleanup() 571 | module.fail_json(msg = message, logs=logs) 572 | 573 | class Parameters: 574 | pass 575 | 576 | 577 | def checkParameters(p): 578 | pass 579 | 580 | def main(): 581 | 582 | global module 583 | module = AnsibleModule( 584 | argument_spec = dict( 585 | state = dict(required=False, choices=['present','absent'], default="present"), 586 | admin_url = dict(required=True, type='str'), 587 | admin_username = dict(required=True, type='str'), 588 | admin_password = dict(required=True, type='str'), 589 | validate_certs = dict(required=False, type='bool', default=True), 590 | ca_bundle_file = dict(required=False, type='str'), 591 | service_name = dict(required=False, type='str'), 592 | policies = dict(required=True, type='list'), 593 | log_level = dict(required=False, default="None") 594 | ), 595 | supports_check_mode=False 596 | ) 597 | 598 | if not HAS_REQUESTS: 599 | module.fail_json(msg="python-requests package is not installed") 600 | 601 | p = Parameters() 602 | p.state = module.params['state'] 603 | p.adminUrl = module.params['admin_url'] 604 | p.adminUsername = module.params['admin_username'] 605 | p.adminPassword = module.params['admin_password'] 606 | p.validateCerts = module.params['validate_certs'] 607 | p.ca_bundleFile = module.params['ca_bundle_file'] 608 | p.serviceName = module.params['service_name'] 609 | p.policies = module.params['policies'] 610 | p.logLevel = module.params['log_level'] 611 | p.changed = False 612 | 613 | global logLevel 614 | logLevel = p.logLevel 615 | 616 | checkParameters(p) 617 | 618 | if p.ca_bundleFile != None: 619 | verify = p.ca_bundleFile 620 | else: 621 | verify = p.validateCerts 622 | 623 | global rangerAPI 624 | rangerAPI = RangerAPI(p.adminUrl, p.adminUsername , p.adminPassword , verify) 625 | 626 | result = {} 627 | hiveServiceName = rangerAPI.getServiceNameByType("hive", p.serviceName) 628 | # Perform check before effective operation 629 | for tgtPolicy in p.policies: 630 | groom(tgtPolicy) 631 | for tgtPolicy in p.policies: 632 | policyName = tgtPolicy['name'] 633 | result[policyName] = {} 634 | oldPolicies = rangerAPI.getPolicy(hiveServiceName, policyName) 635 | debug("oldPolicies: " + repr(oldPolicies)) 636 | #misc.ppprint(oldPolicies) 637 | if len(oldPolicies) > 1: 638 | error("More than one policy with name '{0}' !".format(policyName)) 639 | if p.state == 'present': 640 | if len(oldPolicies) == 0: 641 | policy = newPolicy(tgtPolicy, hiveServiceName) 642 | #misc.ppprint(p) 643 | rangerAPI.createPolicy(policy) 644 | result[policyName]['action'] = "created" 645 | p.changed = True 646 | else: 647 | oldPolicy = oldPolicies[0] 648 | pid = oldPolicy["id"] 649 | policy = newPolicy(tgtPolicy, hiveServiceName) 650 | policy["id"] = pid 651 | result[policyName]['id'] = pid 652 | if isPolicyIdentical(oldPolicy, policy): 653 | result[policyName]['action'] = "none" 654 | else: 655 | result[policyName]['action'] = "updated" 656 | rangerAPI.updatePolicy(policy) 657 | p.changed = True 658 | #misc.ppprint(oldPolicy) 659 | elif p.state == 'absent': 660 | if len(oldPolicies) == 1: 661 | rangerAPI.deletePolicy(oldPolicies[0]["id"]) 662 | result[policyName]['action'] = "deleted" 663 | p.changed = True 664 | else: 665 | result[policyName]['action'] = "none" 666 | 667 | cleanup() 668 | module.exit_json( 669 | changed = p.changed, 670 | policies = result, 671 | logs = logs 672 | ) 673 | 674 | 675 | 676 | from ansible.module_utils.basic import * #@UnusedWildImport 677 | 678 | if __name__ == '__main__': 679 | main() 680 | 681 | -------------------------------------------------------------------------------- /library/ranger_kafka_policies.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | # (c) 2017, BROADSoftware 5 | # 6 | # This software is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This software is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this software. If not, see . 18 | 19 | 20 | DOCUMENTATION = ''' 21 | --- 22 | module: ranger_kafka_policies 23 | short_description: Manage definition of Kafka Policy in Apache Ranger 24 | description: 25 | - This module will allow you to manage Kafka policy in Apache Ranger. 26 | - Please refer to Apache Ranger documentation for authorization policy concept and usage. 27 | options: 28 | admin_url: 29 | description: 30 | - The Ranger base URL to access Ranger API. Same host:port as the Ranger Admin GUI. Typically http://myranger.server.com:6080 or https://myranger.server.com:6182 31 | required: true 32 | default: None 33 | aliases: [] 34 | admin_username: 35 | description: 36 | - The user name to log on the Ranger Admin. Must have enough rights to manage policies. 37 | - Also accepts the special value C(KERBEROS). In such case, a valid Kerberos ticket must exist for the ansible_user account on the target system. (A C(kinit) must be issued under this account). 38 | Then HDFS operation will be performed on behalf of the user defined by the Kerberos ticket. 39 | required: true 40 | default: None 41 | aliases: [] 42 | admin_password: 43 | description: 44 | - The password associated with the admin_username 45 | required: true 46 | default: None 47 | aliases: [] 48 | validate_certs: 49 | description: 50 | - Useful if Ranger Admin connection is using SSL. If no, SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates. 51 | required: false 52 | default: True 53 | aliases: [] 54 | ca_bundle_file: 55 | description: 56 | - Useful if Ranger Admin connection is using SSL. Allow to specify a CA_BUNDLE file, a file that contains root and intermediate certificates to validate the Ranger Admin certificate. 57 | - In its simplest case, it could be a file containing the server certificate in .pem format. 58 | - This file will be looked up on the remote system, on which this module will be executed. 59 | required: false 60 | default: None 61 | aliases: [] 62 | service_name: 63 | description: 64 | - In most cases, you should not need to set this parameter. It define the Ranger Admin Kafka service, typically _kafka. 65 | - It must be set if there are several such services defined in your Ranger Admin configuration, to select the one you intend to use. 66 | required: false 67 | default: None 68 | aliases: [] 69 | state: 70 | description: 71 | - Whether to install (present) or remove (absent) these policies 72 | required: false 73 | default: present 74 | choices: [ present, absent ] 75 | policies: 76 | description: 77 | - The list of policies you want to be defined by this operation. 78 | required: true 79 | default: None 80 | aliases: [] 81 | policies[0..n].name: 82 | description: 83 | - The name of the policy. Must be unique across the system. 84 | required: true 85 | default: None 86 | aliases: [] 87 | policies[0..n].topics: 88 | description: 89 | - A list of Kafka topics this policy will apply on. Accept wildcard characters '*' and '?' 90 | required: true 91 | default: None 92 | aliases: [] 93 | policies[0..n].enabled: 94 | description: 95 | - Whether this policy is enabled. 96 | required: false 97 | default: True 98 | aliases: [] 99 | policies[0..n].audit: 100 | description: 101 | - Whether this policy is audited 102 | required: false 103 | default: True 104 | aliases: [] 105 | policies[0..n].permissions: 106 | description: 107 | - A list of permissions associated to this policy 108 | required: True 109 | default: None 110 | aliases: [] 111 | policies[0..n].permissions[0..n].users: 112 | description: 113 | - A list of users this permission will apply on. 114 | required: false 115 | default: None 116 | aliases: [] 117 | policies[0..n].permissions[0..n].groups: 118 | description: 119 | - A list of groups this permission will apply on. 120 | required: false 121 | default: None 122 | aliases: [] 123 | policies[0..n].permissions[0..n].accesses: 124 | description: 125 | - A list of access right granted by this permission. 126 | required: True 127 | default: None 128 | aliases: [] 129 | policies[0..n].permissions[0..n].ip_addresses: 130 | description: 131 | - A list of source IP addresses to be bound to this permission 132 | required: false 133 | default: None 134 | aliases: [] 135 | policies[0..n].permissions[0..n].delegate_admin: 136 | description: 137 | - When a policy is assigned to a user or a group of users those users become the delegated admin. The delegated admin can update, delete the policies. 138 | required: false 139 | default: False 140 | aliases: [] 141 | 142 | author: 143 | - "Serge ALEXANDRE" 144 | 145 | ''' 146 | 147 | 148 | EXAMPLES = ''' 149 | 150 | # Allow user 'app1' to publish to Kafka topic 'topic1'. And allow user 'app2' and all users belonging to groups 'grp1 and grp2 to consume. 151 | 152 | - hosts: edge_node1 153 | roles: 154 | - ranger_modules 155 | tasks: 156 | - ranger_kafka_policies: 157 | state: present 158 | admin_url: https://ranger.mycompany.com:6182 159 | admin_username: admin 160 | admin_password: admin 161 | validate_certs: no 162 | policies: 163 | - name: "kpolicy1" 164 | topics: 165 | - "topic1" 166 | permissions: 167 | - users: 168 | - app1 169 | accesses: 170 | - Publish 171 | - users: 172 | - app2 173 | groups: 174 | - grp1 175 | - grp2 176 | accesses: 177 | - consume 178 | 179 | 180 | 181 | # Same result, expressed in a different way 182 | - hosts: en1 183 | vars: 184 | policy1: 185 | { name: kpolicy1, topics: [ topic1 ], permissions: [ { users: [ app1 ], accesses: [ publish ] }, { users: [ app2 ], groups: [ grp1, grp2 ], accesses: [ consume ] } ] } 186 | roles: 187 | - ranger_modules 188 | tasks: 189 | - ranger_kafka_policies: 190 | state: present 191 | admin_url: https://nn1.hdp13.bsa.broadsoftware.com:6182 192 | admin_username: admin 193 | admin_password: admin 194 | validate_certs: no 195 | policies: 196 | - "{{ policy1 }}" 197 | 198 | 199 | 200 | ''' 201 | import warnings 202 | from sets import Set 203 | 204 | HAS_REQUESTS = False 205 | try: 206 | import requests 207 | from requests.auth import HTTPBasicAuth 208 | HAS_REQUESTS = True 209 | except (ImportError, AttributeError): 210 | # AttributeError if __version__ is not present 211 | pass 212 | 213 | HAS_KERBEROS = False 214 | try: 215 | from requests_kerberos import HTTPKerberosAuth 216 | HAS_KERBEROS = True 217 | except ImportError: 218 | pass 219 | 220 | # Global, to allow access from error 221 | module = None 222 | logs = [] 223 | logLevel = 'None' 224 | 225 | def log(level, message): 226 | x = level+':' + message 227 | logs.append(x) 228 | 229 | def debug(message): 230 | if logLevel == 'debug': 231 | log("DEBUG", message) 232 | 233 | def info(message): 234 | if logLevel == "info" or logLevel == "debug": 235 | log("INFO", message) 236 | 237 | class RangerAPI: 238 | 239 | def __init__(self, endpoint, username, password, verify): 240 | self.endpoint = endpoint 241 | self.username = username 242 | self.password = password 243 | self.verify = verify 244 | self.serviceNamesByType = None 245 | if self.username == "KERBEROS": 246 | if not HAS_KERBEROS: 247 | error("'python-requests-kerberos' package is not installed") 248 | else: 249 | self.auth = HTTPKerberosAuth() 250 | else: 251 | self.auth = HTTPBasicAuth(self.username, self.password) 252 | warnings.filterwarnings("ignore", ".*Unverified HTTPS.*") 253 | warnings.filterwarnings("ignore", ".*Certificate has no `subjectAltName`.*") 254 | 255 | def get(self, path): 256 | url = self.endpoint + "/" + path 257 | resp = requests.get(url, auth = self.auth, verify=self.verify) 258 | debug("HTTP GET({}) --> {}".format(url, resp.status_code)) 259 | if resp.status_code == 200: # Warning: Failing auth may trigger a 200 with an HTML login page. 260 | contentType = resp.headers["content-type"] if ("content-type" in resp.headers) else "unknow" 261 | debug("Response content-type:{}".format(contentType)) 262 | if "json" in contentType: 263 | result = resp.json() 264 | return result 265 | elif contentType.startswith("text/html"): 266 | error("HTML content received. May be Ranger login or password is invalid!") 267 | else: 268 | error("Invalid 'content-type' ({}) in response".format(contentType)) 269 | elif resp.status_code == 401 and self.username == "KERBEROS": 270 | error("KERBEROS authentication failed! (Did you perform kinit ?)") 271 | else: 272 | error("Invalid returned http code '{0}' when calling GET on '{1}'".format(resp.status_code, url)) 273 | 274 | def getServiceNameByType(self, stype, candidate=None): 275 | if self.serviceNamesByType == None: 276 | self.serviceNamesByType = {} 277 | services = self.get("service/public/v2/api/service") 278 | for service in services: 279 | if not service["type"] in self.serviceNamesByType: 280 | self.serviceNamesByType[service['type']] = [] 281 | self.serviceNamesByType[service['type']].append(service['name']) 282 | #logger.debug(self.serviceNamesByType) 283 | if stype not in self.serviceNamesByType: 284 | error("Service type '{0}' is not defined in this Ranger instance".format(stype) ) 285 | serviceNames = self.serviceNamesByType[stype] 286 | if candidate != None: 287 | if candidate not in serviceNames: 288 | error("Service {0} is not defined on this Ranger instance".format(candidate)) 289 | return candidate 290 | else: 291 | if len(serviceNames) != 1: 292 | error("There is several choice for '{0}' service: {1}. Please configure one explicitly!".format(stype, serviceNames)) 293 | return serviceNames[0] 294 | 295 | def getPolicy(self, service, policyName): 296 | return self.get("service/public/v2/api/service/{0}/policy?policyName={1}".format(service, policyName)) 297 | 298 | def createPolicy(self, policy): 299 | url = self.endpoint + '/service/public/v2/api/policy' 300 | resp = requests.post(url, auth = self.auth, json=policy, headers={'content-type': 'application/json'}, verify=self.verify) 301 | debug("HTTP POST({}) --> {}".format(url, resp.status_code)) 302 | if resp.status_code != 200: 303 | error("Invalid returned http code '{0}' when calling POST on '{1}': {2}".format(resp.status_code, url, resp.text)) 304 | 305 | def deletePolicy(self, pid): 306 | url = "{0}/service/public/v2/api/policy/{1}".format(self.endpoint, pid) 307 | resp = requests.delete(url, auth = self.auth, verify=self.verify) 308 | debug("HTTP DELETE({}) --> {}".format(url, resp.status_code)) 309 | if resp.status_code < 200 or resp.status_code > 299: 310 | error("Invalid returned http code '{0}' when calling DELETE on '{1}: {2}'".format(resp.status_code, url, resp.text)) 311 | 312 | def updatePolicy(self, policy): 313 | url = "{0}/service/public/v2/api/policy/{1}".format(self.endpoint, policy["id"]) 314 | resp = requests.put(url, auth = self.auth, json=policy, headers={'content-type': 'application/json'}, verify=self.verify) 315 | debug("HTTP PUT({}) --> {}".format(url, resp.status_code)) 316 | if resp.status_code != 200: 317 | error("Invalid returned http code '{0}' when calling PUT on '{1}': {2}".format(resp.status_code, url, resp.text)) 318 | 319 | def close(self): 320 | pass 321 | 322 | # --------------------------------------------------------------------------------- 323 | 324 | 325 | def digdiff(left, right): 326 | result = { 327 | "missingOnLeft": [], 328 | "missingOnRight": [], 329 | "differsByValue": [], 330 | "differsByType": [] 331 | } 332 | diffValue(left, right, "", result) 333 | return result 334 | 335 | 336 | def diffValue(left, right, path, result): 337 | #print "diffValue(left:{0} right:{1})".format(left, right) 338 | if right == None: 339 | if left != None: 340 | result["differsByValue"].append(path) 341 | else: 342 | pass 343 | else: 344 | if left == None: 345 | result["differsByValue"].append(path) 346 | elif isinstance(left, dict): 347 | if isinstance(right, dict): 348 | diffDict(left, right, path, result) 349 | else: 350 | result["differsByType"].append(path) 351 | elif isinstance(left, list): 352 | if isinstance(right, list): 353 | diffList(left, right, path, result) 354 | else: 355 | result["differsByType"].append(path) 356 | else: 357 | # left is a scalar 358 | left = normalizeType(left) 359 | right = normalizeType(right) 360 | if type(left) != type(right): 361 | #print "********************* type(left):{0} type(right):{1}".format(type(left), type(right)) 362 | result["differsByType"].append(path) 363 | else: 364 | if left != right: 365 | result["differsByValue"].append(path) 366 | else: 367 | pass 368 | 369 | def normalizeType(value): 370 | """ 371 | Try to normalize o type, to be able to compare them 372 | """ 373 | if isinstance(value, unicode): 374 | return str(value) 375 | else: 376 | return value 377 | 378 | 379 | 380 | def diffDict(left, right, path, result): 381 | #print "diffDict(left:{0} right:{1})".format(left, right) 382 | for kl in left: 383 | path2 = path + "." + kl 384 | if kl in right: 385 | diffValue(left[kl], right[kl], path2, result) 386 | else: 387 | result['missingOnRight'].append(path2) 388 | for kr in right: 389 | path2 = path + "." + kr 390 | if kr in left: 391 | pass 392 | else: 393 | result['missingOnLeft'].append(path2) 394 | 395 | 396 | def diffList(left, right, path, result): 397 | for x in range(len(left)): 398 | path2 = path + '[' + str(x) + ']' 399 | if x >= len(right): 400 | result['missingOnRight'].append(path2) 401 | else: 402 | diffValue(left[x], right[x], path2, result) 403 | for x in range(len(left), len(right)): 404 | path2 = path + '[' + str(x) + ']' 405 | result['missingOnLeft'].append(path2) 406 | 407 | 408 | 409 | # --------------------------------------------------------------------------------- 410 | 411 | 412 | ALLOWED_MISSING_ON_RIGHT = Set([".version", ".policyType", ".guid"]) 413 | 414 | def isPolicyIdentical(old, new): 415 | result = digdiff(old, new) 416 | #misc.ppprint(old) 417 | #misc.ppprint(new) 418 | debug("missingOnLeft:{}".format(result['missingOnLeft'])) 419 | debug("missingOnRight:{}".format(result['missingOnRight'])) 420 | debug("differsByType:{}".format(result['differsByType'])) 421 | debug("differsByValue:{}".format(result['differsByValue'])) 422 | if len(result['missingOnLeft']) > 0 or len(result['differsByType']) > 0 or len(result['differsByValue']) > 0: 423 | return False 424 | else: 425 | for missing in result["missingOnRight"]: 426 | if not missing in ALLOWED_MISSING_ON_RIGHT: 427 | return False 428 | return True 429 | 430 | 431 | 432 | # --------------------------------------------------------- Grooming helper function 433 | 434 | def checkListOfStrNotEmpty(base, attr, prefix): 435 | if attr not in base: 436 | error("{0}: Missing attribute '{1}'".format(prefix, attr)) 437 | if not isinstance(base[attr], list): 438 | error("{0}: Attribute '{1}' if of wrong type. Must by a list".format(prefix, attr)) 439 | if len(base[attr]) == 0: 440 | error("{0}: Attribute '{1}': Must have at least one items".format(prefix, attr)) 441 | for v in base[attr]: 442 | if not isinstance(v, basestring) or len(v) == 0: 443 | error("{0}: All items of list '{1}' must be non null string".format(prefix, attr)) 444 | 445 | 446 | def checkListOfStr(base, attr, prefix): 447 | if attr not in base: 448 | base[attr] = [] 449 | else: 450 | if not isinstance(base[attr], list): 451 | error("{0}: Attribute '{1}' if of wrong type. Must by a list".format(prefix, attr)) 452 | for v in base[attr]: 453 | if not isinstance(v, basestring) or len(v) == 0: 454 | error("{0}: All items of list '{1}' must be non null string".format(prefix, attr)) 455 | 456 | def checkTypeWithDefault(base, attr, typ, default, prefix): 457 | if attr not in base: 458 | base[attr] = default 459 | else: 460 | if not isinstance(base[attr], typ): 461 | error("{0}: Attribute '{1}' if of wrong type. Must by a {2}".format(prefix, attr, typ)) 462 | 463 | def checkEnumWithDefault(base, attr, candidates, default, prefix): 464 | if attr not in base: 465 | base[attr] = default 466 | else: 467 | if not isinstance(base[attr], basestring): 468 | error("{0}: Attribute '{1}' if of wrong type. Must by a string".format(prefix, attr)) 469 | else: 470 | if not base[attr] in candidates: 471 | error("{0}: Attribute '{1}' must be one of the following: {2}".format(prefix, attr, candidates)) 472 | 473 | def checkValidAttr(base, validAttrSet, prefix): 474 | for attr in base: 475 | if attr not in validAttrSet: 476 | error("{0}: Invalid attribute '{1}'. Must be one of {2}".format(prefix, attr, validAttrSet)) 477 | 478 | 479 | 480 | def groom(policy): 481 | """ 482 | Check and Normalize target policy expression 483 | """ 484 | if 'name' not in policy: 485 | error("There is at least one Kafka policy without name!") 486 | if not isinstance(policy["name"], basestring): 487 | error("Kafka policy: Attribute 'name' if of wrong type. Must by a string") 488 | prefix = "Kafka policy '{0}': ".format(policy['name']) 489 | 490 | checkValidAttr(policy, ['name', 'topics', 'audit', 'enabled', 'permissions'], prefix) 491 | 492 | checkListOfStrNotEmpty(policy, "topics", prefix) 493 | 494 | checkTypeWithDefault(policy, "audit", bool, True, prefix) 495 | checkTypeWithDefault(policy, "enabled", bool, True, prefix) 496 | 497 | checkTypeWithDefault(policy, "permissions", list, [], prefix) 498 | 499 | for permission in policy['permissions']: 500 | checkValidAttr(permission, ['users', 'groups', 'accesses', 'ip_addresses', 'delegate_admin'], prefix) 501 | checkListOfStr(permission, 'users', prefix) 502 | checkListOfStr(permission, 'groups', prefix) 503 | checkListOfStr(permission, 'accesses', prefix) 504 | checkListOfStr(permission, 'ip_addresses', prefix) 505 | checkTypeWithDefault(permission, 'delegate_admin', bool, False, prefix) 506 | 507 | 508 | 509 | 510 | def newPolicy(tgtPolicy, service): 511 | policy = { 512 | 'allowExceptions': [], 513 | 'dataMaskPolicyItems': [], 514 | 'denyExceptions': [], 515 | 'denyPolicyItems': [], 516 | 'isAuditEnabled': tgtPolicy['audit'], 517 | 'isEnabled': tgtPolicy['enabled'], 518 | 'name': tgtPolicy['name'], 519 | 'policyItems': [], 520 | 'resources': { 521 | "topic": { 522 | "isExcludes": False, 523 | "isRecursive": False, 524 | "values": tgtPolicy["topics"] 525 | } 526 | }, 527 | 'rowFilterPolicyItems': [], 528 | 'service': service 529 | } 530 | for p in tgtPolicy['permissions']: 531 | tp = {} 532 | tp['accesses'] = [] 533 | tp['conditions'] = [] 534 | tp['delegateAdmin'] = p['delegate_admin'] 535 | tp['groups'] = p['groups'] 536 | tp['users'] = p['users'] 537 | for a in p['accesses']: 538 | tp['accesses'].append({ "isAllowed": True, "type": a.lower() }) 539 | if 'ip_addresses' in p and len(p['ip_addresses']) > 0: 540 | tp['conditions'].append({ "type": "ip-range", "values": p['ip_addresses']}) 541 | policy['policyItems'].append(tp) 542 | return policy 543 | 544 | 545 | rangerAPI = None 546 | 547 | def cleanup(): 548 | if rangerAPI != None: 549 | rangerAPI.close() 550 | 551 | 552 | def error(message): 553 | cleanup() 554 | module.fail_json(msg = message, logs=logs) 555 | 556 | class Parameters: 557 | pass 558 | 559 | 560 | def checkParameters(p): 561 | pass 562 | 563 | def main(): 564 | 565 | global module 566 | module = AnsibleModule( 567 | argument_spec = dict( 568 | state = dict(required=False, choices=['present','absent'], default="present"), 569 | admin_url = dict(required=True, type='str'), 570 | admin_username = dict(required=True, type='str'), 571 | admin_password = dict(required=True, type='str'), 572 | validate_certs = dict(required=False, type='bool', default=True), 573 | ca_bundle_file = dict(required=False, type='str'), 574 | service_name = dict(required=False, type='str'), 575 | policies = dict(required=True, type='list'), 576 | log_level = dict(required=False, default="None") 577 | ), 578 | supports_check_mode=False 579 | ) 580 | 581 | if not HAS_REQUESTS: 582 | module.fail_json(msg="python-requests package is not installed") 583 | 584 | p = Parameters() 585 | p.state = module.params['state'] 586 | p.adminUrl = module.params['admin_url'] 587 | p.adminUsername = module.params['admin_username'] 588 | p.adminPassword = module.params['admin_password'] 589 | p.validateCerts = module.params['validate_certs'] 590 | p.ca_bundleFile = module.params['ca_bundle_file'] 591 | p.serviceName = module.params['service_name'] 592 | p.policies = module.params['policies'] 593 | p.logLevel = module.params['log_level'] 594 | p.changed = False 595 | 596 | global logLevel 597 | logLevel = p.logLevel 598 | 599 | checkParameters(p) 600 | 601 | if p.ca_bundleFile != None: 602 | verify = p.ca_bundleFile 603 | else: 604 | verify = p.validateCerts 605 | 606 | global rangerAPI 607 | rangerAPI = RangerAPI(p.adminUrl, p.adminUsername , p.adminPassword , verify) 608 | 609 | result = {} 610 | kafkaServiceName = rangerAPI.getServiceNameByType("kafka", p.serviceName) 611 | # Perform check before effective operation 612 | for tgtPolicy in p.policies: 613 | groom(tgtPolicy) 614 | for tgtPolicy in p.policies: 615 | policyName = tgtPolicy['name'] 616 | result[policyName] = {} 617 | oldPolicies = rangerAPI.getPolicy(kafkaServiceName, policyName) 618 | debug("oldPolicies: " + repr(oldPolicies)) 619 | #misc.ppprint(oldPolicies) 620 | if len(oldPolicies) > 1: 621 | error("More than one policy with name '{0}' !".format(policyName)) 622 | if p.state == 'present': 623 | if len(oldPolicies) == 0: 624 | policy = newPolicy(tgtPolicy, kafkaServiceName) 625 | #misc.ppprint(p) 626 | rangerAPI.createPolicy(policy) 627 | result[policyName]['action'] = "created" 628 | p.changed = True 629 | else: 630 | oldPolicy = oldPolicies[0] 631 | pid = oldPolicy["id"] 632 | policy = newPolicy(tgtPolicy, kafkaServiceName) 633 | policy["id"] = pid 634 | result[policyName]['id'] = pid 635 | if isPolicyIdentical(oldPolicy, policy): 636 | result[policyName]['action'] = "none" 637 | else: 638 | result[policyName]['action'] = "updated" 639 | rangerAPI.updatePolicy(policy) 640 | p.changed = True 641 | #misc.ppprint(oldPolicy) 642 | elif p.state == 'absent': 643 | if len(oldPolicies) == 1: 644 | rangerAPI.deletePolicy(oldPolicies[0]["id"]) 645 | result[policyName]['action'] = "deleted" 646 | p.changed = True 647 | else: 648 | result[policyName]['action'] = "none" 649 | 650 | cleanup() 651 | module.exit_json( 652 | changed = p.changed, 653 | policies = result, 654 | logs = logs 655 | ) 656 | 657 | 658 | 659 | from ansible.module_utils.basic import * #@UnusedWildImport 660 | 661 | if __name__ == '__main__': 662 | main() 663 | 664 | -------------------------------------------------------------------------------- /library/ranger_storm_policies.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | # (c) 2018, BROADSoftware 5 | # 6 | # This software is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This software is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this software. If not, see . 18 | 19 | 20 | DOCUMENTATION = ''' 21 | --- 22 | module: ranger_storm_policies 23 | short_description: Manage definition of Storm Policy in Apache Ranger 24 | description: 25 | - This module will allow you to manage Storm policies in Apache Ranger. 26 | - Please refer to Apache Ranger documentation for authorization policy concept and usage. 27 | options: 28 | admin_url: 29 | description: 30 | - The Ranger base URL to access Ranger API. Same host:port as the Ranger Admin GUI. Typically http://myranger.server.com:6080 or https://myranger.server.com:6182 31 | required: true 32 | default: None 33 | aliases: [] 34 | admin_username: 35 | description: 36 | - The user name to log on the Ranger Admin. Must have enough rights to manage policies. 37 | - Also accepts the special value C(KERBEROS). In such case, a valid Kerberos ticket must exist for the ansible_user account on the target system. (A C(kinit) must be issued under this account). 38 | Then HDFS operation will be performed on behalf of the user defined by the Kerberos ticket. 39 | required: true 40 | default: None 41 | aliases: [] 42 | admin_password: 43 | description: 44 | - The password associated with the admin_username 45 | required: true 46 | default: None 47 | aliases: [] 48 | validate_certs: 49 | description: 50 | - Useful if Ranger Admin connection is using SSL. If no, SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates. 51 | required: false 52 | default: True 53 | aliases: [] 54 | ca_bundle_file: 55 | description: 56 | - Useful if Ranger Admin connection is using SSL. Allow to specify a CA_BUNDLE file, a file that contains root and intermediate certificates to validate the Ranger Admin certificate. 57 | - In its simplest case, it could be a file containing the server certificate in .pem format. 58 | - This file will be looked up on the remote system, on which this module will be executed. 59 | required: false 60 | default: None 61 | aliases: [] 62 | service_name: 63 | description: 64 | - In most cases, you should not need to set this parameter. It define the Ranger Admin Storm service, typically _storm. 65 | - It must be set if there are several such services defined in your Ranger Admin configuration, to select the one you intend to use. 66 | required: false 67 | default: None 68 | aliases: [] 69 | state: 70 | description: 71 | - Whether to install (present) or remove (absent) these policies 72 | required: false 73 | default: present 74 | choices: [ present, absent ] 75 | policies: 76 | description: 77 | - The list of policies you want to be defined by this operation. 78 | required: true 79 | default: None 80 | aliases: [] 81 | policies[0..n].name: 82 | description: 83 | - The name of the policy. Must be unique across the system. 84 | required: true 85 | default: None 86 | aliases: [] 87 | policies[0..n].topologies: 88 | description: 89 | - A list of Storm topologies this policy will apply on. Accept wildcard characters '*' and '?' 90 | required: true 91 | default: None 92 | aliases: [] 93 | policies[0..n].enabled: 94 | description: 95 | - Whether this policy is enabled. 96 | required: false 97 | default: True 98 | aliases: [] 99 | policies[0..n].audit: 100 | description: 101 | - Whether this policy is audited 102 | required: false 103 | default: True 104 | aliases: [] 105 | policies[0..n].permissions: 106 | description: 107 | - A list of permissions associated to this policy 108 | required: True 109 | default: None 110 | aliases: [] 111 | policies[0..n].permissions[0..n].users: 112 | description: 113 | - A list of users this permission will apply on. 114 | required: false 115 | default: None 116 | aliases: [] 117 | policies[0..n].permissions[0..n].groups: 118 | description: 119 | - A list of groups this permission will apply on. 120 | required: false 121 | default: None 122 | aliases: [] 123 | policies[0..n].permissions[0..n].accesses: 124 | description: 125 | - A list of access right granted by this permission. 126 | required: True 127 | default: None 128 | aliases: [] 129 | policies[0..n].permissions[0..n].delegate_admin: 130 | description: 131 | - When a policy is assigned to a user or a group of users those users become the delegated admin. The delegated admin can update, delete the policies. 132 | required: false 133 | default: False 134 | aliases: [] 135 | 136 | author: 137 | - "Serge ALEXANDRE" 138 | 139 | ''' 140 | 141 | 142 | EXAMPLES = ''' 143 | 144 | - hosts: edge_node1 145 | vars: 146 | stormAdminAccesses: 147 | - 'submitTopology' 148 | - 'fileUpload' 149 | - 'fileDownload' 150 | - 'killTopology' 151 | - 'rebalance' 152 | - 'activate' 153 | - 'deactivate' 154 | - 'getTopologyConf' 155 | - 'getTopology' 156 | - 'getUserTopology' 157 | - 'getTopologyInfo' 158 | - 'uploadNewCredentials' 159 | roles: 160 | - ranger_modules 161 | tasks: 162 | - name: Copy ca_bundle 163 | copy: src=../hdp13_ranger_cert.pem dest=/etc/security/hdp13_ranger_cert.pem owner=root mode=0400 164 | 165 | - name: Test ranger_yarn 166 | ranger_storm_policies: 167 | state: present 168 | admin_url: https://ranger.mycompany.com:6182 169 | admin_username: admin 170 | admin_password: admin 171 | validate_certs: no 172 | policies: 173 | - name: test3 174 | topologies: 175 | - topology1 176 | audit: true 177 | enabled: true 178 | permissions: 179 | - users: 180 | - jim 181 | - john 182 | groups: 183 | - grp1 184 | accesses: 185 | - submitTopology 186 | - killTopology 187 | - activate 188 | - deactivate 189 | - getTopology 190 | - users: 191 | - admin 192 | accesses: "{{ stormAdminAccesses }}" 193 | delegate_admin: true 194 | no_log: True 195 | 196 | 197 | ''' 198 | import warnings 199 | from sets import Set 200 | 201 | HAS_REQUESTS = False 202 | try: 203 | import requests 204 | from requests.auth import HTTPBasicAuth 205 | HAS_REQUESTS = True 206 | except (ImportError, AttributeError): 207 | # AttributeError if __version__ is not present 208 | pass 209 | 210 | HAS_KERBEROS = False 211 | try: 212 | from requests_kerberos import HTTPKerberosAuth 213 | HAS_KERBEROS = True 214 | except ImportError: 215 | pass 216 | 217 | # Global, to allow access from error 218 | module = None 219 | logs = [] 220 | logLevel = 'None' 221 | 222 | def log(level, message): 223 | x = level+':' + message 224 | logs.append(x) 225 | 226 | def debug(message): 227 | if logLevel == 'debug': 228 | log("DEBUG", message) 229 | 230 | def info(message): 231 | if logLevel == "info" or logLevel == "debug": 232 | log("INFO", message) 233 | 234 | class RangerAPI: 235 | 236 | def __init__(self, endpoint, username, password, verify): 237 | self.endpoint = endpoint 238 | self.username = username 239 | self.password = password 240 | self.verify = verify 241 | self.serviceNamesByType = None 242 | if self.username == "KERBEROS": 243 | if not HAS_KERBEROS: 244 | error("'python-requests-kerberos' package is not installed") 245 | else: 246 | self.auth = HTTPKerberosAuth() 247 | else: 248 | self.auth = HTTPBasicAuth(self.username, self.password) 249 | warnings.filterwarnings("ignore", ".*Unverified HTTPS.*") 250 | warnings.filterwarnings("ignore", ".*Certificate has no `subjectAltName`.*") 251 | 252 | def get(self, path): 253 | url = self.endpoint + "/" + path 254 | resp = requests.get(url, auth = self.auth, verify=self.verify) 255 | debug("HTTP GET({}) --> {}".format(url, resp.status_code)) 256 | if resp.status_code == 200: # Warning: Failing auth may trigger a 200 with an HTML login page. 257 | contentType = resp.headers["content-type"] if ("content-type" in resp.headers) else "unknow" 258 | debug("Response content-type:{}".format(contentType)) 259 | if "json" in contentType: 260 | result = resp.json() 261 | return result 262 | elif contentType.startswith("text/html"): 263 | error("HTML content received. May be Ranger login or password is invalid!") 264 | else: 265 | error("Invalid 'content-type' ({}) in response".format(contentType)) 266 | elif resp.status_code == 401 and self.username == "KERBEROS": 267 | error("KERBEROS authentication failed! (Did you perform kinit ?)") 268 | else: 269 | error("Invalid returned http code '{0}' when calling GET on '{1}'".format(resp.status_code, url)) 270 | 271 | def getServiceNameByType(self, stype, candidate=None): 272 | if self.serviceNamesByType == None: 273 | self.serviceNamesByType = {} 274 | services = self.get("service/public/v2/api/service") 275 | for service in services: 276 | if not service["type"] in self.serviceNamesByType: 277 | self.serviceNamesByType[service['type']] = [] 278 | self.serviceNamesByType[service['type']].append(service['name']) 279 | #logger.debug(self.serviceNamesByType) 280 | if stype not in self.serviceNamesByType: 281 | error("Service type '{0}' is not defined in this Ranger instance".format(stype) ) 282 | serviceNames = self.serviceNamesByType[stype] 283 | if candidate != None: 284 | if candidate not in serviceNames: 285 | error("Service {0} is not defined on this Ranger instance".format(candidate)) 286 | return candidate 287 | else: 288 | if len(serviceNames) != 1: 289 | error("There is several choice for '{0}' service: {1}. Please configure one explicitly!".format(stype, serviceNames)) 290 | return serviceNames[0] 291 | 292 | def getPolicy(self, service, policyName): 293 | return self.get("service/public/v2/api/service/{0}/policy?policyName={1}".format(service, policyName)) 294 | 295 | def createPolicy(self, policy): 296 | url = self.endpoint + '/service/public/v2/api/policy' 297 | resp = requests.post(url, auth = self.auth, json=policy, headers={'content-type': 'application/json'}, verify=self.verify) 298 | debug("HTTP POST({}) --> {}".format(url, resp.status_code)) 299 | if resp.status_code != 200: 300 | error("Invalid returned http code '{0}' when calling POST on '{1}': {2}".format(resp.status_code, url, resp.text)) 301 | 302 | def deletePolicy(self, pid): 303 | url = "{0}/service/public/v2/api/policy/{1}".format(self.endpoint, pid) 304 | resp = requests.delete(url, auth = self.auth, verify=self.verify) 305 | debug("HTTP DELETE({}) --> {}".format(url, resp.status_code)) 306 | if resp.status_code < 200 or resp.status_code > 299: 307 | error("Invalid returned http code '{0}' when calling DELETE on '{1}: {2}'".format(resp.status_code, url, resp.text)) 308 | 309 | def updatePolicy(self, policy): 310 | url = "{0}/service/public/v2/api/policy/{1}".format(self.endpoint, policy["id"]) 311 | resp = requests.put(url, auth = self.auth, json=policy, headers={'content-type': 'application/json'}, verify=self.verify) 312 | debug("HTTP PUT({}) --> {}".format(url, resp.status_code)) 313 | if resp.status_code != 200: 314 | error("Invalid returned http code '{0}' when calling PUT on '{1}': {2}".format(resp.status_code, url, resp.text)) 315 | 316 | def close(self): 317 | pass 318 | 319 | # --------------------------------------------------------------------------------- 320 | 321 | 322 | def digdiff(left, right): 323 | result = { 324 | "missingOnLeft": [], 325 | "missingOnRight": [], 326 | "differsByValue": [], 327 | "differsByType": [] 328 | } 329 | diffValue(left, right, "", result) 330 | return result 331 | 332 | 333 | def diffValue(left, right, path, result): 334 | #print "diffValue(left:{0} right:{1})".format(left, right) 335 | if right == None: 336 | if left != None: 337 | result["differsByValue"].append(path) 338 | else: 339 | pass 340 | else: 341 | if left == None: 342 | result["differsByValue"].append(path) 343 | elif isinstance(left, dict): 344 | if isinstance(right, dict): 345 | diffDict(left, right, path, result) 346 | else: 347 | result["differsByType"].append(path) 348 | elif isinstance(left, list): 349 | if isinstance(right, list): 350 | diffList(left, right, path, result) 351 | else: 352 | result["differsByType"].append(path) 353 | else: 354 | # left is a scalar 355 | left = normalizeType(left) 356 | right = normalizeType(right) 357 | if type(left) != type(right): 358 | #print "********************* type(left):{0} type(right):{1}".format(type(left), type(right)) 359 | result["differsByType"].append(path) 360 | else: 361 | if left != right: 362 | result["differsByValue"].append(path) 363 | else: 364 | pass 365 | 366 | def normalizeType(value): 367 | """ 368 | Try to normalize o type, to be able to compare them 369 | """ 370 | if isinstance(value, unicode): 371 | return str(value) 372 | else: 373 | return value 374 | 375 | 376 | 377 | def diffDict(left, right, path, result): 378 | #print "diffDict(left:{0} right:{1})".format(left, right) 379 | for kl in left: 380 | path2 = path + "." + kl 381 | if kl in right: 382 | diffValue(left[kl], right[kl], path2, result) 383 | else: 384 | result['missingOnRight'].append(path2) 385 | for kr in right: 386 | path2 = path + "." + kr 387 | if kr in left: 388 | pass 389 | else: 390 | result['missingOnLeft'].append(path2) 391 | 392 | 393 | def diffList(left, right, path, result): 394 | for x in range(len(left)): 395 | path2 = path + '[' + str(x) + ']' 396 | if x >= len(right): 397 | result['missingOnRight'].append(path2) 398 | else: 399 | diffValue(left[x], right[x], path2, result) 400 | for x in range(len(left), len(right)): 401 | path2 = path + '[' + str(x) + ']' 402 | result['missingOnLeft'].append(path2) 403 | 404 | 405 | 406 | # --------------------------------------------------------------------------------- 407 | 408 | 409 | ALLOWED_MISSING_ON_RIGHT = Set([".version", ".policyType", ".guid"]) 410 | 411 | def isPolicyIdentical(old, new): 412 | result = digdiff(old, new) 413 | #misc.ppprint(old) 414 | #misc.ppprint(new) 415 | debug("missingOnLeft:{}".format(result['missingOnLeft'])) 416 | debug("missingOnRight:{}".format(result['missingOnRight'])) 417 | debug("differsByType:{}".format(result['differsByType'])) 418 | debug("differsByValue:{}".format(result['differsByValue'])) 419 | if len(result['missingOnLeft']) > 0 or len(result['differsByType']) > 0 or len(result['differsByValue']) > 0: 420 | return False 421 | else: 422 | for missing in result["missingOnRight"]: 423 | if not missing in ALLOWED_MISSING_ON_RIGHT: 424 | return False 425 | return True 426 | 427 | 428 | 429 | # --------------------------------------------------------- Grooming helper function 430 | 431 | def checkListOfStrNotEmpty(base, attr, prefix): 432 | if attr not in base: 433 | error("{0}: Missing attribute '{1}'".format(prefix, attr)) 434 | if not isinstance(base[attr], list): 435 | error("{0}: Attribute '{1}' if of wrong type. Must by a list".format(prefix, attr)) 436 | if len(base[attr]) == 0: 437 | error("{0}: Attribute '{1}': Must have at least one items".format(prefix, attr)) 438 | for v in base[attr]: 439 | if not isinstance(v, basestring) or len(v) == 0: 440 | error("{0}: All items of list '{1}' must be non null string".format(prefix, attr)) 441 | 442 | 443 | def checkListOfStr(base, attr, prefix): 444 | if attr not in base: 445 | base[attr] = [] 446 | else: 447 | if not isinstance(base[attr], list): 448 | error("{0}: Attribute '{1}' if of wrong type. Must by a list".format(prefix, attr)) 449 | for v in base[attr]: 450 | if not isinstance(v, basestring) or len(v) == 0: 451 | error("{0}: All items of list '{1}' must be non null string".format(prefix, attr)) 452 | 453 | def checkTypeWithDefault(base, attr, typ, default, prefix): 454 | if attr not in base: 455 | base[attr] = default 456 | else: 457 | if not isinstance(base[attr], typ): 458 | error("{0}: Attribute '{1}' if of wrong type. Must by a {2}".format(prefix, attr, typ)) 459 | 460 | def checkEnumWithDefault(base, attr, candidates, default, prefix): 461 | if attr not in base: 462 | base[attr] = default 463 | else: 464 | if not isinstance(base[attr], basestring): 465 | error("{0}: Attribute '{1}' if of wrong type. Must by a string".format(prefix, attr)) 466 | else: 467 | if not base[attr] in candidates: 468 | error("{0}: Attribute '{1}' must be one of the following: {2}".format(prefix, attr, candidates)) 469 | 470 | def checkValidAttr(base, validAttrSet, prefix): 471 | for attr in base: 472 | if attr not in validAttrSet: 473 | error("{0}: Invalid attribute '{1}'. Must be one of {2}".format(prefix, attr, validAttrSet)) 474 | 475 | 476 | 477 | def groom(policy): 478 | """ 479 | Check and Normalize target policy expression 480 | """ 481 | if 'name' not in policy: 482 | error("There is at least one Storm policy without name!") 483 | if not isinstance(policy["name"], basestring): 484 | error("Storm policy: Attribute 'name' if of wrong type. Must by a string") 485 | prefix = "Storm policy '{0}': ".format(policy['name']) 486 | 487 | 488 | checkValidAttr(policy, ['name', 'topologies', 'state', 'audit', 'enabled', 'permissions'], prefix) 489 | 490 | checkListOfStrNotEmpty(policy, "topologies", prefix) 491 | 492 | checkTypeWithDefault(policy, "audit", bool, True, prefix) 493 | checkTypeWithDefault(policy, "enabled", bool, True, prefix) 494 | 495 | checkTypeWithDefault(policy, "permissions", list, [], prefix) 496 | 497 | for permission in policy['permissions']: 498 | checkValidAttr(permission, ['users', 'groups', 'accesses', 'delegate_admin'], prefix) 499 | checkListOfStr(permission, 'users', prefix) 500 | checkListOfStr(permission, 'groups', prefix) 501 | checkListOfStr(permission, 'accesses', prefix) 502 | checkTypeWithDefault(permission, 'delegate_admin', bool, False, prefix) 503 | 504 | 505 | def newPolicy(tgtPolicy, service): 506 | policy = { 507 | 'allowExceptions': [], 508 | 'dataMaskPolicyItems': [], 509 | 'denyExceptions': [], 510 | 'denyPolicyItems': [], 511 | 'isAuditEnabled': tgtPolicy['audit'], 512 | 'isEnabled': tgtPolicy['enabled'], 513 | 'name': tgtPolicy['name'], 514 | 'policyItems': [], 515 | 'resources': { 516 | "topology": { 517 | "isExcludes": False, 518 | "isRecursive": False, 519 | "values": tgtPolicy["topologies"] 520 | } 521 | }, 522 | 'rowFilterPolicyItems': [], 523 | 'service': service 524 | } 525 | for p in tgtPolicy['permissions']: 526 | tp = {} 527 | tp['accesses'] = [] 528 | tp['conditions'] = [] 529 | tp['delegateAdmin'] = p['delegate_admin'] 530 | tp['groups'] = p['groups'] 531 | tp['users'] = p['users'] 532 | for a in p['accesses']: 533 | tp['accesses'].append({ "isAllowed": True, "type": a }) 534 | policy['policyItems'].append(tp) 535 | return policy 536 | 537 | 538 | rangerAPI = None 539 | 540 | def cleanup(): 541 | if rangerAPI != None: 542 | rangerAPI.close() 543 | 544 | 545 | def error(message): 546 | cleanup() 547 | module.fail_json(msg = message, logs=logs) 548 | 549 | class Parameters: 550 | pass 551 | 552 | 553 | def checkParameters(p): 554 | pass 555 | 556 | def main(): 557 | 558 | global module 559 | module = AnsibleModule( 560 | argument_spec = dict( 561 | state = dict(required=False, choices=['present','absent'], default="present"), 562 | admin_url = dict(required=True, type='str'), 563 | admin_username = dict(required=True, type='str'), 564 | admin_password = dict(required=True, type='str'), 565 | validate_certs = dict(required=False, type='bool', default=True), 566 | ca_bundle_file = dict(required=False, type='str'), 567 | service_name = dict(required=False, type='str'), 568 | policies = dict(required=True, type='list'), 569 | log_level = dict(required=False, default="None") 570 | ), 571 | supports_check_mode=False 572 | ) 573 | 574 | if not HAS_REQUESTS: 575 | module.fail_json(msg="python-requests package is not installed") 576 | 577 | p = Parameters() 578 | p.state = module.params['state'] 579 | p.adminUrl = module.params['admin_url'] 580 | p.adminUsername = module.params['admin_username'] 581 | p.adminPassword = module.params['admin_password'] 582 | p.validateCerts = module.params['validate_certs'] 583 | p.ca_bundleFile = module.params['ca_bundle_file'] 584 | p.serviceName = module.params['service_name'] 585 | p.policies = module.params['policies'] 586 | p.logLevel = module.params['log_level'] 587 | p.changed = False 588 | 589 | global logLevel 590 | logLevel = p.logLevel 591 | 592 | checkParameters(p) 593 | 594 | if p.ca_bundleFile != None: 595 | verify = p.ca_bundleFile 596 | else: 597 | verify = p.validateCerts 598 | 599 | global rangerAPI 600 | rangerAPI = RangerAPI(p.adminUrl, p.adminUsername , p.adminPassword , verify) 601 | 602 | result = {} 603 | stormServiceName = rangerAPI.getServiceNameByType("storm", p.serviceName) 604 | # Perform check before effective operation 605 | for tgtPolicy in p.policies: 606 | groom(tgtPolicy) 607 | for tgtPolicy in p.policies: 608 | policyName = tgtPolicy['name'] 609 | result[policyName] = {} 610 | oldPolicies = rangerAPI.getPolicy(stormServiceName, policyName) 611 | debug("oldPolicies: " + repr(oldPolicies)) 612 | #misc.ppprint(oldPolicies) 613 | if len(oldPolicies) > 1: 614 | error("More than one policy with name '{0}' !".format(policyName)) 615 | if p.state == 'present': 616 | if len(oldPolicies) == 0: 617 | policy = newPolicy(tgtPolicy, stormServiceName) 618 | #misc.ppprint(p) 619 | rangerAPI.createPolicy(policy) 620 | result[policyName]['action'] = "created" 621 | p.changed = True 622 | else: 623 | oldPolicy = oldPolicies[0] 624 | pid = oldPolicy["id"] 625 | policy = newPolicy(tgtPolicy, stormServiceName) 626 | policy["id"] = pid 627 | result[policyName]['id'] = pid 628 | if isPolicyIdentical(oldPolicy, policy): 629 | result[policyName]['action'] = "none" 630 | else: 631 | result[policyName]['action'] = "updated" 632 | rangerAPI.updatePolicy(policy) 633 | p.changed = True 634 | #misc.ppprint(oldPolicy) 635 | elif p.state == 'absent': 636 | if len(oldPolicies) == 1: 637 | rangerAPI.deletePolicy(oldPolicies[0]["id"]) 638 | result[policyName]['action'] = "deleted" 639 | p.changed = True 640 | else: 641 | result[policyName]['action'] = "none" 642 | 643 | cleanup() 644 | module.exit_json( 645 | changed = p.changed, 646 | policies = result, 647 | logs = logs 648 | ) 649 | 650 | 651 | 652 | from ansible.module_utils.basic import * #@UnusedWildImport 653 | 654 | if __name__ == '__main__': 655 | main() 656 | 657 | -------------------------------------------------------------------------------- /library/ranger_yarn_policies.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | # (c) 2017, BROADSoftware 5 | # 6 | # This software is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This software is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this software. If not, see . 18 | 19 | 20 | DOCUMENTATION = ''' 21 | --- 22 | module: ranger_yarn_policies 23 | short_description: Manage definition of yarn Policy in Apache Ranger 24 | description: 25 | - This module will allow you to manage Yarn policy in Apache Ranger. 26 | - Please refer to Apache Ranger documentation for authorization policy concept and usage. 27 | options: 28 | admin_url: 29 | description: 30 | - The Ranger base URL to access Ranger API. Same host:port as the Ranger Admin GUI. Typically http://myranger.server.com:6080 or https://myranger.server.com:6182 31 | required: true 32 | default: None 33 | aliases: [] 34 | admin_username: 35 | description: 36 | - The user name to log on the Ranger Admin. Must have enough rights to manage policies. 37 | - Also accepts the special value C(KERBEROS). In such case, a valid Kerberos ticket must exist for the ansible_user account on the target system. (A C(kinit) must be issued under this account). 38 | Then HDFS operation will be performed on behalf of the user defined by the Kerberos ticket. 39 | required: true 40 | default: None 41 | aliases: [] 42 | admin_password: 43 | description: 44 | - The password associated with the admin_username 45 | required: true 46 | default: None 47 | aliases: [] 48 | validate_certs: 49 | description: 50 | - Useful if Ranger Admin connection is using SSL. If no, SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates. 51 | required: false 52 | default: True 53 | aliases: [] 54 | ca_bundle_file: 55 | description: 56 | - Useful if Ranger Admin connection is using SSL. Allow to specify a CA_BUNDLE file, a file that contains root and intermediate certificates to validate the Ranger Admin certificate. 57 | - In its simplest case, it could be a file containing the server certificate in .pem format. 58 | - This file will be looked up on the remote system, on which this module will be executed. 59 | required: false 60 | default: None 61 | aliases: [] 62 | service_name: 63 | description: 64 | - In most cases, you should not need to set this parameter. It define the Ranger Admin Yarn service, typically _yarn. 65 | - It must be set if there are several such services defined in your Ranger Admin configuration, to select the one you intend to use. 66 | required: false 67 | default: None 68 | aliases: [] 69 | state: 70 | description: 71 | - Whether to install (present) or remove (absent) these policies 72 | required: false 73 | default: present 74 | choices: [ present, absent ] 75 | policies: 76 | description: 77 | - The list of policies you want to be defined by this operation. 78 | required: true 79 | default: None 80 | aliases: [] 81 | policies[0..n].name: 82 | description: 83 | - The name of the policy. Must be unique across the system. 84 | required: true 85 | default: None 86 | aliases: [] 87 | policies[0..n].queues: 88 | description: 89 | - A list of Yarn queues this policy will apply on. Accept wildcard characters '*' and '?' 90 | required: true 91 | default: None 92 | aliases: [] 93 | policies[0..n].enabled: 94 | description: 95 | - Whether this policy is enabled. 96 | required: false 97 | default: True 98 | aliases: [] 99 | policies[0..n].audit: 100 | description: 101 | - Whether this policy is audited 102 | required: false 103 | default: True 104 | aliases: [] 105 | policies[0..n].recursive: 106 | description: 107 | - Whether this policy is recursive 108 | required: false 109 | default: True 110 | aliases: [] 111 | policies[0..n].permissions: 112 | description: 113 | - A list of permissions associated to this policy 114 | required: True 115 | default: None 116 | aliases: [] 117 | policies[0..n].permissions[0..n].users: 118 | description: 119 | - A list of users this permission will apply on. 120 | required: false 121 | default: None 122 | aliases: [] 123 | policies[0..n].permissions[0..n].groups: 124 | description: 125 | - A list of groups this permission will apply on. 126 | required: false 127 | default: None 128 | aliases: [] 129 | policies[0..n].permissions[0..n].accesses: 130 | description: 131 | - A list of access right granted by this permission. 132 | required: True 133 | default: None 134 | aliases: [] 135 | policies[0..n].permissions[0..n].delegate_admin: 136 | description: 137 | - When a policy is assigned to a user or a group of users those users become the delegated admin. The delegated admin can update, delete the policies. 138 | required: false 139 | default: False 140 | aliases: [] 141 | 142 | author: 143 | - "Serge ALEXANDRE" 144 | 145 | ''' 146 | 147 | 148 | EXAMPLES = ''' 149 | 150 | # This playbook snippet will: 151 | # - Allow all members of group 'users' to submit jobs on queue 'sales'. 152 | # - Grant admin rights fir user 'admin' on the same queue. 153 | # 154 | # Note also how we handle Certificate bundle, by first copying it on the remote site. 155 | # 156 | - hosts: edge_node1 157 | roles: 158 | - ranger_modules 159 | tasks: 160 | - name: Copy ca_bundle 161 | copy: src=../rangersrv_cert.pem dest=/etc/security/rangersrc_cert.pem owner=root mode=0400 162 | - name: Apply ranger Yarn policy 163 | ranger_yarn_policies: 164 | state: present 165 | admin_url: https://ranger.mycompany.com:6182 166 | admin_username: admin 167 | admin_password: admin 168 | validate_certs: yes 169 | ca_bundle_file: /etc/security/rangersrv_cert.pem 170 | policies: 171 | - name: "testyarn2" 172 | queues: 173 | - sales 174 | permissions: 175 | - groups: 176 | - users 177 | accesses: 178 | - submit-app 179 | - users: 180 | - admin 181 | accesses: 182 | - submit-app 183 | - admin-queue 184 | delegate_admin: true 185 | 186 | 187 | ''' 188 | import warnings 189 | from sets import Set 190 | 191 | HAS_REQUESTS = False 192 | try: 193 | import requests 194 | from requests.auth import HTTPBasicAuth 195 | HAS_REQUESTS = True 196 | except (ImportError, AttributeError): 197 | # AttributeError if __version__ is not present 198 | pass 199 | 200 | HAS_KERBEROS = False 201 | try: 202 | from requests_kerberos import HTTPKerberosAuth 203 | HAS_KERBEROS = True 204 | except ImportError: 205 | pass 206 | 207 | # Global, to allow access from error 208 | module = None 209 | logs = [] 210 | logLevel = 'None' 211 | 212 | def log(level, message): 213 | x = level+':' + message 214 | logs.append(x) 215 | 216 | def debug(message): 217 | if logLevel == 'debug': 218 | log("DEBUG", message) 219 | 220 | def info(message): 221 | if logLevel == "info" or logLevel == "debug": 222 | log("INFO", message) 223 | 224 | class RangerAPI: 225 | 226 | def __init__(self, endpoint, username, password, verify): 227 | self.endpoint = endpoint 228 | self.username = username 229 | self.password = password 230 | self.verify = verify 231 | self.serviceNamesByType = None 232 | if self.username == "KERBEROS": 233 | if not HAS_KERBEROS: 234 | error("'python-requests-kerberos' package is not installed") 235 | else: 236 | self.auth = HTTPKerberosAuth() 237 | else: 238 | self.auth = HTTPBasicAuth(self.username, self.password) 239 | warnings.filterwarnings("ignore", ".*Unverified HTTPS.*") 240 | warnings.filterwarnings("ignore", ".*Certificate has no `subjectAltName`.*") 241 | 242 | def get(self, path): 243 | url = self.endpoint + "/" + path 244 | resp = requests.get(url, auth = self.auth, verify=self.verify) 245 | debug("HTTP GET({}) --> {}".format(url, resp.status_code)) 246 | if resp.status_code == 200: # Warning: Failing auth may trigger a 200 with an HTML login page. 247 | contentType = resp.headers["content-type"] if ("content-type" in resp.headers) else "unknow" 248 | debug("Response content-type:{}".format(contentType)) 249 | if "json" in contentType: 250 | result = resp.json() 251 | return result 252 | elif contentType.startswith("text/html"): 253 | error("HTML content received. May be Ranger login or password is invalid!") 254 | else: 255 | error("Invalid 'content-type' ({}) in response".format(contentType)) 256 | elif resp.status_code == 401 and self.username == "KERBEROS": 257 | error("KERBEROS authentication failed! (Did you perform kinit ?)") 258 | else: 259 | error("Invalid returned http code '{0}' when calling GET on '{1}'".format(resp.status_code, url)) 260 | 261 | def getServiceNameByType(self, stype, candidate=None): 262 | if self.serviceNamesByType == None: 263 | self.serviceNamesByType = {} 264 | services = self.get("service/public/v2/api/service") 265 | for service in services: 266 | if not service["type"] in self.serviceNamesByType: 267 | self.serviceNamesByType[service['type']] = [] 268 | self.serviceNamesByType[service['type']].append(service['name']) 269 | #logger.debug(self.serviceNamesByType) 270 | if stype not in self.serviceNamesByType: 271 | error("Service type '{0}' is not defined in this Ranger instance".format(stype) ) 272 | serviceNames = self.serviceNamesByType[stype] 273 | if candidate != None: 274 | if candidate not in serviceNames: 275 | error("Service {0} is not defined on this Ranger instance".format(candidate)) 276 | return candidate 277 | else: 278 | if len(serviceNames) != 1: 279 | error("There is several choice for '{0}' service: {1}. Please configure one explicitly!".format(stype, serviceNames)) 280 | return serviceNames[0] 281 | 282 | def getPolicy(self, service, policyName): 283 | return self.get("service/public/v2/api/service/{0}/policy?policyName={1}".format(service, policyName)) 284 | 285 | def createPolicy(self, policy): 286 | url = self.endpoint + '/service/public/v2/api/policy' 287 | resp = requests.post(url, auth = self.auth, json=policy, headers={'content-type': 'application/json'}, verify=self.verify) 288 | debug("HTTP POST({}) --> {}".format(url, resp.status_code)) 289 | if resp.status_code != 200: 290 | error("Invalid returned http code '{0}' when calling POST on '{1}': {2}".format(resp.status_code, url, resp.text)) 291 | 292 | def deletePolicy(self, pid): 293 | url = "{0}/service/public/v2/api/policy/{1}".format(self.endpoint, pid) 294 | resp = requests.delete(url, auth = self.auth, verify=self.verify) 295 | debug("HTTP DELETE({}) --> {}".format(url, resp.status_code)) 296 | if resp.status_code < 200 or resp.status_code > 299: 297 | error("Invalid returned http code '{0}' when calling DELETE on '{1}: {2}'".format(resp.status_code, url, resp.text)) 298 | 299 | def updatePolicy(self, policy): 300 | url = "{0}/service/public/v2/api/policy/{1}".format(self.endpoint, policy["id"]) 301 | resp = requests.put(url, auth = self.auth, json=policy, headers={'content-type': 'application/json'}, verify=self.verify) 302 | debug("HTTP PUT({}) --> {}".format(url, resp.status_code)) 303 | if resp.status_code != 200: 304 | error("Invalid returned http code '{0}' when calling PUT on '{1}': {2}".format(resp.status_code, url, resp.text)) 305 | 306 | def close(self): 307 | pass 308 | 309 | # --------------------------------------------------------------------------------- 310 | 311 | 312 | def digdiff(left, right): 313 | result = { 314 | "missingOnLeft": [], 315 | "missingOnRight": [], 316 | "differsByValue": [], 317 | "differsByType": [] 318 | } 319 | diffValue(left, right, "", result) 320 | return result 321 | 322 | 323 | def diffValue(left, right, path, result): 324 | #print "diffValue(left:{0} right:{1})".format(left, right) 325 | if right == None: 326 | if left != None: 327 | result["differsByValue"].append(path) 328 | else: 329 | pass 330 | else: 331 | if left == None: 332 | result["differsByValue"].append(path) 333 | elif isinstance(left, dict): 334 | if isinstance(right, dict): 335 | diffDict(left, right, path, result) 336 | else: 337 | result["differsByType"].append(path) 338 | elif isinstance(left, list): 339 | if isinstance(right, list): 340 | diffList(left, right, path, result) 341 | else: 342 | result["differsByType"].append(path) 343 | else: 344 | # left is a scalar 345 | left = normalizeType(left) 346 | right = normalizeType(right) 347 | if type(left) != type(right): 348 | #print "********************* type(left):{0} type(right):{1}".format(type(left), type(right)) 349 | result["differsByType"].append(path) 350 | else: 351 | if left != right: 352 | result["differsByValue"].append(path) 353 | else: 354 | pass 355 | 356 | def normalizeType(value): 357 | """ 358 | Try to normalize o type, to be able to compare them 359 | """ 360 | if isinstance(value, unicode): 361 | return str(value) 362 | else: 363 | return value 364 | 365 | 366 | 367 | def diffDict(left, right, path, result): 368 | #print "diffDict(left:{0} right:{1})".format(left, right) 369 | for kl in left: 370 | path2 = path + "." + kl 371 | if kl in right: 372 | diffValue(left[kl], right[kl], path2, result) 373 | else: 374 | result['missingOnRight'].append(path2) 375 | for kr in right: 376 | path2 = path + "." + kr 377 | if kr in left: 378 | pass 379 | else: 380 | result['missingOnLeft'].append(path2) 381 | 382 | 383 | def diffList(left, right, path, result): 384 | for x in range(len(left)): 385 | path2 = path + '[' + str(x) + ']' 386 | if x >= len(right): 387 | result['missingOnRight'].append(path2) 388 | else: 389 | diffValue(left[x], right[x], path2, result) 390 | for x in range(len(left), len(right)): 391 | path2 = path + '[' + str(x) + ']' 392 | result['missingOnLeft'].append(path2) 393 | 394 | 395 | 396 | # --------------------------------------------------------------------------------- 397 | 398 | 399 | ALLOWED_MISSING_ON_RIGHT = Set([".version", ".policyType", ".guid"]) 400 | 401 | def isPolicyIdentical(old, new): 402 | result = digdiff(old, new) 403 | #misc.ppprint(old) 404 | #misc.ppprint(new) 405 | debug("missingOnLeft:{}".format(result['missingOnLeft'])) 406 | debug("missingOnRight:{}".format(result['missingOnRight'])) 407 | debug("differsByType:{}".format(result['differsByType'])) 408 | debug("differsByValue:{}".format(result['differsByValue'])) 409 | if len(result['missingOnLeft']) > 0 or len(result['differsByType']) > 0 or len(result['differsByValue']) > 0: 410 | return False 411 | else: 412 | for missing in result["missingOnRight"]: 413 | if not missing in ALLOWED_MISSING_ON_RIGHT: 414 | return False 415 | return True 416 | 417 | 418 | 419 | # --------------------------------------------------------- Grooming helper function 420 | 421 | def checkListOfStrNotEmpty(base, attr, prefix): 422 | if attr not in base: 423 | error("{0}: Missing attribute '{1}'".format(prefix, attr)) 424 | if not isinstance(base[attr], list): 425 | error("{0}: Attribute '{1}' if of wrong type. Must by a list".format(prefix, attr)) 426 | if len(base[attr]) == 0: 427 | error("{0}: Attribute '{1}': Must have at least one items".format(prefix, attr)) 428 | for v in base[attr]: 429 | if not isinstance(v, basestring) or len(v) == 0: 430 | error("{0}: All items of list '{1}' must be non null string".format(prefix, attr)) 431 | 432 | 433 | def checkListOfStr(base, attr, prefix): 434 | if attr not in base: 435 | base[attr] = [] 436 | else: 437 | if not isinstance(base[attr], list): 438 | error("{0}: Attribute '{1}' if of wrong type. Must by a list".format(prefix, attr)) 439 | for v in base[attr]: 440 | if not isinstance(v, basestring) or len(v) == 0: 441 | error("{0}: All items of list '{1}' must be non null string".format(prefix, attr)) 442 | 443 | def checkTypeWithDefault(base, attr, typ, default, prefix): 444 | if attr not in base: 445 | base[attr] = default 446 | else: 447 | if not isinstance(base[attr], typ): 448 | error("{0}: Attribute '{1}' if of wrong type. Must by a {2}".format(prefix, attr, typ)) 449 | 450 | def checkEnumWithDefault(base, attr, candidates, default, prefix): 451 | if attr not in base: 452 | base[attr] = default 453 | else: 454 | if not isinstance(base[attr], basestring): 455 | error("{0}: Attribute '{1}' if of wrong type. Must by a string".format(prefix, attr)) 456 | else: 457 | if not base[attr] in candidates: 458 | error("{0}: Attribute '{1}' must be one of the following: {2}".format(prefix, attr, candidates)) 459 | 460 | def checkValidAttr(base, validAttrSet, prefix): 461 | for attr in base: 462 | if attr not in validAttrSet: 463 | error("{0}: Invalid attribute '{1}'. Must be one of {2}".format(prefix, attr, validAttrSet)) 464 | 465 | 466 | def groom(policy): 467 | """ 468 | Check and Normalize target policy expression 469 | """ 470 | if 'name' not in policy: 471 | error("There is at least one Yarn policy without name!") 472 | if not isinstance(policy["name"], basestring): 473 | error("Yarn policy: Attribute 'name' if of wrong type. Must by a string") 474 | prefix = "Yarn policy '{0}': ".format(policy['name']) 475 | 476 | checkValidAttr(policy, ['name', 'queues', 'audit', 'recursive', 'enabled', 'permissions'], prefix) 477 | 478 | checkListOfStrNotEmpty(policy, "queues", prefix) 479 | 480 | checkTypeWithDefault(policy, "recursive", bool, True, prefix) 481 | checkTypeWithDefault(policy, "audit", bool, True, prefix) 482 | checkTypeWithDefault(policy, "enabled", bool, True, prefix) 483 | 484 | checkTypeWithDefault(policy, "permissions", list, [], prefix) 485 | 486 | for permission in policy['permissions']: 487 | checkValidAttr(permission, ['users', 'groups', 'accesses', 'delegate_admin'], prefix) 488 | checkListOfStr(permission, 'users', prefix) 489 | checkListOfStr(permission, 'groups', prefix) 490 | checkListOfStr(permission, 'accesses', prefix) 491 | checkTypeWithDefault(permission, 'delegate_admin', bool, False, prefix) 492 | 493 | 494 | def newPolicy(tgtPolicy, service): 495 | policy = { 496 | 'allowExceptions': [], 497 | 'dataMaskPolicyItems': [], 498 | 'denyExceptions': [], 499 | 'denyPolicyItems': [], 500 | 'isAuditEnabled': tgtPolicy['audit'], 501 | 'isEnabled': tgtPolicy['enabled'], 502 | 'name': tgtPolicy['name'], 503 | 'policyItems': [], 504 | 'resources': { 505 | "queue": { 506 | "isExcludes": False, 507 | "isRecursive": tgtPolicy["recursive"], 508 | "values": tgtPolicy["queues"] 509 | } 510 | }, 511 | 'rowFilterPolicyItems': [], 512 | 'service': service 513 | } 514 | for p in tgtPolicy['permissions']: 515 | tp = {} 516 | tp['accesses'] = [] 517 | tp['conditions'] = [] 518 | tp['delegateAdmin'] = p['delegate_admin'] 519 | tp['groups'] = p['groups'] 520 | tp['users'] = p['users'] 521 | for a in p['accesses']: 522 | tp['accesses'].append({ "isAllowed": True, "type": a.lower() }) 523 | policy['policyItems'].append(tp) 524 | return policy 525 | 526 | rangerAPI = None 527 | 528 | def cleanup(): 529 | if rangerAPI != None: 530 | rangerAPI.close() 531 | 532 | 533 | def error(message): 534 | cleanup() 535 | module.fail_json(msg = message, logs=logs) 536 | 537 | class Parameters: 538 | pass 539 | 540 | 541 | def checkParameters(p): 542 | pass 543 | 544 | def main(): 545 | 546 | global module 547 | module = AnsibleModule( 548 | argument_spec = dict( 549 | state = dict(required=False, choices=['present','absent'], default="present"), 550 | admin_url = dict(required=True, type='str'), 551 | admin_username = dict(required=True, type='str'), 552 | admin_password = dict(required=True, type='str'), 553 | validate_certs = dict(required=False, type='bool', default=True), 554 | ca_bundle_file = dict(required=False, type='str'), 555 | service_name = dict(required=False, type='str'), 556 | policies = dict(required=True, type='list'), 557 | log_level = dict(required=False, default="None") 558 | ), 559 | supports_check_mode=False 560 | ) 561 | 562 | if not HAS_REQUESTS: 563 | module.fail_json(msg="python-requests package is not installed") 564 | 565 | p = Parameters() 566 | p.state = module.params['state'] 567 | p.adminUrl = module.params['admin_url'] 568 | p.adminUsername = module.params['admin_username'] 569 | p.adminPassword = module.params['admin_password'] 570 | p.validateCerts = module.params['validate_certs'] 571 | p.ca_bundleFile = module.params['ca_bundle_file'] 572 | p.serviceName = module.params['service_name'] 573 | p.policies = module.params['policies'] 574 | p.logLevel = module.params['log_level'] 575 | p.changed = False 576 | 577 | global logLevel 578 | logLevel = p.logLevel 579 | 580 | checkParameters(p) 581 | 582 | if p.ca_bundleFile != None: 583 | verify = p.ca_bundleFile 584 | else: 585 | verify = p.validateCerts 586 | 587 | global rangerAPI 588 | rangerAPI = RangerAPI(p.adminUrl, p.adminUsername , p.adminPassword , verify) 589 | 590 | result = {} 591 | yarnServiceName = rangerAPI.getServiceNameByType("yarn", p.serviceName) 592 | # Perform check before effective operation 593 | for tgtPolicy in p.policies: 594 | groom(tgtPolicy) 595 | for tgtPolicy in p.policies: 596 | policyName = tgtPolicy['name'] 597 | result[policyName] = {} 598 | oldPolicies = rangerAPI.getPolicy(yarnServiceName, policyName) 599 | debug("oldPolicies: " + repr(oldPolicies)) 600 | #misc.ppprint(oldPolicies) 601 | if len(oldPolicies) > 1: 602 | error("More than one policy with name '{0}' !".format(policyName)) 603 | if p.state == 'present': 604 | if len(oldPolicies) == 0: 605 | policy = newPolicy(tgtPolicy, yarnServiceName) 606 | #misc.ppprint(p) 607 | rangerAPI.createPolicy(policy) 608 | result[policyName]['action'] = "created" 609 | p.changed = True 610 | else: 611 | oldPolicy = oldPolicies[0] 612 | pid = oldPolicy["id"] 613 | policy = newPolicy(tgtPolicy, yarnServiceName) 614 | policy["id"] = pid 615 | result[policyName]['id'] = pid 616 | if isPolicyIdentical(oldPolicy, policy): 617 | result[policyName]['action'] = "none" 618 | else: 619 | result[policyName]['action'] = "updated" 620 | rangerAPI.updatePolicy(policy) 621 | p.changed = True 622 | #misc.ppprint(oldPolicy) 623 | elif p.state == 'absent': 624 | if len(oldPolicies) == 1: 625 | rangerAPI.deletePolicy(oldPolicies[0]["id"]) 626 | result[policyName]['action'] = "deleted" 627 | p.changed = True 628 | else: 629 | result[policyName]['action'] = "none" 630 | 631 | cleanup() 632 | module.exit_json( 633 | changed = p.changed, 634 | policies = result, 635 | logs = logs 636 | ) 637 | 638 | 639 | 640 | from ansible.module_utils.basic import * #@UnusedWildImport 641 | 642 | if __name__ == '__main__': 643 | main() 644 | 645 | -------------------------------------------------------------------------------- /meta/main.yml: -------------------------------------------------------------------------------- 1 | galaxy_info: 2 | author: Serge ALEXANDRE 3 | description: Apache Ranger policy management modules 4 | company: BROADSoftware 5 | license: GPLv3 6 | min_ansible_version: 1.9 7 | 8 | platforms: 9 | - name: EL 10 | versions: 11 | - 7 12 | 13 | galaxy_tags: [ "hdfs", "hadoop", "bigdata", "ranger", "hortonworks", "yarn", "kafka", "storm", "hbase", "hive" ] 14 | dependencies: [] 15 | -------------------------------------------------------------------------------- /tasks/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | # (c) 2017, BROADSoftware 4 | # 5 | # This software is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This software is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this software. If not, see . 17 | 18 | # Required by hdfs_file, hdfs_cmd and hdfs_info 19 | 20 | - name: Install python-requests for ranger_xxxxx_policies ansibles modules (RedHat) 21 | yum: name=python-requests,python-requests-kerberos state=present 22 | when: ansible_os_family == 'RedHat' 23 | 24 | - name: Install python-requests for ranger_xxxxx_policies ansibles modules (Debian) 25 | apt: name=python-requests,python-requests-kerberos state=present 26 | when: ansible_os_family == 'Debian' 27 | --------------------------------------------------------------------------------