├── .gitignore ├── .idea ├── ansible-dyninv-mysql.iml ├── dataSources.local.xml ├── dataSources.xml ├── dataSources │ ├── 32e888d2-fd27-442f-8d4e-bf9fb9d0648e.xml │ └── 32e888d2-fd27-442f-8d4e-bf9fb9d0648e │ │ ├── _metadata_ │ │ ├── metadata │ │ ├── metadata.keystream │ │ ├── metadata.keystream.len │ │ ├── metadata.len │ │ ├── metadata.values.at │ │ ├── metadata_i │ │ └── metadata_i.len │ │ ├── _src_ │ │ └── schema │ │ │ └── ansible_inventory.zip │ │ └── storage.xml ├── dictionaries │ └── seven.xml ├── encodings.xml ├── inspectionProfiles │ └── Project_Default.xml ├── misc.xml ├── modules.xml ├── vcs.xml └── workspace.xml ├── LICENSE ├── README ├── __init__.py ├── inventory.py ├── inventoryctl.py ├── mysql.ini.dist ├── setup.py └── tables.sql /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/* 2 | dist 3 | /**/mysql.ini 4 | __pycache__ 5 | *.egg-info/* 6 | -------------------------------------------------------------------------------- /.idea/ansible-dyninv-mysql.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 11 | -------------------------------------------------------------------------------- /.idea/dataSources.local.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | #@ 7 | ` 8 | 9 | 10 | master_key 11 | root 12 | *:ansible_inventory 13 | 14 | 15 | -------------------------------------------------------------------------------- /.idea/dataSources.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | mysql 6 | true 7 | com.mysql.jdbc.Driver 8 | jdbc:mysql://localhost:6603/ansible_inventory 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /.idea/dataSources/32e888d2-fd27-442f-8d4e-bf9fb9d0648e.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 1 7 | 1 8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 |
16 |
17 | 18 | VIEW 19 | 20 | 21 | VIEW 22 | 23 | 24 | 1 25 | int(11)|0 26 | 1 27 | 1 28 | 29 | 30 | 2 31 | int(11)|0 32 | 1 33 | 34 | 35 | 3 36 | int(11)|0 37 | 1 38 | 39 | 40 | child_id 41 | 42 | 43 | parent_id 44 | 45 | 46 | child_id 47 | parent_id 48 | 1 49 | 50 | 51 | 1 52 | id 53 | 1 54 | 55 | 56 | child_id 57 | parent_id 58 | childid 59 | 60 | 61 | child_id 62 | ansible_inventory 63 | group 64 | id 65 | 66 | 67 | parent_id 68 | ansible_inventory 69 | group 70 | id 71 | 72 | 73 | 1 74 | int(11)|0 75 | 1 76 | 1 77 | 78 | 79 | 2 80 | varchar(255)|0 81 | 1 82 | 83 | 84 | 3 85 | longtext|0 86 | 87 | 88 | 4 89 | tinyint(1)|0 90 | 1 91 | 92 | 93 | name 94 | 1 95 | 96 | 97 | 1 98 | id 99 | 1 100 | 101 | 102 | name 103 | group_name 104 | 105 | 106 | 1 107 | int(11)|0 108 | 1 109 | 1 110 | 111 | 112 | 2 113 | varchar(255)|0 114 | 1 115 | 116 | 117 | 3 118 | varchar(255)|0 119 | 1 120 | 121 | 122 | 4 123 | longtext|0 124 | 125 | 126 | 5 127 | tinyint(1)|0 128 | 1 129 | 130 | 131 | host 132 | 1 133 | 134 | 135 | hostname 136 | 1 137 | 138 | 139 | 1 140 | id 141 | 1 142 | 143 | 144 | host 145 | host_host 146 | 147 | 148 | hostname 149 | host_hostname 150 | 151 | 152 | 1 153 | int(11)|0 154 | 1 155 | 1 156 | 157 | 158 | 2 159 | int(11)|0 160 | 1 161 | 162 | 163 | 3 164 | int(11)|0 165 | 1 166 | 167 | 168 | group_id 169 | 170 | 171 | host_id 172 | 173 | 174 | host_id 175 | group_id 176 | 1 177 | 178 | 179 | 1 180 | id 181 | 1 182 | 183 | 184 | host_id 185 | group_id 186 | host_id 187 | 188 | 189 | host_id 190 | ansible_inventory 191 | host 192 | id 193 | 194 | 195 | group_id 196 | ansible_inventory 197 | group 198 | id 199 | 200 | 201 | 1 202 | varchar(255)|0 203 | 204 | 205 | 2 206 | varchar(255)|0 207 | 208 | 209 | 1 210 | varchar(255)|0 211 | 1 212 | 213 | 214 | 2 215 | varchar(255)|0 216 | 217 | 218 | 3 219 | varchar(255)|0 220 | 221 | 222 | 4 223 | longtext|0 224 | 225 | 226 | -------------------------------------------------------------------------------- /.idea/dataSources/32e888d2-fd27-442f-8d4e-bf9fb9d0648e/_metadata_/metadata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/askdaddy/ansible-dynamic-inventory-mysql/5695c31d4a0621898d24af4ac2b8981da3639077/.idea/dataSources/32e888d2-fd27-442f-8d4e-bf9fb9d0648e/_metadata_/metadata -------------------------------------------------------------------------------- /.idea/dataSources/32e888d2-fd27-442f-8d4e-bf9fb9d0648e/_metadata_/metadata.keystream: -------------------------------------------------------------------------------- 1 | ansible_inventoryschemachildrenviewansible_inventoryschema inventoryview -------------------------------------------------------------------------------- /.idea/dataSources/32e888d2-fd27-442f-8d4e-bf9fb9d0648e/_metadata_/metadata.keystream.len: -------------------------------------------------------------------------------- 1 | [ -------------------------------------------------------------------------------- /.idea/dataSources/32e888d2-fd27-442f-8d4e-bf9fb9d0648e/_metadata_/metadata.len: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/askdaddy/ansible-dynamic-inventory-mysql/5695c31d4a0621898d24af4ac2b8981da3639077/.idea/dataSources/32e888d2-fd27-442f-8d4e-bf9fb9d0648e/_metadata_/metadata.len -------------------------------------------------------------------------------- /.idea/dataSources/32e888d2-fd27-442f-8d4e-bf9fb9d0648e/_metadata_/metadata.values.at: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/askdaddy/ansible-dynamic-inventory-mysql/5695c31d4a0621898d24af4ac2b8981da3639077/.idea/dataSources/32e888d2-fd27-442f-8d4e-bf9fb9d0648e/_metadata_/metadata.values.at -------------------------------------------------------------------------------- /.idea/dataSources/32e888d2-fd27-442f-8d4e-bf9fb9d0648e/_metadata_/metadata_i: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/askdaddy/ansible-dynamic-inventory-mysql/5695c31d4a0621898d24af4ac2b8981da3639077/.idea/dataSources/32e888d2-fd27-442f-8d4e-bf9fb9d0648e/_metadata_/metadata_i -------------------------------------------------------------------------------- /.idea/dataSources/32e888d2-fd27-442f-8d4e-bf9fb9d0648e/_metadata_/metadata_i.len: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/askdaddy/ansible-dynamic-inventory-mysql/5695c31d4a0621898d24af4ac2b8981da3639077/.idea/dataSources/32e888d2-fd27-442f-8d4e-bf9fb9d0648e/_metadata_/metadata_i.len -------------------------------------------------------------------------------- /.idea/dataSources/32e888d2-fd27-442f-8d4e-bf9fb9d0648e/_src_/schema/ansible_inventory.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/askdaddy/ansible-dynamic-inventory-mysql/5695c31d4a0621898d24af4ac2b8981da3639077/.idea/dataSources/32e888d2-fd27-442f-8d4e-bf9fb9d0648e/_src_/schema/ansible_inventory.zip -------------------------------------------------------------------------------- /.idea/dataSources/32e888d2-fd27-442f-8d4e-bf9fb9d0648e/storage.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.idea/dictionaries/seven.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ansible 5 | askdaddy 6 | gname 7 | groupdata 8 | groupinfo 9 | hostdata 10 | hostgroups 11 | kbits 12 | lastrowid 13 | myconfig 14 | reformated 15 | ungrouped 16 | 17 | 18 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 110 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/workspace.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 15 | 16 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 257 | 258 | 259 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 1508222040745 268 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 303 | 304 | 306 | 307 | 308 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | # Ansible Dynamic Inventory for MySQL 2 | 3 | This is a [Dynamic Inventory](http://docs.ansible.com/ansible/intro_dynamic_inventory.html) for [Ansible](https://github.com/ansible/ansible) to be used together with MySQL. 4 | 5 | It was written because we maintain a lot of servers and static inventory files did not meet our demand, and we like MySQL. 6 | 7 | ## Usage 8 | ### Work with ansible and ansible-playbook 9 | Simply call the script like the following 10 | 11 | ``` 12 | ansible-playbook -i inventory.py 13 | # or 14 | ansible -i inventory.py 15 | ``` 16 | 17 | Limitations also work 18 | 19 | ``` 20 | ansible-playbook -i inventory.py --limit foo.bar.com 21 | ansible-playbook -i inventory.py --limit groupFoo 22 | ``` 23 | 24 | ### Manager inventory Database 25 | #### Add host 26 | Add a new host 27 | - -H: set host dns `my.host.domain`, can also set ip address 28 | - [-g]: set group name is `my`, otherwise host will add to group called `ungrouped` 29 | - [-v key val]: 2 sets of variables { var0:val0, var1:val1 } 30 | - See details: `python inventoryctl.py host -h` 31 | ``` 32 | $ python inventoryctl.py host -H my.host.domain -g my -v var0 val0 -v var1 val1 33 | Command: host 34 | {'enabled': 1, 'variables': None, 'id': 1, 'name': 'my'} 35 | ``` 36 | 37 | #### Update host 38 | - -H: which host will be update 39 | - -U: enter update mode, otherwise only view the host 40 | - See details: `python inventoryctl.py host -h` 41 | ``` 42 | $ python inventoryctl.py host -H my.host.domain -U -v var2 val2 43 | Command: host 44 | Update mode 45 | set variables to {"var1": "val1", "var0": "val0", "var2": "val2"} 46 | Update my.host.domain affected rows: 1 47 | ``` 48 | 49 | ## Setup 50 | I won't explain the process of installing a database or creating the tables, see `tables.sql` for the required MySQL structure. 51 | 52 | Once setup rename `mysql.ini.dist` to `mysql.ini` to suit your needs, if you don't want to use caching just put it on 0. 53 | 54 | ### Groups 55 | In the table `group` you create the groups you need and their variables, 56 | 57 | ### Hosts 58 | In the table `host` under `host` you place the IP/DNS for the system. 59 | 60 | #### Facts 61 | Under `hostname` you can fill in a value, this will be presented as a variable `inventory_hostname` during the play. 62 | You can modify the name of this Fact variable by changing the `facts_hostname_var` variable in my `mysql.ini`. 63 | 64 | ### Relation between Hosts and Groups 65 | The table `hostgroups` maps the relation between `host` and `group` using two `FOREIGN KEYS`. 66 | 67 | #### Children 68 | Groups can have other groups as children, use the table `childgroups`. 69 | 70 | ### Note on Variables 71 | This applies to `host` and `group` respectively. 72 | If no variables are needed either NULL it (actual MySQL `NULL` not the `string`) or use `{}`. 73 | 74 | 75 | ## LICENSE 76 | 77 | As it was fork from [productsupcom/ansible-dyninv-mysql](https://github.com/productsupcom/ansible-dyninv-mysql), 78 | the same license, the GPL-3 applies. 79 | 80 | 81 | The [GPL-3](http://www.gnu.org/licenses/gpl-3.0.en.html) can be found under the link. 82 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/askdaddy/ansible-dynamic-inventory-mysql/5695c31d4a0621898d24af4ac2b8981da3639077/__init__.py -------------------------------------------------------------------------------- /inventory.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | MySQL external inventory script 5 | ================================= 6 | 7 | External inventory using a MySQL backend. 8 | 9 | Requires a MySQL database using a few predefined tables. 10 | See the mysql.sql file for the tables to import, 11 | modify mysql.ini to match your login credentials. 12 | 13 | Extended upon the Cobbler Inventory script. 14 | 15 | """ 16 | 17 | # Copyright (c) 2015 Productsup GmbH, Yorick Terweijden yt@products-up.de 18 | # 19 | # As it is mostly based on the original Cobbler Dynamic Inventory 20 | # https://github.com/ansible/ansible/blob/devel/contrib/inventory/cobbler.py 21 | # the same license, the GPL-3 applies. 22 | # 23 | ###################################################################### 24 | 25 | import argparse 26 | import ast 27 | import configparser 28 | import os 29 | import pprint 30 | import re 31 | from time import time 32 | import pymysql.cursors 33 | 34 | try: 35 | import json 36 | from json import JSONDecodeError 37 | except ImportError: 38 | import simplejson as json 39 | from simplejson import JSONDecodeError 40 | 41 | 42 | class MySQLInventory(object): 43 | def __init__(self): 44 | 45 | """ Main execution path """ 46 | self.conn = None 47 | self.myconfig = None 48 | self.cache_path_cache = None 49 | self.cache_path_inventory = None 50 | self.cache_max_age = None 51 | self.facts_hostname_var = None 52 | 53 | self.hosts = dict() 54 | self.inventory = dict() # A list of groups and the hosts in that group 55 | self.cache = dict() # Details about hosts in the inventory 56 | 57 | # Read settings and parse CLI arguments 58 | self.read_settings() 59 | self.parse_cli_args() 60 | 61 | # Cache 62 | if self.args.refresh_cache: 63 | self.update_cache() 64 | elif not self.is_cache_valid(): 65 | self.update_cache() 66 | else: 67 | self.load_inventory_from_cache() 68 | self.load_cache_from_cache() 69 | 70 | data_to_print = "" 71 | 72 | # Data to print 73 | if self.args.host: 74 | data_to_print += self.get_host_info() 75 | else: 76 | self.inventory['_meta'] = {'hostvars': {}} 77 | for hostname in self.cache: 78 | self.inventory['_meta']['hostvars'][hostname] = self.cache[hostname] 79 | data_to_print += self.json_format_dict(self.inventory, True) 80 | 81 | print(data_to_print) 82 | 83 | def _connect(self): 84 | if not self.conn: 85 | self.conn = pymysql.connect(**self.myconfig) 86 | 87 | def is_cache_valid(self): 88 | """ Determines if the cache files have expired, or if it is still valid """ 89 | 90 | if os.path.isfile(self.cache_path_cache): 91 | mod_time = os.path.getmtime(self.cache_path_cache) 92 | current_time = time() 93 | if (mod_time + self.cache_max_age) > current_time: 94 | if os.path.isfile(self.cache_path_inventory): 95 | return True 96 | 97 | return False 98 | 99 | def read_settings(self): 100 | """ Reads the settings from the mysql.ini file """ 101 | 102 | config = configparser.ConfigParser() 103 | config.read(os.path.dirname(os.path.realpath(__file__)) + '/mysql.ini') 104 | 105 | self.myconfig = dict(config.items('server')) 106 | if 'port' in self.myconfig: 107 | self.myconfig['port'] = config.getint('server', 'port') 108 | 109 | # Cache related 110 | cache_path = config.get('config', 'cache_path') 111 | self.cache_path_cache = cache_path + "/ansible-mysql.cache" 112 | self.cache_path_inventory = cache_path + "/ansible-mysql.index" 113 | self.cache_max_age = config.getint('config', 'cache_max_age') 114 | 115 | # Other config 116 | self.facts_hostname_var = config.get('config', 'facts_hostname_var') 117 | 118 | def parse_cli_args(self): 119 | """ Command line argument processing """ 120 | 121 | parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on MySQL') 122 | parser.add_argument('--list', action='store_true', default=True, help='List instances (default: True)') 123 | parser.add_argument('--host', action='store', help='Get all the variables about a specific instance') 124 | parser.add_argument('--refresh-cache', action='store_true', default=False, 125 | help='Force refresh of cache by making API requests to MySQL \ 126 | (default: False - use cache files)') 127 | self.args = parser.parse_args() 128 | 129 | def process_group(self, groupname): 130 | # Fetch the Group info 131 | if groupname not in self.inventory: 132 | cursor = self.conn.cursor(pymysql.cursors.DictCursor) 133 | sql = "SELECT variables FROM `group` WHERE name = %s" 134 | cursor.execute(sql, groupname) 135 | groupinfo = cursor.fetchone() 136 | self.inventory[groupname] = dict() 137 | 138 | if groupinfo is not None and 'variables' in groupinfo: 139 | if groupinfo['variables'] and not self.isNone(groupinfo['variables']) and groupinfo['variables'].strip(): 140 | try: 141 | vs = json.loads(groupinfo['variables']) 142 | self.inventory[groupname]['vars'] = vs if vs is not None else {} 143 | self.inventory[groupname]['hosts'] = list() 144 | except JSONDecodeError as e: 145 | print(e) 146 | raise Exception('Group does not have valid JSON', groupname, groupinfo['variables']) 147 | 148 | if 'vars' not in self.inventory[groupname]: 149 | self.inventory[groupname] = list() 150 | 151 | def update_cache(self): 152 | """ Make calls to MySQL and save the output in a cache """ 153 | 154 | self._connect() 155 | self.hosts = dict() 156 | 157 | # Fetch the systems 158 | cursor = self.conn.cursor(pymysql.cursors.DictCursor) 159 | sql = "SELECT * FROM inventory;" 160 | cursor.execute(sql) 161 | data = cursor.fetchall() 162 | 163 | for host in data: 164 | self.process_group(host['group']) 165 | 166 | if 'hosts' in self.inventory[host['group']]: 167 | self.inventory[host['group']]['hosts'].append(host['host']) 168 | else: 169 | self.inventory[host['group']].append(host['host']) 170 | 171 | dns_name = host['host'] 172 | if host['host_vars'] and ast.literal_eval(host['host_vars']) is not None and host['host_vars'].strip(): 173 | try: 174 | cleanhost = json.loads(host['host_vars']) 175 | except JSONDecodeError as e: 176 | print(e) 177 | raise Exception('Host does not have valid JSON', host['host'], host['host_vars']) 178 | else: 179 | cleanhost = dict() 180 | cleanhost[self.facts_hostname_var] = host['hostname'] 181 | 182 | self.cache[dns_name] = cleanhost 183 | 184 | # first fetch all the groups to check for possible childs 185 | gsql = """SELECT 186 | `gparent`.`name` as `parent`, 187 | `gchild`.`name` as `child` 188 | FROM childgroups 189 | LEFT JOIN `group` `gparent` on `childgroups`.`parent_id` = `gparent`.`id` 190 | LEFT JOIN `group` `gchild` on `childgroups`.`child_id` = `gchild`.`id` 191 | ORDER BY `parent`;""" 192 | 193 | cursor.execute(gsql) 194 | groupdata = cursor.fetchall() 195 | 196 | for group in groupdata: 197 | self.process_group(group['parent']) 198 | if 'hosts' not in self.inventory[group['parent']]: 199 | self.inventory[group['parent']] = {'hosts': self.inventory[group['parent']]} 200 | 201 | if 'children' not in self.inventory[group['parent']]: 202 | self.inventory[group['parent']]['children'] = list() 203 | 204 | self.inventory[group['parent']]['children'].append(group['child']) 205 | 206 | # cleanup output 207 | for group in self.inventory: 208 | if 'hosts' in self.inventory[group] and not self.inventory[group]['hosts']: 209 | del self.inventory[group]['hosts'] 210 | 211 | self.write_to_cache(self.cache, self.cache_path_cache) 212 | self.write_to_cache(self.inventory, self.cache_path_inventory) 213 | 214 | def get_host_info(self): 215 | """ Get variables about a specific host """ 216 | 217 | if not self.cache or len(self.cache) == 0: 218 | # Need to load index from cache 219 | self.load_cache_from_cache() 220 | 221 | if not self.args.host in self.cache: 222 | # try updating the cache 223 | self.update_cache() 224 | 225 | if not self.args.host in self.cache: 226 | # host might not exist anymore 227 | return self.json_format_dict({}, True) 228 | 229 | return self.json_format_dict(self.cache[self.args.host], True) 230 | 231 | def push(self, my_dict, key, element): 232 | """ Pushed an element onto an array that may not have been defined in the dict """ 233 | 234 | if key in my_dict: 235 | my_dict[key].append(element) 236 | else: 237 | my_dict[key] = [element] 238 | 239 | def load_inventory_from_cache(self): 240 | """ Reads the index from the cache file sets self.index """ 241 | 242 | cache = open(self.cache_path_inventory, 'r') 243 | json_inventory = cache.read() 244 | self.inventory = json.loads(json_inventory) 245 | 246 | def load_cache_from_cache(self): 247 | """ Reads the cache from the cache file sets self.cache """ 248 | 249 | cache = open(self.cache_path_cache, 'r') 250 | json_cache = cache.read() 251 | self.cache = json.loads(json_cache) 252 | 253 | def write_to_cache(self, data, filename): 254 | """ Writes data in JSON format to a file """ 255 | json_data = self.json_format_dict(data, True) 256 | cache = open(filename, 'w') 257 | cache.write(json_data) 258 | cache.close() 259 | 260 | @staticmethod 261 | def to_safe(word): 262 | """ Converts 'bad' characters in a string to underscores so they can be used as Ansible groups """ 263 | 264 | return re.sub("[^A-Za-z0-9\-]", "_", word) 265 | 266 | @staticmethod 267 | def json_format_dict(data, pretty=False): 268 | """ Converts a dict to a JSON object and dumps it as a formatted string """ 269 | 270 | if pretty: 271 | return json.dumps(data, sort_keys=True, indent=2) 272 | else: 273 | return json.dumps(data) 274 | 275 | @staticmethod 276 | def isNone(var): 277 | if (type(var) is str): 278 | return var.lower() == 'none' 279 | return var is None 280 | 281 | 282 | MySQLInventory() 283 | -------------------------------------------------------------------------------- /inventoryctl.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Created on 19/10/2017 4 | 5 | @author: askdaddy 6 | """ 7 | import argparse 8 | import ast 9 | import configparser 10 | import os 11 | import pprint 12 | import sys 13 | from distutils.util import strtobool 14 | import pymysql 15 | 16 | try: 17 | import json 18 | from json import JSONDecodeError 19 | except ImportError: 20 | import simplejson as json 21 | from simplejson import JSONDecodeError 22 | 23 | VAR_DEL_MARK = 'nil' 24 | 25 | 26 | class InventoryCtl(object): 27 | def __init__(self): 28 | self.myconfig = None 29 | self.facts_hostname_var = None 30 | self.conn = None 31 | self.cursor = None 32 | 33 | self.args = [] 34 | self.read_settings() 35 | self.parse_cli_args() 36 | 37 | # pprint.pprint(self.args) 38 | self.run_command() 39 | 40 | def read_settings(self): 41 | """ Reads the settings from the mysql.ini file """ 42 | 43 | config = configparser.ConfigParser() 44 | config.read(os.path.dirname(os.path.realpath(__file__)) + '/mysql.ini') 45 | self.myconfig = dict(config.items('server')) 46 | if 'port' in self.myconfig: 47 | self.myconfig['port'] = config.getint('server', 'port') 48 | 49 | self.facts_hostname_var = config.get('config', 'facts_hostname_var') 50 | 51 | def parse_cli_args(self): 52 | """ Command line argument processing """ 53 | 54 | parser = argparse.ArgumentParser( 55 | description='Query or send control commands to the Ansible Dynamic Inventory based on MySQL' 56 | ) 57 | 58 | # Sub commands 59 | subparsers = parser.add_subparsers(dest='cmd') 60 | 61 | # Groups 62 | parser_group = subparsers.add_parser('group', help='Create or Update a Group') 63 | parser_group.add_argument('-U', '--update', action='store_true', 64 | help='Enable Update mode. In this mode, the existing Group will be updated') 65 | parser_group.add_argument('-n', '--name', required=True, 66 | help='Name of the Group') 67 | parser_group.add_argument('-p', '--parent', 68 | help='Name of parent Group') 69 | parser_group.add_argument('-e', '--enabled', type=int, choices=[0, 1], 70 | help='Whether to enable this Group') 71 | parser_group.add_argument('-v', '--variable', action='append', nargs=2, metavar=('key', 'val'), 72 | help='Add multiple Variables to an entire Group \ 73 | If val is `%s`, the variable will be removed.' % VAR_DEL_MARK) 74 | 75 | # Hosts 76 | parser_host = subparsers.add_parser('host', help='Add , Update or Delete a host') 77 | parser_host.add_argument('-U', '--update', action='store_true', 78 | help='Enable Update mode. In this mode, the existing Host will be updated') 79 | parser_host.add_argument('-n', '--name', 80 | help='Hostname of the host') 81 | parser_host.add_argument('-H', '--host', required=True, 82 | help='IP address or Domain of the Host') 83 | parser_host.add_argument('-g', '--group', default=None, 84 | help='The name of the group to join. \ 85 | If not set, the Host will NOT join any group') 86 | parser_host.add_argument('-e', '--enabled', type=int, choices=[0, 1], 87 | help='Whether to enable this Host') 88 | parser_host.add_argument('-v', '--variable', action='append', nargs=2, metavar=('key', 'val'), 89 | help='Add/Edit multiple Variables to an entire Host, \ 90 | e.g. ssh_user, ssh_password, ssh_key. \ 91 | If val is `%s`, the variable will be removed.' % VAR_DEL_MARK) 92 | parser_host.add_argument('-d', '--delete', action='store_true', 93 | help='Delete host') 94 | # List Hosts && Groups 95 | parser_list = subparsers.add_parser('ls', 96 | help='List the Hosts or groups information') 97 | parser_list.add_argument('-g', '--group', action='store_true', 98 | help='Whether to show Groups or not') 99 | exclusion_group = parser_list.add_mutually_exclusive_group() 100 | exclusion_group.add_argument('-a', '--all', action='store_true', 101 | help='List all, including disabled') 102 | exclusion_group.add_argument('-m', '--match', 103 | help='list only matches a part of the \ 104 | `host` or `hostname` of host and `name` of group') 105 | 106 | if len(sys.argv[1:]) == 0: 107 | parser.print_help() 108 | parser.exit() 109 | self.args = parser.parse_args() 110 | 111 | def run_command(self): 112 | self._connect() 113 | print('[Command]: %s' % self.args.cmd) 114 | if self.args.cmd == 'host': 115 | self._cmd_host() 116 | elif self.args.cmd == 'group': 117 | self._cmd_group() 118 | elif self.args.cmd == 'ls': 119 | self._cmd_ls() 120 | else: 121 | print('Invalid instruction.') 122 | self._disconnect() 123 | 124 | def _cmd_host(self): 125 | hostdata, groupdata = self._host_fetch() 126 | 127 | if hostdata is None: 128 | # Add new host 129 | self._host_add(groupdata) 130 | else: 131 | # Delete host 132 | if 'delete' in self.args and self.args.delete is True: 133 | if self._prompt("Are you sure you want to delete the host: %s[%s] ?! \ 134 | \nAfter deleting the data will not be restored!! " % ( 135 | hostdata['host'], hostdata['hostname'])): 136 | self._host_delete(hostdata) 137 | else: 138 | print('User canceled the operation.') 139 | return 140 | 141 | # Update host 142 | self._host_update(hostdata, groupdata) 143 | 144 | def _cmd_group(self): 145 | gname = self.args.name 146 | parent_group = self.args.parent 147 | groups = self._group_fetch() 148 | if parent_group is not None and parent_group not in groups: 149 | # parent does not exist 150 | raise Exception('The specified group[%s] does not exist' % parent_group) 151 | 152 | if gname not in groups: 153 | # Add a new group with its parent 154 | self._group_add(gname, groups) 155 | 156 | elif gname in groups: 157 | groupdata = groups[gname] 158 | 159 | # Delete host 160 | if 'delete' in self.args and self.args.delete is True: 161 | if self._prompt("Are you sure you want to delete the group: %s ?! \ 162 | \nAfter deleting the data will not be restored!! " % gname): 163 | self._group_delete(groupdata) 164 | else: 165 | print('User canceled the operation.') 166 | return 167 | 168 | # group already exists 169 | # Update group 170 | self._group_update(gname, groups) 171 | 172 | def _cmd_ls(self): 173 | # Default list all hosts and their groups info 174 | if self.args.group: 175 | self._list_groups() 176 | else: 177 | self._list_hosts() 178 | 179 | @property 180 | def __enabled(self): 181 | if self.args.enabled is None: 182 | return 1 183 | return self.args.enabled 184 | 185 | @property 186 | def __hostname(self): 187 | if self.args.name is not None: 188 | return self.args.name 189 | return self.args.host 190 | 191 | def _host_fetch(self): 192 | host = self.args.host 193 | group = self.args.group 194 | groupdata = None 195 | # if set group name [-g/--group] 196 | # convert group name to group id 197 | if group is not None: 198 | sql = "SELECT * FROM `group` WHERE `group`.`name` = '%s'" 199 | self.__cursor.execute(sql % group) 200 | groupdata = self.__cursor.fetchone() 201 | if groupdata is None: 202 | print('Group %s does NOT exist!' % self.args.group) 203 | else: 204 | print('Assign to group: %s [id=%d]' % (groupdata['name'], groupdata['id'])) 205 | 206 | # fetch host data 207 | sql = """SELECT `host`.`id`,`host`.`host`,`host`.`hostname`,`host`.`enabled`,`host`.`variables`, 208 | `group`.`id` as `group_id`,`group`.`name` as `group_name`,`group`.`enabled` as `group_enabled`, `group`.`variables` as `group_variables` 209 | FROM (`host` LEFT JOIN `hostgroups` ON `host`.`id` = `hostgroups`.`host_id` 210 | LEFT JOIN `group` ON `hostgroups`.`group_id`=`group`.`id`) 211 | WHERE `host`.`host` = '%s';""" 212 | self.__cursor.execute(sql % host) 213 | hostdata = self.__cursor.fetchone() 214 | 215 | return hostdata, groupdata 216 | 217 | def _host_add(self, group): 218 | affected_rows = 0 219 | print('Create mode') 220 | 221 | # combination variables 222 | 223 | variables = None 224 | if self.args.variable is not None: 225 | variables = json.dumps({item[0]: item[1] for item in self.args.variable}) 226 | 227 | print('Add host: %s %s %s %d' % (self.args.host, self.__hostname, variables, self.__enabled)) 228 | sql = """INSERT INTO `host` 229 | (`host`, `hostname`, `variables`, `enabled`) VALUES 230 | ('%s', '%s', '%s', %d);""" 231 | affected_rows += self.__cursor.execute(sql % (self.args.host, self.__hostname, variables, self.__enabled)) 232 | if group is not None: 233 | # Add group 234 | lastrowid = self.__cursor.lastrowid 235 | sql = """INSERT INTO `hostgroups` 236 | (`host_id`, `group_id`) VALUES 237 | (%d, %d);""" 238 | affected_rows += self.__cursor.execute(sql % (lastrowid, group['id'])) 239 | self.conn.commit() 240 | print('Affected rows: %d' % affected_rows) 241 | 242 | def _host_delete(self, host): 243 | print("Remove host from groups") 244 | rows = self.__cursor.execute("""DELETE FROM `hostgroups` WHERE `hostgroups`.`host_id` = %d;""" % host['id']) 245 | print('Affected rows: %d' % rows) 246 | 247 | print('Delete host: id = %d' % id) 248 | rows = self.__cursor.execute("""DELETE FROM `host` WHERE `host`.`id` = %d;""" % host['id']) 249 | print('Affected rows: %d' % rows) 250 | 251 | self.conn.commit() 252 | 253 | def _host_update(self, host, group): 254 | if self.args.update: 255 | print('Update mode') 256 | affected_rows = 0 257 | 258 | if group is not None: 259 | # sql = """UPDATE `hostgroups` SET `group_id` = %d WHERE `host_id` = %d;""" 260 | sql = """REPLACE into `hostgroups` (`host_id`,`group_id`) values(%d,%d)""" 261 | affected_rows += self.__cursor.execute(sql % (host['id'], group['id'])) 262 | print('set group to %s' % group['name']) 263 | 264 | # update hostname 265 | if self.args.name is not None: 266 | # TODO Verify the name is valid 267 | sql = """UPDATE `host` SET `hostname` = '%s' WHERE `host`.`id` = %d;""" 268 | affected_rows += self.__cursor.execute(sql % (self.args.name, host['id'])) 269 | print('set hostname to %s' % self.args.name) 270 | 271 | # modify variables 272 | if self.args.variable is not None: 273 | try: 274 | if ast.literal_eval(host['variables']) is not None: 275 | variables = json.loads(host['variables']) 276 | for var in self.args.variable: 277 | variables[var[0]] = var[1] 278 | else: 279 | variables = {item[0]: item[1] for item in self.args.variable} 280 | 281 | for _k, _v in variables.copy().items(): 282 | if _v == VAR_DEL_MARK: 283 | variables.pop(_k, None) 284 | 285 | var_json = json.dumps(variables) 286 | sql = """UPDATE `host` SET `variables` = '%s' WHERE `host`.`id` = %d;""" 287 | affected_rows += self.__cursor.execute(sql % (var_json, host['id'])) 288 | print('set variables to %s' % var_json) 289 | except JSONDecodeError as e: 290 | print(e) 291 | raise Exception('Host does not have valid JSON', host['host'], host['variables']) 292 | 293 | # change enable state 294 | if host['enabled'] != self.__enabled: 295 | sql = """UPDATE `host` SET `enabled` = %d WHERE `host`.`id` = %d;""" 296 | affected_rows += self.__cursor.execute(sql % (self.__enabled, host['id'])) 297 | print('set enabled to %d' % self.__enabled) 298 | 299 | # commit to db 300 | print('Update %s affected rows: %d' % (host['host'], affected_rows)) 301 | self.conn.commit() 302 | else: 303 | # only show the host data 304 | host['group'] = group 305 | pprint.pprint(host) 306 | print(' ----- ') 307 | print('If you want to UPDATE this host, plz attach -U/--update argument') 308 | 309 | def _group_fetch(self): 310 | # a list store all the names to query 311 | group_names = [self.args.name] 312 | 313 | if self.args.parent is not None: 314 | group_names.append(self.args.parent) 315 | 316 | # fetch group info with name 317 | sql = """SELECT `child`.`name`,`child`.`id`,`child`.`variables`,`child`.`enabled`, 318 | `parent`.`name`,`parent`.`id` as `parent_id`, `parent`.`variables` as `parent_variables`, 319 | `parent`.`enabled` as `parent_enabled` 320 | FROM `group` `child` 321 | LEFT JOIN `childgroups` ON `child`.`id` = `childgroups`.`child_id` 322 | LEFT JOIN `group` `parent` ON `childgroups`.`parent_id` = `parent`.`id` 323 | WHERE `child`.`name` IN (%s);""" 324 | self.__cursor.execute(sql % ("'" + "','".join(map(str, group_names)) + "'")) 325 | groups = self.__cursor.fetchall() 326 | 327 | return {i['name']: i for i in groups} 328 | 329 | def _group_add(self, gname, groups): 330 | affected_rows = 0 331 | # add a new group 332 | print('Create mode') 333 | 334 | # combination variables 335 | variables = None 336 | if self.args.variable is not None: 337 | variables = json.dumps({item[0]: item[1] for item in self.args.variable}) 338 | 339 | sql = """INSERT INTO `group` (`name`, `variables`, `enabled`) 340 | VALUES ('%s', '%s', %d);""" 341 | affected_rows += self.__cursor.execute(sql % (gname, variables, self.__enabled)) 342 | lastrowid = self.__cursor.lastrowid 343 | 344 | if self.args.parent is not None: 345 | # the new group has a parent 346 | sql = """INSERT INTO `childgroups` (`child_id`,`parent_id`) VALUES 347 | (%d,%d);""" 348 | affected_rows += self.__cursor.execute(sql % (lastrowid, groups[self.args.parent]['id'])) 349 | self.conn.commit() 350 | print('Affected rows: %d' % affected_rows) 351 | print('Add group id: %d' % lastrowid) 352 | 353 | def _group_delete(self, group): 354 | print('Break the relationship between groups') 355 | s = """DELETE FROM `childgroups` WHERE `child_id` = %d OR `parent_id` = %d;""" 356 | rows = self.__cursor.execute(s % (group['id'], group['id'])) 357 | print('Affected rows: %d' % rows) 358 | 359 | print('Delete group named `%s` with variables %s' % (group['name'], group['variables'])) 360 | s = """DELETE FROM `group` WHERE `id` = %d;""" 361 | rows = self.__cursor.execute(s % group['id']) 362 | print('Affected rows: %d' % rows) 363 | self.conn.commit() 364 | 365 | def _group_update(self, gname, groups): 366 | affected_rows = 0 367 | group = groups[gname] 368 | parent = None 369 | if self.args.parent in groups: 370 | parent = group[self.args.parent] 371 | 372 | if self.args.update: 373 | print('Update mode') 374 | if group['enabled'] != self.__enabled: 375 | # modify enabled 376 | sql = """UPDATE `group` SET `enabled` = %d WHERE `id` = %d;""" 377 | affected_rows += self.__cursor.execute(sql % (self.args.enabled, group['id'])) 378 | 379 | # modify variables 380 | if self.args.variable is not None: 381 | try: 382 | if ast.literal_eval(group['variables']) is not None: 383 | variables = json.loads(group['variables']) 384 | for var in self.args.variable: 385 | variables[var[0]] = var[1] 386 | else: 387 | variables = {item[0]: item[1] for item in self.args.variable} 388 | 389 | for _k, _v in variables.copy().items(): 390 | if _v == VAR_DEL_MARK: 391 | variables.pop(_k, None) 392 | 393 | var_json = json.dumps(variables) 394 | sql = """UPDATE `group` SET `variables` = '%s' WHERE `group`.`id` = %d;""" 395 | affected_rows += self.__cursor.execute(sql % (var_json, group['id'])) 396 | print('set variables to %s' % var_json) 397 | except JSONDecodeError as e: 398 | print(e) 399 | raise Exception('Group does not have valid JSON', group['name'], group['variables']) 400 | 401 | # modify parent group 402 | if parent is not None: 403 | sql = """UPDATE `childgroups` SET `parent_id` = %d WHERE `child_id` = %d;""" 404 | affected_rows += self.__cursor.execute(sql % (group['id'], parent['id'])) 405 | 406 | self.conn.commit() 407 | 408 | else: 409 | print('View mode') 410 | pprint.pprint(groups[g['name']]) 411 | print(' ----- ') 412 | print('If you want to UPDATE this group, plz attach -U/--update argument') 413 | 414 | def _list_hosts(self): 415 | sql = """SELECT `host`.`host`,`host`.`hostname`,`host`.`variables` AS `vars`, `host`.`enabled`, 416 | `group`.`name` AS `group`,`group`.`variables` AS `group_vars` 417 | FROM `host` 418 | LEFT JOIN `hostgroups` ON `host`.id = `hostgroups`.`host_id` 419 | LEFT JOIN `group` ON `hostgroups`.`group_id` = `group`.`id` 420 | {} 421 | ORDER BY `host`.`host`;""" 422 | 423 | # default 424 | where = "WHERE `host`.`enabled` = 1" 425 | if self.args.all: 426 | where = '' 427 | 428 | if self.args.match is not None: 429 | m = self.args.match 430 | where = "WHERE `host`.`host` LIKE '%%%s%%' OR `host`.`hostname` LIKE '%%%s%%'" % (m, m) 431 | 432 | sql = sql.format(where) 433 | 434 | self.__cursor.execute(sql) 435 | hosts = self.__cursor.fetchall() 436 | 437 | # reformat 438 | reformated = dict() 439 | for host in hosts: 440 | h_vars = None 441 | g_vars = None 442 | try: 443 | if host['vars'] is not None: 444 | h_vars = json.loads(host['vars']) 445 | if host['group_vars'] is not None: 446 | g_vars = json.loads(host['group_vars']) 447 | except JSONDecodeError: 448 | pass 449 | 450 | reformated[host['host']] = { 451 | 'hostname': host['hostname'], 452 | 'vars': h_vars, 453 | 'group': host['group'], 454 | 'group_vars': g_vars} 455 | if 'enabled' in host: 456 | reformated[host['host']]['state'] = 'enable' if host['enabled'] == 1 else 'disable' 457 | 458 | pprint.pprint(reformated) 459 | 460 | def _list_groups(self): 461 | sql = """SELECT `gc`.`name` as `child`,`gc`.`variables` as `c_vars`, 462 | `gp`.`name` as `parent` ,`gp`.`variables` as `p_vars` 463 | FROM `group` `gc` 464 | LEFT JOIN `childgroups` ON `gc`.`id` = `childgroups`.`child_id` 465 | LEFT JOIN `group` `gp` ON `childgroups`.`parent_id` = `gp`.`id` 466 | {} 467 | ORDER BY `parent` 468 | """ 469 | # default 470 | where = "WHERE `gc`.`enabled` = 1 " 471 | if self.args.all: 472 | where = '' 473 | 474 | if self.args.match is not None: 475 | m = self.args.match 476 | where = "WHERE `gc`.`name` LIKE '%%%s%%' OR `gp`.`name` LIKE '%%%s%%' " % (m, m) 477 | 478 | self.__cursor.execute(sql.format(where)) 479 | groupsdata = self.__cursor.fetchall() 480 | 481 | groups = [[{'name': g['child'], 'vars': self._loads_json(g['c_vars'])}, 482 | {'name': g['parent'], 'vars': self._loads_json(g['p_vars'])} if g['parent'] is not None else None] 483 | for g in groupsdata] 484 | pprint.pprint(self._construct_group_trees(groups)) 485 | 486 | @staticmethod 487 | def _construct_group_trees(groups): 488 | trees = dict() 489 | 490 | for child, parent in groups: 491 | if parent is not None: 492 | parent_k = parent['name'] 493 | if parent_k not in trees: 494 | trees[parent_k] = parent 495 | 496 | if 'children' not in trees[parent_k]: 497 | trees[parent_k]['children'] = list() 498 | trees[parent_k]['children'].append(child) 499 | else: 500 | child_k = child['name'] 501 | if child_k not in trees: 502 | trees[child_k] = child 503 | # pprint.pprint(trees) 504 | return trees 505 | 506 | # Find roots 507 | # children, parents = map(list, zip(*groups)) 508 | # pprint.pprint(trees.keys()) 509 | # pprint.pprint(children) 510 | # pprint.pprint(parents) 511 | # 512 | # roots = [children[k] for k, v in enumerate(parents) if v['name'] in trees.keys()] 513 | # pprint.pprint(roots) 514 | # 515 | # return {root['name']: trees[root['name']] for root in roots} 516 | 517 | def _connect(self): 518 | if not self.conn: 519 | self.conn = pymysql.connect(**self.myconfig) 520 | 521 | def _disconnect(self): 522 | if self.conn: 523 | self.conn.close() 524 | 525 | def _prompt(self, query): 526 | sys.stdout.write('''%s [y/n]: ''' % query) 527 | val = input() 528 | try: 529 | ret = strtobool(val) 530 | except ValueError: 531 | sys.stdout.write('Please answer with a y/n\n') 532 | return self._prompt(query) 533 | return ret 534 | 535 | @property 536 | def __cursor(self): 537 | if self.cursor is None: 538 | self.cursor = self.conn.cursor(pymysql.cursors.DictCursor) 539 | return self.cursor 540 | 541 | @staticmethod 542 | def _loads_json(json_str): 543 | ret = None 544 | if json_str is not None: 545 | try: 546 | ret = json.loads(json_str) 547 | except JSONDecodeError as e: 548 | pass 549 | return ret 550 | 551 | 552 | InventoryCtl() 553 | -------------------------------------------------------------------------------- /mysql.ini.dist: -------------------------------------------------------------------------------- 1 | # Ansible MySQL external inventory script settings 2 | # Copy it and rename to mysql.ini 3 | # 4 | 5 | # MySQL Server 6 | [server] 7 | host = YOURHOST 8 | user = YOURUSER 9 | passwd = YOURPASSWORD 10 | db = YOURDB 11 | port = 3306 12 | 13 | [config] 14 | 15 | # API calls to MySQL can be slow. For this reason, we can cache the results of an API 16 | # call. Set this to the path you want cache files to be written to. Two files 17 | # will be written to this directory: 18 | # - ansible-mysql.cache 19 | # - ansible-mysql.index 20 | cache_path = /tmp 21 | 22 | # The number of seconds a cache file is considered valid. After this many 23 | # seconds, a new API call will be made, and the cache file will be updated. 24 | cache_max_age = 0 25 | 26 | # Facts variable for the hostname 27 | facts_hostname_var = inventory_hostname 28 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | from codecs import open 3 | from os import path 4 | 5 | here = path.abspath(path.dirname(__file__)) 6 | 7 | # Get the long description from the README file 8 | with open(path.join(here, 'README'), encoding='utf-8') as f: 9 | long_description = f.read() 10 | 11 | setup( 12 | name='ansible-dynamic-inventory-mysql', 13 | packages=['ansible-dynamic-inventory-mysql'], 14 | version='0.1.1', 15 | python_requires='~=3.5', 16 | description='This is a Dynamic Inventory for Ansible to be used together with MySQL.', 17 | long_description=long_description, 18 | author='Askdaddy', 19 | author_email='askdaddy@gmail.com', 20 | url='https://github.com/askdaddy/ansible-dynamic-inventory-mysql', 21 | download_url='https://github.com/askdaddy/ansible-dynamic-inventory-mysql/archive/arya.zip', 22 | install_requires=[ 23 | 'configparser>=3.5.0', 24 | 'PyMySQL>=0.7.11' 25 | ], 26 | keywords=['ansible','inventory','mysql'] 27 | ) 28 | -------------------------------------------------------------------------------- /tables.sql: -------------------------------------------------------------------------------- 1 | -- Create syntax for TABLE 'group' 2 | CREATE TABLE `group` ( 3 | `id` int(11) NOT NULL AUTO_INCREMENT, 4 | `name` varchar(255) NOT NULL, 5 | `variables` longtext, 6 | `enabled` tinyint(1) NOT NULL, 7 | PRIMARY KEY (`id`), 8 | UNIQUE KEY `group_name` (`name`) 9 | ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 10 | 11 | -- Create syntax for TABLE 'childgroups' 12 | CREATE TABLE `childgroups` ( 13 | `id` int(11) NOT NULL AUTO_INCREMENT, 14 | `child_id` int(11) NOT NULL, 15 | `parent_id` int(11) NOT NULL, 16 | PRIMARY KEY (`id`), 17 | UNIQUE KEY `childid` (`child_id`,`parent_id`), 18 | KEY `childgroups_child_id` (`child_id`), 19 | KEY `childgroups_parent_id` (`parent_id`), 20 | CONSTRAINT `childgroups_ibfk_1` FOREIGN KEY (`child_id`) REFERENCES `group` (`id`), 21 | CONSTRAINT `childgroups_ibfk_2` FOREIGN KEY (`parent_id`) REFERENCES `group` (`id`) 22 | ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 23 | 24 | -- Create syntax for TABLE 'host' 25 | CREATE TABLE `host` ( 26 | `id` int(11) NOT NULL AUTO_INCREMENT, 27 | `host` varchar(255) NOT NULL, 28 | `hostname` varchar(255) NOT NULL, 29 | `variables` longtext, 30 | `enabled` tinyint(1) NOT NULL, 31 | PRIMARY KEY (`id`), 32 | UNIQUE KEY `host_host` (`host`), 33 | UNIQUE KEY `host_hostname` (`hostname`) 34 | ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 35 | 36 | -- Create syntax for TABLE 'hostgroups' 37 | CREATE TABLE `hostgroups` ( 38 | `id` int(11) NOT NULL AUTO_INCREMENT, 39 | `host_id` int(11) NOT NULL, 40 | `group_id` int(11) NOT NULL, 41 | PRIMARY KEY (`id`), 42 | UNIQUE KEY `host_id` (`host_id`,`group_id`), 43 | KEY `hostgroups_host_id` (`host_id`), 44 | KEY `hostgroups_group_id` (`group_id`), 45 | CONSTRAINT `hostgroups_ibfk_1` FOREIGN KEY (`host_id`) REFERENCES `host` (`id`), 46 | CONSTRAINT `hostgroups_ibfk_2` FOREIGN KEY (`group_id`) REFERENCES `group` (`id`) 47 | ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 48 | 49 | -- Create syntax for VIEW 'inventory' 50 | -- CREATE VIEW `inventory` 51 | -- AS SELECT 52 | -- `group`.`name` AS `group`, 53 | -- `host`.`host` AS `host`, 54 | -- `host`.`hostname` AS `hostname`, 55 | -- `host`.`variables` AS `host_vars` 56 | -- FROM (`group` left join (`host` left join `hostgroups` on((`host`.`id` = `hostgroups`.`host_id`))) on((`hostgroups`.`group_id` = `group`.`id`))) where ((`host`.`enabled` = 1) and (`group`.`enabled` = 1)) order by `host`.`hostname`; 57 | 58 | -- Create syntax for VIEW 'children' 59 | CREATE VIEW `children` 60 | AS SELECT 61 | `gparent`.`name` AS `parent`, 62 | `gchild`.`name` AS `child` 63 | FROM ((`childgroups` left join `group` `gparent` on((`childgroups`.`parent_id` = `gparent`.`id`))) left join `group` `gchild` on((`childgroups`.`child_id` = `gchild`.`id`))) order by `gparent`.`name`; 64 | -- CREATE VIEW `ungrouped` 65 | -- AS SELECT 66 | -- `host`.`host` AS `host`, 67 | -- `host`.`hostname` AS `hostname`, 68 | -- `host`.`variables` AS `host_vars` 69 | -- FROM 70 | -- (`host` 71 | -- LEFT JOIN `hostgroups` ON ((`host`.`id` = `hostgroups`.`host_id`))) 72 | -- WHERE 73 | -- ISNULL(`hostgroups`.`group_id`) 74 | -- ORDER BY `host`.`hostname` 75 | 76 | -- Create syntax for VIEW 'inventory' ,New inventory with ungrouped -- 77 | CREATE VIEW `inventory` 78 | AS (SELECT 79 | `group`.`name` AS `group`, 80 | `host`.`host` AS `host`, 81 | `host`.`hostname` AS `hostname`, 82 | `host`.`variables` AS `host_vars` 83 | FROM (`group` left join (`host` left join `hostgroups` ON ((`host`.`id` = `hostgroups`.`host_id`))) ON ((`hostgroups`.`group_id` = `group`.`id`))) 84 | WHERE `host`.`enabled` = 1 AND `group`.`enabled` = 1) 85 | UNION 86 | (SELECT 87 | 'ungrouped' AS `group`, 88 | `host`.`host` AS `host`, 89 | `host`.`hostname` AS `hostname`, 90 | `host`.`variables` AS `host_vars` 91 | FROM `host` LEFT JOIN `hostgroups` ON `host`.`id` = `hostgroups`.`host_id` 92 | WHERE `hostgroups`.`group_id` IS NULL); 93 | --------------------------------------------------------------------------------