Full Code of kubespray/kubespray-cli for AI

master e2a0670b8daf cached
14 files
112.3 KB
25.9k tokens
42 symbols
1 requests
Download .txt
Repository: kubespray/kubespray-cli
Branch: master
Commit: e2a0670b8daf
Files: 14
Total size: 112.3 KB

Directory structure:
gitextract_tsd1_jj_/

├── .gitignore
├── HISTORY.rst
├── LICENCE
├── README.md
├── bin/
│   └── kubespray
├── setup.cfg
├── setup.py
└── src/
    └── kubespray/
        ├── __init__.py
        ├── cloud.py
        ├── common.py
        ├── configure.py
        ├── deploy.py
        ├── files/
        │   └── .kubespray.yml
        └── inventory.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Created by .ignore support plugin (hsz.mobi)
### Example user template template
### Example user template

# IntelliJ project files
.idea
*.iml
out
gen


================================================
FILE: HISTORY.rst
================================================
=======
History
=======

0.1.0 (2016-3-20)
------------------

* First release on PyPI.


================================================
FILE: LICENCE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
Kubespray wrapper
=============

This tool helps to deploy a kubernetes cluster with ansible.


Example on GCE:
[![asciicast](https://asciinema.org/a/065mhh5pzmxcwxgp6evebarvd.png)](https://asciinema.org/a/065mhh5pzmxcwxgp6evebarvd?speed=4)

Requirements
============

-   **Ansible v2.3 (or newer)**
-   The current user must have its ssh **public key** installed on the
    remote servers.
-   The remote user (option --user) must be in the sudoers with no
    password

Installation
============

### Python pip

    sudo pip2 install kubespray


Config file
-----------

A config file can be updated (yaml). (default: *~/.kubespray.yml* ) </br>
This file contains default values for some parameters that don't change
frequently </br>
**Note** these values are **overwritten** by the command line.


    # Common options
    # ---------------
    # Path where the kubespray ansible playbooks will be installed
    # Defaults to current user's home directory if not set
    # kubespray_path: "/tmp"
    # Default inventory path
    kubespray_git_repo: "https://github.com/kubernetes-incubator/kubespray.git"
    # Logging options
    loglevel: "info"

    # Amazon web services options
    # ---
    # aws_access_key: "<key>"
    # aws_secret_key: "<secret_key>"
    # key_name: "<keypair_name>"
    # ami: "<aws_ami>"
    # masters_instance_type: "<masters_instance_type>"
    # nodes_instance_type: "<nodes_instance_type>"
    # etcds_instance_type: "<etcds_instance_type>"
    # masters_instance_profile_name: "<master_instance_profile_name>"
    # nodes_instance_profile_name: "<nodes_instance_profile_name>"
    # etcds_instance_profile_name: "<etcds_instance_profile_name>"
    # security_group_name: "<security_group_name>"
    # security_group_id: "<security_group_id>"
    # assign_public_ip: True
    # vpc_subnet_id: "<vpc_id>"
    # region: "<aws_region>"
    # tags:
    #   - type: k8s

    # OpenStack options
    # ---
    # os_auth_url: "https://"
    # os_username: "k8s"
    # os_password: "secret"
    # os_project_name: "k8s"
    # masters_flavor: "m1.small"
    # nodes_flavor: "m1.small"
    # etcds_flavor: "m1.small"
    # image: "wily-server-cloudimg-amd64"
    # network: "my-network"
    # sshkey: "my-pub-key"
    ...

Basic usage
-----------
**Note**: You may want to choose the architecture of your cluster. </br>
Here are 3 examples:
* 3 vms, all 3 have etcd installed, all 3 are nodes (running pods), 2 of them run master components
```
kubespray [prepare|aws|gce] --nodes 3
```

![3nodes](https://s32.postimg.org/8q7gns8ut/3nodes.png)
* 6 vms, 2 are nodes and masters, 1 is node only and a distinct etcd cluster
```
kubespray [prepare|aws|gce] --nodes 3 --etcds 3
```

![3nodes3etcds](https://s32.postimg.org/hphgxcjmt/3nodes_3etcds.png)
* 8 vms, 2 distinct masters, 3 nodes and 3 etcds
```
kubespray [prepare|aws|gce] --nodes 3 --etcds 3 --masters 2
```

![3nodes3etcds2masters](https://s31.postimg.org/h4gdu4qjv/3nodes_2masters_3etcds.png)

You should have at least 3 nodes but you can spawn only one instance for
tests purposes.

### Generate inventory for a baremetal cluster

If the servers are already available you can use the argument **prepare**
The command below will just clone the git repository and creates the
inventory.
The hostvars must be separated by a **comma without spaces**

    kubespray prepare --nodes node1[ansible_ssh_host=10.99.21.1] node2[ansible_ssh_host=10.99.21.2] node3[ansible_ssh_host=10.99.21.3] [--etcds N+] [--masters N+]

### Run instances and generate the inventory on Clouds


**AWS**

In order to create vms on AWS you can either edit the config file *~/.kubespray.yml* or set the options with the argument **aws**
if the config file is filled with the proper information you just need to run the following command

    kubespray aws --nodes 3 [--etcds N+] [masters N+] [--nodes-instance-type m4.large]

Another example which download kubespray's repo in a defined directory and set the cluster name

    kubespray aws --nodes 3 -p /tmp/mykubespray --cluster-name foobar


**GCE**

In order to create vms on GCE you can either edit the config file */etc/kubespray/kubespray.yml* or set the options with the argument **gce**
if the config file is filled with the proper information you just need to run the following command

    kubespray gce --nodes 3

Another example if you already have a kubespray repository in your home dir

    kubespray gce --nodes 3 --noclone --cluster-name foobar [--nodes-machine-type n1-standard-4]


**OpenStack**

In order to create vms on a OpenStack cluster you can either edit the config file *~/.kubespray.yml* or set the options with the argument **openstack**.
The options **network** and **sshkey** are required and need to be created before running kubespray, you can either create them using the OpenStack Dashboard or the OpenStack CLI clients. Running the ansible routines that kubespray will invoke requires to have installed the [openstack cli tools](http://docs.openstack.org/user-guide/common/cli_install_openstack_command_line_clients.html) and openstack [shade](http://docs.openstack.org/infra/shade/installation.html).


Create a network using the OpenStack Neutron client

    # create network
    $ neutron net-create k8s-network

    Created a new network:
    +-----------------+--------------------------------------+
    | Field           | Value                                |
    +-----------------+--------------------------------------+
    | admin_state_up  | True                                 |
    | id              | 18989cb2-d9fc-4abd-85e8-fe5b33df3541 |
    | mtu             | 0                                    |
    | name            | k8s-network                          |
    | router:external | False                                |
    | shared          | False                                |
    | status          | ACTIVE                               |
    | subnets         |                                      |
    | tenant_id       | 5de2cf232a674b05983b61fdc1ea67aa     |
    +-----------------+--------------------------------------+

    # create subnet
    $ neutron subnet-create --name k8s-subnet --dns-nameserver 8.8.8.8 --enable-dhcp --allocation_pool "start=192.168.0.100,end=192.168.0.200" k8s-network 192.168.0.0/24

    Created a new subnet:
    +-------------------+----------------------------------------------------+
    | Field             | Value                                              |
    +-------------------+----------------------------------------------------+
    | allocation_pools  | {"start": "192.168.0.100", "end": "192.168.0.200"} |
    | cidr              | 192.168.0.0/24                                     |
    | dns_nameservers   |                                                    |
    | enable_dhcp       | True                                               |
    | gateway_ip        | 192.168.0.1                                        |
    | host_routes       |                                                    |
    | id                | fc5a5436-de3a-4d68-9846-d977d047d6d7               |
    | ip_version        | 4                                                  |
    | ipv6_address_mode |                                                    |
    | ipv6_ra_mode      |                                                    |
    | name              | k8s-subnet                                         |
    | network_id        | 18989cb2-d9fc-4abd-85e8-fe5b33df3541               |
    | subnetpool_id     |                                                    |
    | tenant_id         | 5de2cf232a674b05983b61fdc1ea67aa                   |
    +-------------------+----------------------------------------------------+

    # create a router
    $ neutron router-create k8s-router

    Created a new router:
    +-----------------------+--------------------------------------+
    | Field                 | Value                                |
    +-----------------------+--------------------------------------+
    | admin_state_up        | True                                 |
    | external_gateway_info |                                      |
    | id                    | 69027fa4-239b-4bae-89bc-3040c365ee4d |
    | name                  | k8s-router                           |
    | routes                |                                      |
    | status                | ACTIVE                               |
    | tenant_id             | 5de2cf232a674b05983b61fdc1ea67aa     |
    +-----------------------+--------------------------------------+

    # set gateway network, external_network is the name of the external network defined by your OpenStack provider
    $ neutron router-gateway-set k8s-router external_network

    Set gateway for router k8s-router

    # add k8s-subnet to k8s-router, plug the virtual cable
    $ neutron router-interface-add k8s-router subnet=k8s-subnet

    Added interface a62ca3b4-3302-45b6-803e-f87a4f43b4b6 to router k8s-router.

Upload a ssh key in order to connect to the vms using the OpenStack Nova client


    # import SSH Public Key with name k8s-pub-key
    $ nova keypair-add --pub-key id_rsa.pub k8s-pub-key


Once the preparation have been completed you can enter the required options to the config file */etc/kubespray/kubespray.yml*:

    ...

    network: "k8s-network"
    sshkey: "k8s-pub-key"

    ...


If the config file is filled with the proper information you just need to run the following command

    kubespray openstack --masters 2 --nodes 2 --etcds 3

Another example if you already have a kubespray repository in your home dir

    kubespray openstack --masters 2 --nodes 2 --etcds 3 --noclone --cluster-name foobar


**Add a node to an existing cluster**
It's possible to add nodes to a running cluster, </br>
these newly added nodes will act as node only (no etcd, no master components)

Add a node

    kubespray [aws|gce] --add --nodes 1

Then deploy the cluster with the same options as the running cluster.


### Deploy cluster

The last step is to run the cluster deployment.

**Note**:
-   default network plugin : flannel (vxlan) default
-   default kubespray\_path : "/home/\<current\_user\>/kubespray"
-   inventory path : "\<kubespray\_path\>/inventory/inventory.cfg".
-   The option `--inventory` allows to use an existing inventory (file or dynamic)
-   On coreos (--coreos) the directory **/opt/bin** must be writable
- You can use all Ansible's variables with
`--ansible-opts '-e foo=bar -e titi=toto -vvv'` (the value must be enclosed by simple quotes)

some examples:

Deploy with the default options on baremetal

    kubespray deploy

Deploy on AWS using a specific kubespray directory and set the api password

    kubespray deploy --aws --passwd secret -p /tmp/mykubespray -n weave

Deploy a kubernetes cluster on CoreOS servers located on GCE

    kubespray deploy -u core -p /kubespray-dc1 --gce --coreos --cluster-name mykube --kube-network 10.42.0.0/16


================================================
FILE: bin/kubespray
================================================
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# This file is part of Kubespray.
#
#    Kubespray is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Foobar is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.

__version__ = '0.5.2'

import os
import argparse
import getpass
try:
    from ansible.utils.display import Display
except ImportError:
    raise ImportError('Cannot find Ansible: Please check your installation (required version 2)')
from kubespray.common import clone_kubespray_git_repo
from kubespray.configure import Config
from kubespray.inventory import CfgInventory
from kubespray.deploy import RunPlaybook
from kubespray.cloud import AWS, GCE, OpenStack
display = Display()


def prepare(options):
    clone_kubespray_git_repo(options)
    Cfg = CfgInventory(options, 'metal')
    Cfg.write_inventory(
        options['masters_list'],
        options['nodes_list'],
        options['etcds_list']
    )


def aws(options):
    clone_kubespray_git_repo(options)
    A = AWS(options)
    A.gen_ec2_playbook()
    A.create_instances()
    A.write_inventory()


def gce(options):
    clone_kubespray_git_repo(options)
    G = GCE(options)
    G.gen_gce_playbook()
    G.create_instances()
    G.write_inventory()


def openstack(options):
    clone_kubespray_git_repo(options)
    O = OpenStack(options)
    O.gen_openstack_playbook()
    O.create_instances()
    O.write_inventory()


def deploy(options):
    Run = RunPlaybook(options)
    Run.ssh_prepare()
    Run.deploy_kubernetes()

if __name__ == '__main__':
    # Main parser
    parser = argparse.ArgumentParser(
        prog='kubespray',
        description='%(prog)s Kubernetes cluster deployment tool',
        add_help=False
    )
    subparsers = parser.add_subparsers(help='commands')

    parser.add_argument(
        '-v', '--version', action='version',
        version='%(prog)s'+' %s' % __version__
    )
    # Options shared by the first step subparsers (prepare, gce, aws)
    firststep_parser = argparse.ArgumentParser(add_help=False)
    firststep_parser.add_argument(
        '--noclone', default=False, action='store_true', dest='noclone',
        help='Do not clone the git repo. Useful when the repo is already downloaded'
    )

    # Options shared by all subparsers
    parent_parser = argparse.ArgumentParser(add_help=False)
    parent_parser.add_argument(
        '-p', '--path', dest='kubespray_path',
        help='Where the Ansible playbooks are installed. Default: ~/.kubespray'
    )
    parent_parser.add_argument(
        '--config', dest='configfile',
        help="Config file path. Defaults to ~/.kubespray.yml"
    )
    parent_parser.add_argument(
        '-y', '--assumeyes', default=False, dest='assume_yes', action='store_true',
        help='When a yes/no prompt would be presented, assume that the user entered "yes"'
    )
    parent_parser.add_argument(
        '-i', '--inventory', dest='inventory_path',
        help='Inventory file path. Defaults to <path parameter>/inventory/inventory.cfg'
    )

    # prepare
    prepare_parser = subparsers.add_parser(
        'prepare', parents=[parent_parser, firststep_parser],
        help='generate inventory and create vms on cloud providers'
    )
    prepare_parser.add_argument('--add', dest='add_node', action='store_true',
        help="Add node to an existing cluster"
    )
    prepare_parser.add_argument(
        '--etcds', dest='etcds_list', metavar='N', nargs='+', default=[],
        help='Number of etcd, these instances will just act as etcd members'
    )
    prepare_parser.add_argument(
        '--masters', dest='masters_list', metavar='N', nargs='+', default=[],
        help='Number of masters, these instances will not run workloads, master components only'
    )
    prepare_parser.add_argument(
        '--nodes', dest='nodes_list', metavar='N', nargs='+',
        required=True, help='List of nodes'
    )
    prepare_parser.set_defaults(func=prepare)

    # aws
    aws_parser = subparsers.add_parser(
        'aws', parents=[parent_parser, firststep_parser],
        help='Create AWS instances and generate inventory'
    )
    aws_parser.add_argument(
        '--access-key', dest='aws_access_key', help='AWS access key'
    )
    aws_parser.add_argument(
        '--secret-key', dest='aws_secret_key', help='AWS secret key'
    )
    aws_parser.add_argument(
        '--masters-instance-type', dest='masters_instance_type',
        help='AWS instance type for Masters (default: t2.medium)'
    )
    aws_parser.add_argument(
        '--nodes-instance-type', dest='nodes_instance_type',
        help='AWS instance type for Nodes (default: t2.large)'
    )
    aws_parser.add_argument(
        '--etcds-instance-type', dest='etcds_instance_type',
        help='AWS instance type for Etcd members (default: t2.small)'
    )
    aws_parser.add_argument(
        '--keypair', dest='key_name', help='AWS key pair name'
    )
    aws_parser.add_argument('--region', dest='region', help='AWS region')
    sg_group = aws_parser.add_mutually_exclusive_group()
    sg_group.add_argument(
        '--security-group-name', dest='security_group_name',
        help='AWS security group Name'
    )
    sg_group.add_argument(
        '--security-group-id', dest='security_group_id',
        help='AWS security group ID. Uses the "default" security group if not specified.'
    )
    aws_parser.add_argument(
        '--assign-public-ip', default=None, dest='assign_public_ip', action='store_true',
         help='when provisioning within vpc, assign a public IP address'
    )
    aws_parser.add_argument(
        '--use-private-ip', default=None, dest='use_private_ip', action='store_true',
         help='If set to true, using the private ip for SSH connection'
    )
    aws_parser.add_argument('--vpc-id', dest='aws_vpc_id', help='EC2 VPC ID')
    aws_parser.add_argument(
        '--vpc-subnet', dest='vpc_subnet_id', help='EC2 VPC subnet ID'
    )
    aws_parser.add_argument('--ami', dest='ami', help='AWS AMI')
    aws_parser.add_argument(
        '--cluster-name', dest='cluster_name', help='Name of the cluster'
    )
    aws_parser.add_argument(
        '--tags', dest='tags', help='List of VM tags of the form \'name=value\'', nargs="+", metavar="NAME=VALUE"
    )
    aws_parser.add_argument('--add', dest='add_node', action='store_true',
        help="Add node to an existing cluster")
    aws_parser.add_argument(
        '--etcd', dest='etcds_count', type=int,
        help='Number of etcd, these instances will just act as etcd members'
    )
    aws_parser.add_argument(
        '--masters', dest='masters_count', type=int,
        help='Number of masters, these instances will not run workloads, master components only'
    )
    aws_parser.add_argument(
        '--nodes', dest='nodes_count', type=int,
        help='Number of nodes', required=True
    )
    aws_parser.set_defaults(func=aws)

    # gce
    gce_parser = subparsers.add_parser(
        'gce', parents=[parent_parser, firststep_parser],
        help='Create GCE machines and generate inventory'
    )
    gce_parser.add_argument(
        '--pem_file', dest='pem_file', help='GCE ssh pem file path'
    )
    gce_parser.add_argument(
        '--credentials_file', dest='credentials_file',
        help='GCE credentials json file path'
    )
    gce_parser.add_argument(
        '--zone', dest='zone', help='GCE zone'
    )
    gce_parser.add_argument(
        '--masters-machine-type', dest='masters_machine_type',
        help='GCE machine type for Masters (default: n1-standard-2)'
    )
    gce_parser.add_argument(
        '--nodes-machine-type', dest='nodes_machine_type',
        help='GCE machine type for Nodes (default: n1-standard-4)'
    )
    gce_parser.add_argument(
        '--etcds-machine-type', dest='etcds_machine_type',
        help='GCE machine type for Etcd members (default: n1-standard-1)'
    )
    gce_parser.add_argument('--image', dest='image', help='GCE image')
    gce_parser.add_argument(
        '--project', dest='project_id', help='GCE project ID'
    )
    gce_parser.add_argument(
        '--email', dest='service_account_email', help='GCE project ID'
    )
    gce_parser.add_argument(
        '--cluster-name', dest='cluster_name', help='Name of the cluster'
    )
    gce_parser.add_argument(
        '--tags', dest='tags', help='List of VM tags', nargs="+", metavar="TAG"
    )
    gce_parser.add_argument('--add', dest='add_node', action='store_true',
        help="Add node to an existing cluster")
    gce_parser.add_argument(
        '--etcd', dest='etcds_count', type=int,
        help='Number of etcd, these instances will just act as etcd members'
    )
    gce_parser.add_argument(
        '--masters', dest='masters_count', type=int,
        help='Number of masters, these instances will not run workloads, master components only'
    )
    gce_parser.add_argument(
        '--nodes', dest='nodes_count', type=int,
        help='Number of nodes', required=True
    )
    gce_parser.set_defaults(func=gce)

    # openstack
    openstack_parser = subparsers.add_parser(
        'openstack', parents=[parent_parser, firststep_parser],
        help='Create OpenStack instances and generate inventory'
    )
    openstack_parser.add_argument(
        '--os_auth_url', dest='os_auth_url', help='OpenStack authentication URL'
    )
    openstack_parser.add_argument(
        '--os_username', dest='os_username', help='OpenStack Username'
    )
    openstack_parser.add_argument(
        '--os_project_name', dest='os_project_name',
        help='OpenStack Project Name'
    )
    openstack_parser.add_argument(
        '--os_region_name', dest='os_region_name', help='OpenStack Region Name',
        required=False
    )
    openstack_parser.add_argument(
        '--os_password', dest='os_password', help='OpenStack Password'
    )
    openstack_parser.add_argument(
        '--etcd', dest='etcds_count', type=int,
        help='Number of etcd, these instances will just act as etcd members'
    )
    openstack_parser.add_argument(
        '--masters', dest='masters_count', type=int,
        help='Number of masters, these instances will not run workloads, master components only'
    )
    openstack_parser.add_argument(
        '--nodes', dest='nodes_count', type=int,
        help='Number of nodes', required=True
    )
    openstack_parser.add_argument(
        '--sshkey', dest='sshkey', help='Name of saved SSH Keypair'
    )
    openstack_parser.add_argument(
        '-N', '--kube-network', dest='kube_network', default='10.233.0.0/16',
        help="""Network to be used inside the cluster (/16),
             (must not overlap with any of your infrastructure networks and should be the same as in deploy).
             default: 10.233.0.0/16"""
    )
    openstack_parser.add_argument(
        '--add', dest='add_node', action='store_true', default=False,
        help='Add node to an existing cluster')
    openstack_parser.add_argument(
        '--network', dest='network', help='Neutron network name'
    )
    openstack_parser.add_argument(
        '--masters-flavor', dest='masters_flavor',
        help='OpenStack instance flavor for Masters'
    )
    openstack_parser.add_argument(
        '--nodes-flavor', dest='nodes_flavor',
        help='OpenStack instance flavor for Nodes'
    )
    openstack_parser.add_argument(
        '--etcds-flavor', dest='etcds_flavor',
        help='OpenStack instance flavor for Etcd members'
    )
    openstack_parser.add_argument('--image', dest='image', help='Instance boot image')
    openstack_parser.add_argument(
        '--floating_ip', dest='floating_ip', action='store_true',
        required=False, help='Associate public IP to instances'
    )
    openstack_parser.add_argument(
        '--cluster-name', dest='cluster_name', help='Name of the cluster'
    )
    openstack_parser.set_defaults(func=openstack)

    # deploy
    deploy_parser = subparsers.add_parser(
        'deploy', parents=[parent_parser],
        help='Create GCE machines and generate inventory'
    )
    deploy_parser.add_argument(
        '--verbose', default=False, action='store_true',
        help="Run Ansible playbook in verbose mode '-vvvv'"
    )
    deploy_parser.add_argument(
        '-k', '--sshkey', dest='ssh_key',
        help='ssh key for authentication on remote servers'
    )
    deploy_parser.add_argument(
        '-K', '--ask-become-pass', default=False, action='store_true', dest='ask_become_pass',
        help='ask for privilege escalation password'
    )
    deploy_parser.add_argument(
        '-u', '--user', dest='ansible_user', default=getpass.getuser(),
        help='Ansible SSH user (remote user)'
    )
    deploy_parser.add_argument(
        '--passwd', dest='k8s_passwd',
        help="Set the 'kube' passwd to authenticate to the API (default changeme')"
    )
    deploy_parser.add_argument(
        '-P', '--prompt-passwd', default=False, action='store_true', dest='prompt_pwd',
        help="Set the 'kube' passwd to authenticate to the API (Interactive mode)"
    )
    deploy_parser.add_argument(
        '-V', '--kube-version', dest='kube_version',
        help='Choose the kubernetes version to be installed'
    )
    deploy_parser.add_argument(
        '-N', '--kube-network', dest='kube_network',
        help="""Network to be used inside the cluster (/16),
             (must not overlap with any of your infrastructure networks).
             default: 10.233.0.0/16"""
    )
    deploy_parser.add_argument(
        '-n', '--network-plugin',
        choices=['flannel', 'weave', 'calico', 'canal', 'contiv', 'cloud'],
        help='Inventory defaults to calico'
    )
    deploy_parser.add_argument(
        '--apps', dest='apps_enabled', metavar='N', nargs='+', default=[],
        help='''List of optional applications to be installed,
             Possible values: helm, netchecker, efk'''
    )
    deploy_parser.add_argument(
        '--aws', default=False, action='store_true',
        help='Kubernetes deployment on AWS'
    )
    deploy_parser.add_argument(
        '--gce', default=False, action='store_true',
        help='Kubernetes deployment on GCE'
    )
    deploy_parser.add_argument(
        '--redhat', default=False, action='store_true',
        help='bootstrap python on RHEL 7 and newer'
    )
    deploy_parser.add_argument(
        '--coreos', default=False, action='store_true',
        help='bootstrap python on CoreOS'
    )
    deploy_parser.add_argument(
            '--ubuntu', default=False, action='store_true',
            help='bootstrap python on Ubuntu 16.04 and newer'
    )
    deploy_parser.add_argument(
        '--ansible-opts', dest='ansible_opts',
        help='Ansible options'
    )
    deploy_parser.set_defaults(func=deploy)

    # Parse arguments
    args = parser.parse_args()
    if args.configfile is None:
        default_config_dir = os.path.expanduser("~")
        if not os.path.isdir(default_config_dir):
            os.makedirs(default_config_dir)
        args.configfile = os.path.join(default_config_dir, ".kubespray.yml")
    # Read configfile and update options dict
    C = Config(args.configfile)
    configfile_content = C.parse_configfile
    config = C.default_values(args, configfile_content)
    # Run functions with all the options
    os.environ['ANSIBLE_FORCE_COLOR'] = 'true'
    args.func(config)


================================================
FILE: setup.cfg
================================================
[metadata]
description-file = README.md


================================================
FILE: setup.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from setuptools import setup, find_packages

requirements = [
    'cffi>=1.6.0',
    'setuptools>=11.3',
    'cryptography>=1.3.2',
    'requests>=2.4.3',
    'netaddr>=0.7.18',
    'markupsafe>=0.23',
    'pyasn1>=0.1.8',
    'boto>=2.40.0',
    'apache-libcloud>=0.20.1'
]

test_requirements = [
    # TODO: put package test requirements here
]

my_homedir = os.path.expanduser("~")

setup(
    name='kubespray',
    version='0.5.2',
    description="Kubespray kubernetes cluster deployment",
    author="Smaine Kahlouch",
    author_email='smainklh@gmail.com',
    url='https://github.com/kubespray/kubespray-cli',
    data_files=[
        (my_homedir, ['src/kubespray/files/.kubespray.yml'])
    ],
    packages=find_packages('src'),
    scripts=[
        'bin/kubespray'
    ],
    package_dir={'': 'src'},
    package_data={'kubespray': ['files/*.yml'], },
    install_requires=requirements,
    license="GPLv3",
    zip_safe=False,
    keywords='kubespray',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.7',
    ],
    test_suite='tests',
    tests_require=test_requirements
)


================================================
FILE: src/kubespray/__init__.py
================================================
# (c) 2016, Smaine Kahlouch <smainklh@gmail.com>
__author__ = 'smana'
__version__ = '0.5.2'


================================================
FILE: src/kubespray/cloud.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of Kubespray.
#
#    Kubespray is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Foobar is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.

"""
kubespray.cloud
~~~~~~~~~~~~

Run Instances on cloud providers and generate inventory
"""

import sys
import os
import yaml
import json
from kubespray.inventory import CfgInventory
from kubespray.common import get_logger, query_yes_no, run_command, which, id_generator, get_cluster_name
from ansible.utils.display import Display
display = Display()
playbook_exec = which('ansible-playbook')

try:
    import configparser
except ImportError:
    import ConfigParser as configparser


class Cloud(object):
    '''
    Run Instances on cloud providers and generates inventory
    '''
    def __init__(self, options, cloud):
        self.options = options
        self.cloud = cloud
        self.inventorycfg = options['inventory_path']
        self.playbook = os.path.join(options['kubespray_path'], 'local.yml')
        self.cparser = configparser.ConfigParser(allow_no_value=True)
        self.Cfg = CfgInventory(options, cloud)
        self.localcfg = os.path.join(
            options['kubespray_path'],
            'inventory/local.cfg'
        )
        self.instances = {'masters':
                          {'file': os.path.join(
                           options['kubespray_path'], 'masters_instances.json'),
                           'json': None
                           },
                          'nodes':
                          {'file': os.path.join(
                           options['kubespray_path'], 'nodes_instances.json'),
                           'json': None
                           },
                          'etcds':
                          {'file': os.path.join(
                           options['kubespray_path'], 'etcds_instances.json'),
                           'json': None
                           },
                          }
        self.logger = get_logger(
            options.get('logfile'),
            options.get('loglevel')
        )
        self.pbook_content = [{
            'gather_facts': False,
            'hosts': 'localhost',
            'become': False,
            'tasks': []
        }]
        self.logger.debug('''
             The following options were used to generate the inventory: %s
             ''' % self.options)

    def write_local_inventory(self):
        '''Generates inventory for local tasks'''
        self.cparser.add_section('local')
        self.cparser.set(
            'local',
            'localhost ansible_python_interpreter=python2 ansible_connection=local'
        )
        try:
            with open(self.localcfg, 'wb') as f:
                self.cparser.write(f)
        except IOError as e:
            display.error(
                'Cannot write inventory %s: %s'
                % (self.localcfg, e)
            )
            sys.exit(1)

    def write_playbook(self):
        '''Write the playbook for instances creation'''
        try:
            with open(self.playbook, "w") as pb:
                pb.write(yaml.dump(self.pbook_content, default_flow_style=True))
        except IOError as e:
            display.error(
                'Cant write the playbook %s: %s'
                % (self.playbook, e)
            )
            sys.exit(1)

    def write_inventory(self):
        '''Generate the inventory according the instances created'''
        for role in ['masters', 'nodes', 'etcds']:
            if '%s_count' % role in self.options.keys():
                with open(self.instances['%s' % role]['file']) as f:
                    self.instances['%s' % role]['json'] = json.load(f)
            else:
                self.instances['%s' % role]['json'] = []
        self.Cfg.write_inventory(self.instances['masters']['json'], self.instances['nodes']['json'], self.instances['etcds']['json'])

    def create_instances(self):
        '''Run ansible-playbook for instances creation'''
        cmd = [
            playbook_exec, '-i', self.localcfg, '-e',
            'ansible_connection=local', self.playbook
        ]
        if not self.options['assume_yes']:
            count = 0
            for role in ['masters', 'nodes', 'etcds']:
                if '%s_count' % role in self.options.keys():
                    count = count + self.options['%s_count' % role]
            if self.options['add_node']:
                display.warning(
                    '%s node(s) will be added to the current inventory %s' %
                    (count, self.inventorycfg)
                )
            if not query_yes_no('Create %s instances on %s ?' % (count, self.cloud)):
                display.display('Aborted', color='red')
                sys.exit(1)
        rcode, emsg = run_command('Create %s instances' % self.cloud, cmd)
        if rcode != 0:
            self.logger.critical('Cannot create instances: %s' % emsg)
            sys.exit(1)


class AWS(Cloud):

    def __init__(self, options):
        Cloud.__init__(self, options, "aws")
        self.options = options

    def gen_ec2_playbook(self):
        data = self.options
        data.pop('func')
        # Options list of ansible EC2 module
        self.options['image'] = self.options['ami']
        if 'security_group_id' in self.options.keys():
            self.options['group_id'] = self.options['security_group_id']
        if 'security_group_name' in self.options.keys():
            self.options['group'] = self.options['security_group_name']
        if 'tags' in self.options:
            self.options['instance_tags'] = {}
            for kv in self.options['tags']:
                k, v = kv.split("=")
                self.options['instance_tags'][k] = v
        ec2_options = [
            'aws_access_key', 'aws_secret_key', 'count', 'group_id',
            'group', 'instance_type', 'instance_profile_name', 'key_name', 'vpc_subnet_id',
            'image', 'instance_tags', 'assign_public_ip', 'region'
        ]
        # Define EC2 task
        for role in ['masters', 'nodes', 'etcds']:
            if '%s_count' % role in self.options.keys():
                ec2_task = {'ec2': {},
                            'name': 'Provision EC2 %s instances' % role,
                            'register': 'ec2_%s' % role}
                for opt in ec2_options:
                    if opt in self.options.keys():
                        d = {opt: self.options[opt]}
                        ec2_task['ec2'].update(d)
                ec2_task['ec2'].update({'count': self.options['%s_count' % role]})
                ec2_task['ec2'].update({'instance_type': self.options['%s_instance_type' % role]})
                ec2_task['ec2'].update({'instance_profile_name': self.options['%s_instance_profile_name' % role]})
                ec2_task['ec2'].update({'wait': True})
                self.pbook_content[0]['tasks'].append(ec2_task)
                # Write ec2 instances json
                self.pbook_content[0]['tasks'].append(
                    {'name': 'Generate a file with ec2 instances list',
                     'copy':
                         {'dest': '%s' % self.instances['%s' % role]['file'],
                          'content': '{{ec2_%s.instances}}' % role}}
                )
                # Wait for ssh task
                if self.options['use_private_ip']:
                    instance_ip = '{{ item.private_ip }}'
                else:
                    instance_ip = '{{ item.public_ip }}'
                self.pbook_content[0]['tasks'].append(
                    {'local_action': {'host': '%s' % instance_ip,
                                      'module': 'wait_for',
                                      'port': 22,
                                      'state': 'started',
                                      'timeout': 600},
                     'name': 'Wait until SSH is available',
                     'with_items': '{{ec2_%s.instances}}' % role}
                )
        self.write_local_inventory()
        self.write_playbook()


class GCE(Cloud):

    def __init__(self, options):
        Cloud.__init__(self, options, "gce")
        self.options = options

    def gen_gce_playbook(self):
        data = self.options
        data.pop('func')
        if 'tags' in self.options:
            self.options['tags'] = ','.join(self.options['tags'])
        # Options list of ansible GCE module
        gce_options = [
            'machine_type', 'image', 'zone', 'service_account_email',
            'pem_file', 'credentials_file', 'project_id', 'tags', 'network', 'subnetwork'
        ]
        # Define instance names
        cluster_name = 'k8s-' + get_cluster_name()
        for role in ['masters', 'nodes', 'etcds']:
            gce_instance_names = list()
            if '%s_count' % role in self.options.keys():
                for x in range(self.options['%s_count' % role]):
                    if self.options['add_node']:
                        current_inventory = self.Cfg.read_inventory()
                        cluster_name = '-'.join(
                            current_inventory['all']['hosts'][0]['hostname'].split('-')[:-2]
                        )
                        gce_instance_names.append(
                            cluster_name + '-%s' % id_generator()
                        )
                    elif 'cluster_name' in self.options.keys():
                        gce_instance_names.append(
                            self.options['cluster_name'] + '-%s' % id_generator()
                        )
                    else:
                        gce_instance_names.append(
                            cluster_name + '-%s' % id_generator()
                        )
                gce_instance_names = ','.join(gce_instance_names)
                # Define GCE task
                gce_task = {'gce': {},
                            'name': 'Provision GCE %s instances' % role,
                            'register': 'gce_%s' % role}
                for opt in gce_options:
                    if opt in self.options.keys():
                        d = {opt: self.options[opt]}
                        gce_task['gce'].update(d)
                gce_task['gce'].update({'machine_type': self.options['%s_machine_type' % role]})
                gce_task['gce'].update({'instance_names': '%s' % gce_instance_names})
                self.pbook_content[0]['tasks'].append(gce_task)
                # Write gce instances json
                self.pbook_content[0]['tasks'].append(
                    {'name': 'Generate a file with %s list' % role,
                     'copy':
                         {'dest': '%s' % self.instances['%s' % role]['file'],
                          'content': '{{gce_%s.instance_data}}' % role}}
                )
                # Wait for ssh task
                if self.options['use_private_ip']:
                    instance_ip = '{{ item.private_ip }}'
                else:
                    instance_ip = '{{ item.public_ip }}'

                self.pbook_content[0]['tasks'].append(
                    {'local_action': {'host': '%s' % instance_ip,
                                      'module': 'wait_for',
                                      'port': 22,
                                      'state': 'started',
                                      'timeout': 600},
                     'name': 'Wait until SSH is available',
                     'with_items': '{{gce_%s.instance_data}}' % role}
                )
        self.write_local_inventory()
        self.write_playbook()


class OpenStack(Cloud):
    def __init__(self, options):
        Cloud.__init__(self, options, 'openstack')
        self.options = options

    def gen_openstack_playbook(self):
        data = self.options
        data.pop('func')

        openstack_credential_args = ('auth_url', 'username', 'password', 'project_name')
        openstack_auth = {}

        for cred_arg in openstack_credential_args:
            openstack_auth.update({cred_arg: self.options['os_%s' % cred_arg]})

        if 'os_domain_name' in self.options:
            openstack_auth.update({'domain_name': self.options['os_domain_name']})

        if self.options['floating_ip']:
            ip_type = 'public'
        else:
            ip_type = 'private'

        # Define instance names
        cluster_name = 'k8s-' + get_cluster_name()
        if 'cluster_name' in self.options.keys():
            cluster_name = 'k8s-' + self.options['cluster_name']
        os_security_group_name = cluster_name + '-%s' % id_generator()

        self.pbook_content[0]['tasks'].append(
            {'name': 'Create security group',
               'os_security_group': {
                   'auth': openstack_auth,
                   'name': os_security_group_name,
                   'description': 'Contains security rules for the Kubernetes cluster',
                   'region_name': self.options['os_region_name'],
                   'state': 'present'}}
        )
        self.pbook_content[0]['tasks'].append(
            {'name': 'Add security rules',
               'os_security_group_rule': {
                   'auth': openstack_auth,
                   'security_group': os_security_group_name,
                   'protocol': '{{item}}',
                   'region_name': self.options['os_region_name'],
                   'state': 'present'},
               'with_items': ['tcp', 'udp', 'icmp']}
        )

        for role in ('masters', 'nodes', 'etcds'):
            os_instance_names = list()
            if '%s_count' % role in self.options.keys():
                for x in range(self.options['%s_count' % role]):
                    if self.options['add_node']:
                        current_inventory = self.Cfg.read_inventory()
                        cluster_name = '-'.join(
                            current_inventory['all']['hosts'][0]['hostname'].split('-')[:-1]
                        )
                        os_instance_names.append(
                            cluster_name + '-%s' % id_generator()
                        )
                    else:
                        os_instance_names.append(
                            cluster_name + '-%s' % id_generator()
                        )
                self.pbook_content[0]['tasks'].append(
                    {'name': 'Create %s network ports' % role,
                       'os_port': {
                           'auth': openstack_auth,
                           'name': '{{item}}',
                           'region_name': self.options['os_region_name'],
                           'network': self.options['network'],
                           'allowed_address_pairs': [{'ip_address': self.options['kube_network']}],
                           'security_groups': [os_security_group_name],
                           'state': 'present'},
                       'with_items': os_instance_names}
                )
                self.pbook_content[0]['tasks'].append(
                    {'name': 'Provision OS %s instances' % role,
                       'os_server': {
                           'auth': openstack_auth,
                           'name': '{{item}}',
                           'state': 'present',
                           'flavor': self.options['%s_flavor' % role],
                           'key_name': self.options['sshkey'],
                           'region_name': self.options['os_region_name'],
                           'auto_ip': self.options['floating_ip'],
                           'security_groups': [os_security_group_name],
                           'nics': 'port-name={{ item }}',
                           'image': self.options['image']},
                       'register': 'os_%s' % role,
                       'with_items': os_instance_names}
                )
                # Write os instances json
                self.pbook_content[0]['tasks'].append(
                    {'name': 'Generate a file with OS %s instances list' % role,
                     'copy':
                         {'dest': '%s' % self.instances[role]['file'],
                          'content': '{{os_%s.results}}' % role}}
                )
                # Wait for ssh task
                self.pbook_content[0]['tasks'].append(
                    {'name': 'Wait until SSH is available',
                       'wait_for': {
                           'host': '{{item.openstack.%s_v4}}' % ip_type,
                           'port': 22,
                           'search_regex': 'SSH',
                           'state': 'started',
                           'delay': 10},
                       'with_items': '{{os_%s.results}}' % role}
                )
        self.write_local_inventory()
        self.write_playbook()


================================================
FILE: src/kubespray/common.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of Kubespray.
#
#    Foobar is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Foobar is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.

import logging
import shutil
import requests
import random
import os
import re
import netaddr
import sys
import string
import getpass
from ansible.utils.display import Display
from subprocess import PIPE, STDOUT, Popen, CalledProcessError
display = Display()


def which(program):
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file
    return None


def read_password():
    pw = getpass.getpass(prompt="API 'kube' password: ")
    if len(pw) < 6:
        display.warning('Password is too short')
    pw2 = getpass.getpass(prompt="Confirm password: ")
    if pw != pw2:
        display.error("Passwords don't match")
        sys.exit(1)
    return(pw)


def query_yes_no(question, default="yes"):
    """Question user input 'Yes' or 'No'"""
    valid = {"yes": True, "y": True, "no": False, "n": False}
    if default is None:
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("Invalid default answer: '%s'" % default)
    while True:
        sys.stdout.write(question + prompt)
        choice = raw_input().lower()
        if default is not None and choice == '':
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write(
                "Please answer with 'yes' or 'no' (or 'y' or 'n').\n"
            )


def get_logger(logfile, loglevel):
    logger = logging.getLogger()
    handler = logging.FileHandler(logfile)
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(getattr(logging, loglevel.upper()))
    return logger


def get_cluster_name():
    try:
        word_site = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
        response = requests.get(word_site)
        words = response.content.splitlines()
        cluster_name = random.choice(words).decode("utf-8")
    except:
        cluster_name = id_generator()
    if not re.match('^(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?)$', cluster_name):
        get_cluster_name()
    return(cluster_name.lower())


def clone_kubespray_git_repo(options):
    if not options['add_node']:
        if (os.path.isdir(options['kubespray_path']) and not options['assume_yes']
                and not options['noclone']):
            display.warning(
                'A directory %s already exists' % options['kubespray_path']
            )
            if not query_yes_no(
                    'Are you sure to overwrite it ?'
            ):
                    display.display('Aborted', color='red')
                    sys.exit(1)
        if not options['noclone']:
            clone_git_repo(
                'kubespray', options['kubespray_path'], options['kubespray_git_repo']
            )


def clone_git_repo(name, directory, git_repo):
    if which('git') is None:
        display.error('Cannot find git binary! check your installation')
        sys.exit(1)
    if os.path.isdir(directory):
        shutil.rmtree(directory)
    display.banner('CLONING %s GIT REPO' % name.upper())
    cmd = ["git", "clone", git_repo, directory]
    rcode, emsg = run_command('Clone kubespray repository from github', cmd)
    if rcode != 0:
        display.error('Cannot clone kubespray repository from github')
        sys.exit(1)
    display.display('%s repo cloned' % name, color='green')


def run_command(description, cmd):
    '''
    Execute a system command
    '''
    try:
        proc = Popen(
            cmd, stdout=PIPE, stderr=STDOUT,
            universal_newlines=True, shell=False
        )
        with proc.stdout:
            for line in iter(proc.stdout.readline, b''):
                print(line),
        proc.wait()
        return(proc.returncode, None)
    except CalledProcessError as e:
        display.error('%s: %s' % (description, e.output))
        emsg = e.message
        return(proc.returncode, emsg)


def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))


def validate_cidr(cidr, version):
    """
    Validates that a CIDR is valid. Returns true if valid, false if
    not. Version can be "4", "6", None for "IPv4", "IPv6", or "either"
    respectively.
    """
    try:
        ip = netaddr.IPNetwork(cidr, version=version)
        return True
    except (netaddr.core.AddrFormatError, ValueError, TypeError):
        return False


================================================
FILE: src/kubespray/configure.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of Kubespray.
#
#    Kubespray is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Kubespray is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.

"""
kubespray.configure
~~~~~~~~~~~~

Configuration management for Kubespray
"""
import sys
import os
import yaml
from ansible.utils.display import Display
from kubespray.common import read_password


class Config(object):

    def __init__(self, configfile):
        self.display = Display()
        self.configfile = configfile
        self.logfile = None
        self.loglevel = None

    @property
    def parse_configfile(self):
        """
        Retrieve configuration parameters from the config file
        """
        try:
            with open(self.configfile, "r") as f:
                config = yaml.load(f)
        except:
            self.display.error(
                "Can't read configuration file %s" % self.configfile
            )
            sys.exit(1)
        return config

    def default_values(self, args, config):
        # Set kubespray_path
        if 'kubespray_path' not in config.keys() and args.kubespray_path is None:
            config['kubespray_path'] = os.path.join(os.path.expanduser("~"), '.kubespray')
        arguments = dict(args._get_kwargs())
        for key, value in arguments.items():
            if value is not None:
                config[key] = value
        # Set inventory_path
        if 'inventory_path' not in config.keys() and args.inventory_path is None:
            config['inventory_path'] = os.path.join(
                config['kubespray_path'], 'inventory/inventory.cfg'
            )
        # Set logfile
        if 'logfile' not in config.keys():
            config['logfile'] = os.path.join(config['kubespray_path'], 'kubespray.log')
        # Set default bool
        for v in ['use_private_ip', 'assign_public_ip']:
            if v not in config.keys():
                config[v] = False
        # Set default instances type
        if args.func.__name__ == "aws":
            if 'masters_instance_type' not in config.keys() and args.masters_instance_type is None:
                config['masters_instance_type'] = 't2.medium'
            if 'nodes_instance_type' not in config.keys() and args.nodes_instance_type is None:
                config['nodes_instance_type'] = 't2.large'
            if 'etcds_instance_type' not in config.keys() and args.etcds_instance_type is None:
                config['etcds_instance_type'] = 't2.small'
        # ----GCE
        if args.func.__name__ == "gce":
            if 'masters_machine_type' not in config.keys() and args.masters_machine_type is None:
                config['masters_machine_type'] = 'n1-standard-2'
            if 'nodes_machine_type' not in config.keys() and args.nodes_machine_type is None:
                config['nodes_machine_type'] = 'n1-standard-4'
            if 'etcds_machine_type' not in config.keys() and args.etcds_machine_type is None:
                config['etcds_machine_type'] = 'n1-standard-1'
        # Conflicting options
        if args.func.__name__ == "aws":
            if args.security_group_name and 'security_group_id' in config.keys():
                config.pop('security_group_id')
            elif args.security_group_id and 'security_group_name' in config.keys():
                config.pop('security_group_name')
        # Set kubernetes 'kube' password
        if 'prompt_pwd' in config.keys() and config['prompt_pwd'] is True:
            pwd = read_password()
            config['k8s_passwd'] = pwd
        return(config)


================================================
FILE: src/kubespray/deploy.py
================================================
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# This file is part of Kubespray.
#
#    Foobar is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Foobar is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.

"""
kubespray.deploy
~~~~~~~~~~~~

Deploy a kubernetes cluster. Run the ansible-playbbook
"""

import re
import sys
import os
import yaml
import signal
import netaddr
from subprocess import PIPE, STDOUT, Popen, check_output, CalledProcessError
from kubespray.common import get_logger, query_yes_no, run_command, which, validate_cidr
from ansible.utils.display import Display
display = Display()
playbook_exec = which('ansible-playbook')
ansible_exec = which('ansible')


class RunPlaybook(object):
    '''
    Run the Ansible playbook to deploy the kubernetes cluster
    '''
    def __init__(self, options):
        self.existing_ssh_agent = False
        self.options = options
        self.inventorycfg = options['inventory_path']
        self.logger = get_logger(
            options.get('logfile'),
            options.get('loglevel')
        )
        self.logger.debug(
            'Running ansible-playbook command with the following options: %s'
            % self.options
        )

    def kill_ssh_agent(self):
        if self.existing_ssh_agent:
            return

        if 'SSH_AGENT_PID' in os.environ:
            agent_pid = os.environ.get('SSH_AGENT_PID')

            if agent_pid.isdigit():
                os.kill(int(agent_pid), signal.SIGTERM)

    def ssh_prepare(self):
        '''
        Run ssh-agent and store identities
        '''

        if 'SSH_AUTH_SOCK' in os.environ:
            self.existing_ssh_agent = True
            self.logger.info('Using existing ssh agent')
            return

        try:
            sshagent = check_output('ssh-agent')
        except CalledProcessError as e:
            display.error('Cannot run the ssh-agent : %s' % e.output)
        # Set environment variables
        ssh_envars = re.findall('\w*=[\w*-\/.*]*', sshagent)
        for v in ssh_envars:
            os.environ[v.split('=')[0]] = v.split('=')[1]
        # Store ssh identity
        try:
            if 'ssh_key' in self.options.keys():
                cmd = ['ssh-add', os.path.realpath(self.options['ssh_key'])]
            else:
                cmd = 'ssh-add'
            proc = Popen(
                cmd, stdout=PIPE, stderr=STDOUT, stdin=PIPE
            )
            proc.stdin.write('password\n')
            proc.stdin.flush()
            response_stdout, response_stderr = proc.communicate()
            display.display(response_stdout)
        except CalledProcessError as e:
            display.error('Failed to store ssh identity : %s' % e.output)
            sys.exit(1)
        except IOError:
            display.error('Could not find SSH key. Have you run ssh-keygen?')
        try:
            check_output(['ssh-add', '-l'])
        except CalledProcessError as e:
            display.error('Failed to list identities : %s' % e.output)
            sys.exit(1)
        if response_stderr:
            display.error(response_stderr)
            self.logger.critical(
                'Deployment stopped because of ssh credentials'
                % self.filename
            )
            self.kill_ssh_agent()
            sys.exit(1)

    def check_ping(self):
        '''
         Check if hosts are reachable
        '''
        display.banner('CHECKING SSH CONNECTIONS')
        cmd = [
            ansible_exec, '--ssh-extra-args', '-o StrictHostKeyChecking=no',
            '-u', '%s' % self.options['ansible_user'],
            '-b', '--become-user=root', '-m', 'ping', 'all',
            '-i', self.inventorycfg
        ]
        if 'sshkey' in self.options.keys():
            cmd = cmd + ['--private-key', self.options['sshkey']]
        if self.options['ask_become_pass']:
            cmd = cmd + ['--ask-become-pass']
        if self.options['coreos']:
            cmd = cmd + ['-e', 'ansible_python_interpreter=/opt/bin/python']
        display.display(' '.join(cmd))
        rcode, emsg = run_command('SSH ping hosts', cmd)
        if rcode != 0:
            self.logger.critical('Cannot connect to hosts: %s' % emsg)
            self.kill_ssh_agent()
            sys.exit(1)
        display.display('All hosts are reachable', color='green')

    def get_subnets(self):
        '''Check the subnet value and split into 2 distincts subnets'''
        svc_pfx = 17
        pods_pfx = 17
        net = netaddr.IPNetwork(self.options['kube_network'])
        pfx_error_msg = (
            "You have to choose a network with a prefix length = 16, "
            "Please use Ansible options if you need to configure a different netmask."
        )
        if net.prefixlen is not 16:
            display.error(pfx_error_msg)
            self.kill_ssh_agent()
            sys.exit(1)
        subnets = list(net.subnet(pods_pfx))
        pods_network, remaining = subnets[0:2]
        net = netaddr.IPNetwork(remaining)
        svc_network = list(net.subnet(svc_pfx))[0]
        return(svc_network, pods_network)

    def read_kube_versions(self):
        """
        Read the kubernetes versions from karo's vars file
        """
        kube_vers_file = os.path.join(
            self.options['kubespray_path'] + '/roles/download/vars/kube_versions.yml'
        )
        try:
            with open(kube_vers_file, "r") as f:
                kube_versions_vars = yaml.load(f)
        except IOError as e:
            display.error('Cannot read kube_versions file %s: %s'
                          % (kube_vers_file, e)
                          )
            sys.exit(1)
        kube_versions = list()
        for i in kube_versions_vars['kube_checksum']:
            kube_versions.append(i)
        return kube_versions

    def deploy_kubernetes(self):
        '''
        Run the ansible playbook command
        '''
        cmd = [
            playbook_exec, '--ssh-extra-args', '-o StrictHostKeyChecking=no',
            '-u',  '%s' % self.options['ansible_user'],
            '-b', '--become-user=root', '-i', self.inventorycfg,
            os.path.join(self.options['kubespray_path'], 'cluster.yml')
        ]
        # Configure network plugin if defined
        if 'network_plugin' in self.options.keys():
            cmd = cmd + ['-e',
                'kube_network_plugin=%s' % self.options['network_plugin']
                ]
        # Configure the network subnets pods and k8s services
        if 'kube_network' in self.options.keys():
            if not validate_cidr(self.options['kube_network'], version=4):
                display.error('Invalid Kubernetes network address')
                self.kill_ssh_agent()
                sys.exit(1)
            svc_network, pods_network = self.get_subnets()
            cmd = cmd + [
                '-e', 'kube_service_addresses=%s' % svc_network.cidr,
                '-e', 'kube_pods_subnet=%s' % pods_network
            ]
        # Check optional apps
        if 'apps_enabled' in self.options.keys():
            for app in self.options['apps_enabled']:
                if app not in ['helm', 'netchecker', 'efk']:
                    display.error(
                        'The application %s is not available, possible values = %s' %
                        (app, ','.join(self.options['apps_enabled']))
                    )
                    sys.exit(1)
                if app == "netchecker":
                    cmd = cmd + ['-e', 'deploy_netchecker=true']
                else:
                    cmd = cmd + ['-e', '%s_enabled=true' % app]
        # Set kubernetes version
        if 'kube_version' in self.options.keys():
            available_kube_versions = self.read_kube_versions()
            if self.options['kube_version'] not in available_kube_versions:
                display.error(
                    'Kubernetes version %s is not supported, available versions = %s' %
                    (self.options['kube_version'], ','.join(available_kube_versions))
                )
                sys.exit(1)
            cmd = cmd + ['-e', 'kube_version=%s' % self.options['kube_version']]
        # Bootstrap
        if 'coreos' in self.options.keys() and self.options['coreos']:
            cmd = cmd + ['-e', 'bootstrap_os=coreos']
        elif 'redhat' in self.options.keys() and self.options['redhat']:
            cmd = cmd + [
                '-e', 'bootstrap_os=centos', '-e', 'ansible_os_family=RedHat'
            ]
        elif 'ubuntu' in self.options.keys() and self.options['ubuntu']:
            cmd = cmd + ['-e', 'bootstrap_os=ubuntu']
        # Add root password for the apiserver
        if 'k8s_passwd' in self.options.keys():
            cmd = cmd + ['-e', 'kube_api_pwd=%s' % self.options['k8s_passwd']]
        # Ansible verbose mode
        if 'verbose' in self.options.keys() and self.options['verbose']:
            cmd = cmd + ['-vvvv']
        # Add privilege escalation password
        if self.options['ask_become_pass']:
            cmd = cmd + ['--ask-become-pass']
        # Add any additionnal Ansible option
        if 'ansible_opts' in self.options.keys():
            cmd = cmd + self.options['ansible_opts'].split(' ')
        for cloud in ['aws', 'gce']:
            if self.options[cloud]:
                cmd = cmd + ['-e', 'cloud_provider=%s' % cloud]
        self.check_ping()
        if 'kube_network' in self.options.keys():
            display.display(
                'Kubernetes services network : %s (%s IPs)'
                % (svc_network.cidr, str(svc_network.size.real - 2)),
                color='bright gray'
            )
            display.display(
                'Pods network : %s (%s IPs)'
                % (pods_network.cidr, str(pods_network.size.real - 2)),
                color='bright gray'
            )
        display.display(' '.join(cmd), color='bright blue')
        if not self.options['assume_yes']:
            if not query_yes_no(
                'Run kubernetes cluster deployment with the above command ?'
            ):
                display.display('Aborted', color='red')
                sys.exit(1)
        display.banner('RUN PLAYBOOK')
        self.logger.info(
            'Running kubernetes deployment with the command: %s' % ' '.join(cmd)
        )
        rcode, emsg = run_command('Run deployment', cmd)
        if rcode != 0:
            self.logger.critical('Deployment failed: %s' % emsg)
            self.kill_ssh_agent()
            sys.exit(1)
        display.display('Kubernetes deployed successfuly', color='green')
        self.kill_ssh_agent()


================================================
FILE: src/kubespray/files/.kubespray.yml
================================================
---
# Path where the kubespray ansible playbooks will be installed
# Defaults to current user's home directory if not set
# kubespray_path: "~/.kubespray"

# Default inventory path
kubespray_git_repo: "https://github.com/kubespray/kubespray.git"

# Logging options
loglevel: "info"

# The following options would be overwritten by the command line
# ---------------------------------------------------------
#
# Amazon web services options
# ---
# aws_access_key: "<key>"
# aws_secret_key: "<secret_key>"
# key_name: "<keypair_name>"
# ami: "<aws_ami>"
# masters_instance_type: "<masters_instance_type>"
# nodes_instance_type: "<nodes_instance_type>"
# etcds_instance_type: "<etcds_instance_type>"
# security_group_name: "<security_group_name>"
# security_group_id: "<security_group_id>"
# assign_public_ip: True
# use_private_ip: true
# vpc_subnet_id: "<vpc_id>"
# region: "<aws_region>"
# tags:
#   - type: k8s
#
# Google Compute Engine options
# ---
# image: "<cloud_image>"
# masters_machine_type: "<masters_type>
# nodes_machine_type: "<masters_type>
# etcds_machine_type: "<masters_type>
# service_account_email: "<gce_service_account_email>"
# pem_file: "<gce_pem_file>"
# project_id: "<gce_project_id>"
# network: "<gce_network_name>"
# subnetwork: "<gce_subnetwork_name>"
# use_private_ip: true
# zone: "<cloud_region>"
# tags:
#   - k8s
#
# OpenStack options
# ---
# os_auth_url: "<os_auth_url>"
# os_username: "<os_username>"
# os_password: "<os_password>"
# os_project_name: "<os_project_name>"
# os_region_name: "<os_region_name>"
# os_domain_name: "<os_domain_name>"
# masters_flavor: "<os_flavor_name_or_id>"
# nodes_flavor: "<os_flavor_name_or_id>"
# etcds_flavor: "<os_flavor_name_or_id>"
# image: "<os_image_name_or_id>"
# network: "<os_network_name_or_id>"
# sshkey: "<os_ssh_key_name>"
#
# All the options to be passed to the 'ansible-playbook' command line
# Note: 'serial=1' ansible option is a workaround for bug https://github.com/ansible/ansible/issues/17935 which causes installation to hang due to SSH multiplexing
# ansible-opts:
#   - 'serial=1'
#   - '-vvv'
#   - '-e'
#   - 'myvar1=bar'
#   - '-e'
#   - 'myvar2=foo'


================================================
FILE: src/kubespray/inventory.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of Kubespray.
#
#    Kubespray is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Foobar is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.

"""
kubespray.inventory
~~~~~~~~~~~~

Ansible inventory management for Kubespray
"""

import sys
import re
from kubespray.common import get_logger, id_generator, get_cluster_name
from ansible.utils.display import Display
display = Display()

try:
    import configparser
except ImportError:
    import ConfigParser as configparser


class CfgInventory(object):
    '''
    Read classic ansible inventory file.
    '''

    def __init__(self, options, platform):
        self.options = options
        self.platform = platform
        self.inventorycfg = options['inventory_path']
        self.logger = get_logger(options.get('logfile'), options.get('loglevel'))
        self.cparser = configparser.ConfigParser(allow_no_value=True)
        self.inventory = {'all': {'hosts': []},
                          'kube-master': {'hosts': []},
                          'etcd': {'hosts': []},
                          'kube-node': {'hosts': []},
                          'k8s-cluster:children': {'hosts': [
                              {'hostname': 'kube-node', 'hostvars': []},
                              {'hostname': 'kube-master', 'hostvars': []}
                          ]},
                          }

    def read_inventory(self):
        read_cparser = configparser.ConfigParser(allow_no_value=True)
        try:
            read_cparser.read(self.inventorycfg)
        except IOError as e:
            display.error('Cannot read configuration %s: %s'
                          % (self.options['inventory_path'], e)
                          )
            sys.exit(1)
        expected_sections = ['kube-node', 'kube-master', 'all', 'etcd', 'k8s-cluster:children']
        for k in expected_sections:
            if k not in read_cparser.sections():
                display.error(
                    'The config file %s doesn\'t have a section named %s'
                    % (self.options['inventory_path'], k)
                )
                sys.exit(1)
        current_inventory = {'all': {'hosts': []},
                             'kube-master': {'hosts': []},
                             'etcd': {'hosts': []},
                             'kube-node': {'hosts': []},
                             'k8s-cluster:children': {'hosts': [
                                 {'hostname': 'kube-node', 'hostvars': []},
                                 {'hostname': 'kube-master', 'hostvars': []}
                             ]},
                             }
        for section in current_inventory.keys():
            for line, properties_str in read_cparser.items(section):
                machine_part = line.split('#', 1)[0]  # get rid of comments parts
                machine_part = line.split(None, 1)
                inventory_hostname = machine_part[0]
                host_dict = {'hostname': '', 'hostvars': []}
                hostvars = []
                if len(machine_part) == 2:
                    if properties_str:
                        properties_str = machine_part[1] + '=' + properties_str
                    else:
                        properties_str = machine_part[1]
                    for hostvar in properties_str.split():
                        name, value = hostvar.split('=')
                        d = {'name': name, 'value': value}
                        hostvars.append(d)
                host_dict['hostname'] = inventory_hostname
                host_dict['hostvars'] = hostvars
                current_inventory[section]['hosts'].append(host_dict)
        return(current_inventory)

    def format_inventory(self, masters, nodes, etcds):
        new_inventory = {'all': {'hosts': []},
                         'kube-master': {'hosts': []},
                         'etcd': {'hosts': []},
                         'kube-node': {'hosts': []},
                         'k8s-cluster:children': {'hosts': [
                             {'hostname': 'kube-node', 'hostvars': []},
                             {'hostname': 'kube-master', 'hostvars': []}
                             ]},
                         }

        if self.platform == 'openstack':
            if self.options['floating_ip']:
                ip_type = 'public_v4'
            else:
                ip_type = 'private_v4'
            # handle masters
            new_instances = []
            for master in masters:
                new_instances.append({'public_ip': master['openstack'][ip_type],
                                      'name': master['item']})
            masters = new_instances
            # handle nodes
            new_instances = []
            for node in nodes:
                new_instances.append({'public_ip': node['openstack'][ip_type],
                                      'name': node['item']})
            nodes = new_instances
            # handle etcds
            new_instances = []
            for etcd in etcds:
                new_instances.append({'public_ip': etcd['openstack'][ip_type],
                                      'name': etcd['item']})
            etcds = new_instances

        if not self.options['add_node']:
            if not masters and len(nodes) == 1:
                masters = [nodes[0]]
            elif not masters:
                masters = nodes[0:2]
            if not etcds and len(nodes) >= 3:
                etcds = nodes[0:3]
            elif not etcds and len(nodes) < 3:
                etcds = [nodes[0]]
            elif etcds and len(etcds) < 3:
                etcds = [etcds[0]]

        if self.platform in ['aws', 'gce', 'openstack']:
            if self.options['add_node']:
                current_inventory = self.read_inventory()
                cluster_name = '-'.join(
                    current_inventory['all']['hosts'][0]['hostname'].split('-')[:-1]
                )
                new_inventory = current_inventory
            else:
                cluster_name = 'k8s-' + get_cluster_name()
            if self.options['use_private_ip']:
                instance_ip = 'private_ip'
            else:
                instance_ip = 'public_ip'
            for host in nodes + masters + etcds:
                if self.platform == 'aws':
                    host['name'] = "%s-%s" % (cluster_name, id_generator(5))
                new_inventory['all']['hosts'].append(
                    {'hostname': '%s' % host['name'], 'hostvars': [
                        {'name': 'ansible_ssh_host', 'value': host[instance_ip]}
                        ]}
                )
            if not self.options['add_node']:
                for host in nodes:
                    new_inventory['kube-node']['hosts'].append(
                        {'hostname': '%s' % host['name'],
                         'hostvars': []}
                    )
                for host in masters:
                    new_inventory['kube-master']['hosts'].append(
                        {'hostname': '%s' % host['name'],
                         'hostvars': []}
                    )
                for host in etcds:
                    new_inventory['etcd']['hosts'].append(
                        {'hostname': '%s' % host['name'],
                         'hostvars': []}
                    )
        elif self.platform == 'metal':
            for host in nodes + masters + etcds:
                if '[' in host:
                    r = re.search('(^.*)\[(.*)\]', host)
                    inventory_hostname = r.group(1)
                    var_str = r.group(2)
                    hostvars = list()
                    for var in var_str.split(','):
                        hostvars.append({'name': var.split('=')[0], 'value': var.split('=')[1]})
                else:
                    inventory_hostname = host
                    hostvars = []
                new_inventory['all']['hosts'].append(
                    {'hostname': inventory_hostname, 'hostvars': hostvars}
                )
            for host in nodes:
                new_inventory['kube-node']['hosts'].append(
                    {'hostname': host.split('[')[0], 'hostvars': []}
                )
            for host in masters:
                new_inventory['kube-master']['hosts'].append(
                    {'hostname': host.split('[')[0], 'hostvars': []}
                )
            for host in etcds:
                new_inventory['etcd']['hosts'].append(
                    {'hostname': host.split('[')[0], 'hostvars': []}
                )
        return(new_inventory)

    def write_inventory(self, masters, nodes, etcds):
        '''Generates inventory'''
        inventory = self.format_inventory(masters, nodes, etcds)
        if not self.options['add_node']:
            if (('masters_count' in self.options.keys() and len(masters) < 2) or
               ('masters_count' not in self.options.keys() and len(nodes) < 2)):
                display.warning('You should set at least 2 masters')
            if (('etcds_count' in self.options.keys() and len(etcds) < 3) or
               ('etcds_count' not in self.options.keys() and len(nodes) < 3)):
                display.warning('You should set at least 3 nodes for etcd clustering')
        open(self.inventorycfg, 'w').close()
        for key, value in inventory.items():
            self.cparser.add_section(key)
            for host in value['hosts']:
                hostvars = str()
                varlist = list()
                for var in host['hostvars']:
                    varlist.append("%s=%s" % (var['name'], var['value']))
                hostvars = " ".join(varlist)
                self.cparser.set(key, "%s\t\t%s" % (host['hostname'], hostvars))
        with open(self.inventorycfg, 'wb') as configfile:
            display.banner('WRITTING INVENTORY')
            self.cparser.write(configfile)
            self.logger.info(
                'the inventory %s was successfuly generated'
                % self.inventorycfg
            )
            self.logger.debug(
                'The following options were used to generate the inventory: %s'
                % self.options
            )
            display.display(
                'Inventory generated : %s'
                % self.inventorycfg, color='green'
            )
Download .txt
gitextract_tsd1_jj_/

├── .gitignore
├── HISTORY.rst
├── LICENCE
├── README.md
├── bin/
│   └── kubespray
├── setup.cfg
├── setup.py
└── src/
    └── kubespray/
        ├── __init__.py
        ├── cloud.py
        ├── common.py
        ├── configure.py
        ├── deploy.py
        ├── files/
        │   └── .kubespray.yml
        └── inventory.py
Download .txt
SYMBOL INDEX (42 symbols across 5 files)

FILE: src/kubespray/cloud.py
  class Cloud (line 42) | class Cloud(object):
    method __init__ (line 46) | def __init__(self, options, cloud):
    method write_local_inventory (line 87) | def write_local_inventory(self):
    method write_playbook (line 104) | def write_playbook(self):
    method write_inventory (line 116) | def write_inventory(self):
    method create_instances (line 126) | def create_instances(self):
  class AWS (line 151) | class AWS(Cloud):
    method __init__ (line 153) | def __init__(self, options):
    method gen_ec2_playbook (line 157) | def gen_ec2_playbook(self):
  class GCE (line 216) | class GCE(Cloud):
    method __init__ (line 218) | def __init__(self, options):
    method gen_gce_playbook (line 222) | def gen_gce_playbook(self):
  class OpenStack (line 292) | class OpenStack(Cloud):
    method __init__ (line 293) | def __init__(self, options):
    method gen_openstack_playbook (line 297) | def gen_openstack_playbook(self):

FILE: src/kubespray/common.py
  function which (line 34) | def which(program):
  function read_password (line 50) | def read_password():
  function query_yes_no (line 61) | def query_yes_no(question, default="yes"):
  function get_logger (line 85) | def get_logger(logfile, loglevel):
  function get_cluster_name (line 95) | def get_cluster_name():
  function clone_kubespray_git_repo (line 108) | def clone_kubespray_git_repo(options):
  function clone_git_repo (line 126) | def clone_git_repo(name, directory, git_repo):
  function run_command (line 141) | def run_command(description, cmd):
  function id_generator (line 161) | def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
  function validate_cidr (line 165) | def validate_cidr(cidr, version):

FILE: src/kubespray/configure.py
  class Config (line 32) | class Config(object):
    method __init__ (line 34) | def __init__(self, configfile):
    method parse_configfile (line 41) | def parse_configfile(self):
    method default_values (line 55) | def default_values(self, args, config):

FILE: src/kubespray/deploy.py
  class RunPlaybook (line 40) | class RunPlaybook(object):
    method __init__ (line 44) | def __init__(self, options):
    method kill_ssh_agent (line 57) | def kill_ssh_agent(self):
    method ssh_prepare (line 67) | def ssh_prepare(self):
    method check_ping (line 117) | def check_ping(self):
    method get_subnets (line 142) | def get_subnets(self):
    method read_kube_versions (line 161) | def read_kube_versions(self):
    method deploy_kubernetes (line 181) | def deploy_kubernetes(self):

FILE: src/kubespray/inventory.py
  class CfgInventory (line 38) | class CfgInventory(object):
    method __init__ (line 43) | def __init__(self, options, platform):
    method read_inventory (line 59) | def read_inventory(self):
    method format_inventory (line 106) | def format_inventory(self, masters, nodes, etcds):
    method write_inventory (line 219) | def write_inventory(self, masters, nodes, etcds):
Condensed preview — 14 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (119K chars).
[
  {
    "path": ".gitignore",
    "chars": 154,
    "preview": "# Created by .ignore support plugin (hsz.mobi)\n### Example user template template\n### Example user template\n\n# IntelliJ "
  },
  {
    "path": "HISTORY.rst",
    "chars": 88,
    "preview": "=======\nHistory\n=======\n\n0.1.0 (2016-3-20)\n------------------\n\n* First release on PyPI.\n"
  },
  {
    "path": "LICENCE",
    "chars": 35147,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 10992,
    "preview": "Kubespray wrapper\n=============\n\nThis tool helps to deploy a kubernetes cluster with ansible.\n\n\nExample on GCE:\n[![ascii"
  },
  {
    "path": "bin/kubespray",
    "chars": 15878,
    "preview": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n#\n# This file is part of Kubespray.\n#\n#    Kubespray is free software: yo"
  },
  {
    "path": "setup.cfg",
    "chars": 40,
    "preview": "[metadata]\ndescription-file = README.md\n"
  },
  {
    "path": "setup.py",
    "chars": 1334,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nfrom setuptools import setup, find_packages\n\nrequirements = [\n "
  },
  {
    "path": "src/kubespray/__init__.py",
    "chars": 92,
    "preview": "# (c) 2016, Smaine Kahlouch <smainklh@gmail.com>\n__author__ = 'smana'\n__version__ = '0.5.2'\n"
  },
  {
    "path": "src/kubespray/cloud.py",
    "chars": 17360,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# This file is part of Kubespray.\n#\n#    Kubespray is free software: you"
  },
  {
    "path": "src/kubespray/common.py",
    "chars": 5636,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# This file is part of Kubespray.\n#\n#    Foobar is free software: you ca"
  },
  {
    "path": "src/kubespray/configure.py",
    "chars": 4129,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# This file is part of Kubespray.\n#\n#    Kubespray is free software: you"
  },
  {
    "path": "src/kubespray/deploy.py",
    "chars": 11128,
    "preview": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n#\n# This file is part of Kubespray.\n#\n#    Foobar is free software: you c"
  },
  {
    "path": "src/kubespray/files/.kubespray.yml",
    "chars": 2148,
    "preview": "---\n# Path where the kubespray ansible playbooks will be installed\n# Defaults to current user's home directory if not se"
  },
  {
    "path": "src/kubespray/inventory.py",
    "chars": 10915,
    "preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# This file is part of Kubespray.\n#\n#    Kubespray is free software: you"
  }
]

About this extraction

This page contains the full source code of the kubespray/kubespray-cli GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 14 files (112.3 KB), approximately 25.9k tokens, and a symbol index with 42 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!