Init: mediaserver

This commit is contained in:
2023-02-08 12:13:28 +01:00
parent 848bc9739c
commit f7c23d4ba9
31914 changed files with 6175775 additions and 0 deletions

View File

@@ -0,0 +1,283 @@
============================
Community Sops Release Notes
============================
.. contents:: Topics
v1.6.0
======
Release Summary
---------------
Feature release improving the installation role.
Minor Changes
-------------
- install role - add ``sops_github_latest_detection`` option that allows to configure which method to use for detecting the latest release on GitHub. By default (``auto``) first tries to retrieve a list of recent releases using the API, and if that fails due to rate limiting, tries to obtain the latest GitHub release from a semi-documented URL (https://github.com/ansible-collections/community.sops/pull/133).
- install role - add ``sops_github_token`` option to allow passing a GitHub token. This can for example be used to avoid rate limits when using the role in GitHub Actions (https://github.com/ansible-collections/community.sops/pull/132).
- install role - implement another method to determine the latest release on GitHub than using the GitHub API, which can make installation fail due to rate-limiting (https://github.com/ansible-collections/community.sops/pull/131).
v1.5.0
======
Release Summary
---------------
Feature release.
Minor Changes
-------------
- Automatically install GNU Privacy Guard (GPG) in execution environments. To install Mozilla sops a manual step needs to be added to the EE definition, see the collection's documentation for details (https://github.com/ansible-collections/community.sops/pull/98).
New Playbooks
-------------
- community.sops.install - Installs sops and GNU Privacy Guard on all remote hosts
- community.sops.install_localhost - Installs sops and GNU Privacy Guard on localhost
New Roles
---------
- community.sops.install - Install Mozilla sops
v1.4.1
======
Release Summary
---------------
Maintenance release to improve compatibility with future ansible-core releases.
Bugfixes
--------
- load_vars - ensure compatibility with newer versions of ansible-core (https://github.com/ansible-collections/community.sops/pull/121).
v1.4.0
======
Release Summary
---------------
Feature release.
Minor Changes
-------------
- Allow to specify age keys as ``age_key``, or age keyfiles as ``age_keyfile`` (https://github.com/ansible-collections/community.sops/issues/116, https://github.com/ansible-collections/community.sops/pull/117).
- sops_encrypt - allow to specify age recipients (https://github.com/ansible-collections/community.sops/issues/116, https://github.com/ansible-collections/community.sops/pull/117).
v1.3.0
======
Release Summary
---------------
Feature release.
Minor Changes
-------------
- All software licenses are now in the ``LICENSES/`` directory of the collection root, and the collection repository conforms to the `REUSE specification <https://reuse.software/spec/>`__ except for the changelog fragments (https://github.com/ansible-collections/community.crypto/sops/108, https://github.com/ansible-collections/community.sops/pull/113).
- sops vars plugin - added a configuration option to temporarily disable the vars plugin (https://github.com/ansible-collections/community.sops/pull/114).
v1.2.3
======
Release Summary
---------------
Fix formatting bug in documentation. No code changes.
v1.2.2
======
Release Summary
---------------
Maintenance release.
Bugfixes
--------
- Include ``simplified_bsd.txt`` license file for the ``sops`` module utils.
v1.2.1
======
Release Summary
---------------
Maintenance release with updated documentation.
v1.2.0
======
Release Summary
---------------
Collection release for inclusion in Ansible 4.9.0 and 5.1.0.
This release contains a change allowing to configure generic plugin options with ansible.cfg keys and env variables.
Minor Changes
-------------
- sops lookup and vars plugin - allow to configure almost all generic options by ansible.cfg entries and environment variables (https://github.com/ansible-collections/community.sops/pull/81).
Bugfixes
--------
- Fix error handling in calls of the ``sops`` binary when negative errors are returned (https://github.com/ansible-collections/community.sops/issues/82, https://github.com/ansible-collections/community.sops/pull/83).
v1.1.0
======
Release Summary
---------------
A minor release for inclusion in Ansible 4.2.0.
Minor Changes
-------------
- Avoid internal ansible-core module_utils in favor of equivalent public API available since at least Ansible 2.9 (https://github.com/ansible-collections/community.sops/pull/73).
New Plugins
-----------
Filter
~~~~~~
- community.sops.decrypt - Decrypt sops-encrypted data
v1.0.6
======
Release Summary
---------------
This release makes the collection compatible to the latest beta release of ansible-core 2.11.
Bugfixes
--------
- action_module plugin helper - make compatible with latest changes in ansible-core 2.11.0b3 (https://github.com/ansible-collections/community.sops/pull/58).
- community.sops.load_vars - make compatible with latest changes in ansible-core 2.11.0b3 (https://github.com/ansible-collections/community.sops/pull/58).
v1.0.5
======
Release Summary
---------------
This release fixes a bug that prevented correct YAML file to be created when the output was ending in `.yaml`.
Bugfixes
--------
- community.sops.sops_encrypt - use output type ``yaml`` when path ends with ``.yaml`` (https://github.com/ansible-collections/community.sops/pull/56).
v1.0.4
======
Release Summary
---------------
This is a security release, fixing a potential information leak in the ``community.sops.sops_encrypt`` module.
Security Fixes
--------------
- community.sops.sops_encrypt - mark the ``aws_secret_access_key`` and ``aws_session_token`` parameters as ``no_log`` to avoid leakage of secrets (https://github.com/ansible-collections/community.sops/pull/54).
v1.0.3
======
Release Summary
---------------
This release include some fixes to Ansible docs and required changes for inclusion in Ansible.
Bugfixes
--------
- community.sops.sops lookup plugins - fix wrong format of Ansible variables so that these are actually used (https://github.com/ansible-collections/community.sops/pull/51).
- community.sops.sops vars plugins - remove non-working Ansible variables (https://github.com/ansible-collections/community.sops/pull/51).
v1.0.2
======
Release Summary
---------------
Fix of 1.0.1 release which had no changelog entry.
v1.0.1
======
Release Summary
---------------
Re-release of 1.0.0 to counteract error during release.
v1.0.0
======
Release Summary
---------------
First stable release. This release is expected to be included in Ansible 3.0.0.
Minor Changes
-------------
- All plugins and modules: allow to pass generic sops options with new options ``config_path``, ``enable_local_keyservice``, ``keyservice``. Also allow to pass AWS parameters with options ``aws_profile``, ``aws_access_key_id``, ``aws_secret_access_key``, and ``aws_session_token`` (https://github.com/ansible-collections/community.sops/pull/47).
- community.sops.sops_encrypt - allow to pass encryption-specific options ``kms``, ``gcp_kms``, ``azure_kv``, ``hc_vault_transit``, ``pgp``, ``unencrypted_suffix``, ``encrypted_suffix``, ``unencrypted_regex``, ``encrypted_regex``, ``encryption_context``, and ``shamir_secret_sharing_threshold`` to sops (https://github.com/ansible-collections/community.sops/pull/47).
v0.2.0
======
Release Summary
---------------
This release adds features for the lookup and vars plugins.
Minor Changes
-------------
- community.sops.sops lookup plugin - add ``empty_on_not_exist`` option which allows to return an empty string instead of an error when the file does not exist (https://github.com/ansible-collections/community.sops/pull/33).
- community.sops.sops vars plugin - add option to control caching (https://github.com/ansible-collections/community.sops/pull/32).
- community.sops.sops vars plugin - add option to determine when vars are loaded (https://github.com/ansible-collections/community.sops/pull/32).
v0.1.0
======
Release Summary
---------------
First release of the `community.sops` collection!
This release includes multiple plugins: an `action` plugin, a `lookup` plugin and a `vars` plugin.
New Plugins
-----------
Lookup
~~~~~~
- community.sops.sops - Read sops encrypted file contents
Vars
~~~~
- community.sops.sops - Loading sops-encrypted vars files
New Modules
-----------
- community.sops.load_vars - Load sops-encrypted variables from files, dynamically within a task
- community.sops.sops_encrypt - Encrypt data with sops

View File

@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project

View File

@@ -0,0 +1,37 @@
<!--
Copyright (c) Ansible Project
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
-->
# Contributing
Hello and welcome! Thank you for being interested in contributing to this project.
First of all get confident with the [Ansible Collections Overview](https://github.com/ansible-collections/overview).
We accept pull requests for bugfixes, new features, and other improvements, assuming they pass our review. If you are planning a larger feature or refactoring, please create an issue first to discuss it with us.
## :bug: Reporting an issue
Please [search in the issue list](https://github.com/ansible-collections/community.sops/issues) and if has not been already reported, [open a new issue](https://github.com/ansible-collections/community.sops/issues/new/choose)
## 🏗 To contribute
A more extensive walk-through can be found in [Ansible's Contributing to collections](https://docs.ansible.com/ansible/latest/dev_guide/developing_collections.html#hacking-collections).
1. Fork this repo (when checking it out, see [here](https://docs.ansible.com/ansible/latest/dev_guide/developing_collections.html#contributing-to-collections) for how to place the checkout correctly)
1. Create a feature branch
1. Commit and push your code. To make the process faster, please ensure:
- the tests are green. Tests runs using [GitHub Actions](https://help.github.com/en/actions)
- you added a [changelog fragment](https://docs.ansible.com/ansible/latest/community/development_process.html#changelogs-how-to)
Please note that all PRs that are not strictly documentation, testing, or add a new plugin or module, require a changelog fragment. See [Creating a changelog fragment](https://docs.ansible.com/ansible/latest/community/development_process.html#changelogs-how-to) for information on that.
Further resources:
- [Ansible Developer guide: developing collections](https://docs.ansible.com/ansible/latest/dev_guide/developing_collections.html)
- [Ansible Developer guide](https://docs.ansible.com/ansible/latest/dev_guide/index.html)
This repository adheres to the [Ansible Community code of conduct](https://docs.ansible.com/ansible/latest/community/code_of_conduct.html)

View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://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 <https://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
<https://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
<https://www.gnu.org/licenses/why-not-lgpl.html>.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,8 @@
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://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 <https://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
<https://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
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@@ -0,0 +1,37 @@
{
"collection_info": {
"namespace": "community",
"name": "sops",
"version": "1.6.0",
"authors": [
"Edoardo Tenani"
],
"readme": "README.md",
"tags": [
"sops",
"encryption",
"decryption",
"secret",
"vault"
],
"description": "Support usage of mozilla/sops from your Ansible playbooks",
"license": [
"GPL-3.0-or-later",
"BSD-2-Clause"
],
"license_file": null,
"dependencies": {},
"repository": "https://github.com/ansible-collections/community.sops",
"documentation": null,
"homepage": "https://github.com/ansible-collections/community.sops",
"issues": "https://github.com/ansible-collections/community.sops/issues"
},
"file_manifest_file": {
"name": "FILES.json",
"ftype": "file",
"chksum_type": "sha256",
"chksum_sha256": "00045b59652c7d4d317ef1f26b4e98da121eb82114bcff1439455bee68c1e830",
"format": 1
},
"format": 1
}

View File

@@ -0,0 +1,354 @@
<!--
Copyright (c) Ansible Project
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
-->
# Community Sops Collection
[![CI](https://github.com/ansible-collections/community.sops/workflows/CI/badge.svg?event=push)](https://github.com/ansible-collections/community.sops/actions) [![Codecov](https://img.shields.io/codecov/c/github/ansible-collections/community.sops)](https://codecov.io/gh/ansible-collections/community.sops)
<!-- Describe the collection and why a user would want to use it. What does the collection do? -->
The `community.sops` collection allows integrating [`mozilla/sops`](https://github.com/mozilla/sops) in Ansible.
`mozilla/sops` is a tool for encryption and decryption of files using secure keys (GPG, KMS). It can be leveraged in Ansible to provide an easy to use and flexible to manage way to manage ecrypted secrets' files.
Please note that this collection does **not** support Windows targets.
**Sops version compatibility**
The following table shows which versions of sops were tested with which versions of the collection. Older (or newer) versions of sops can still work fine, it just means that we did not test them. In some cases, it could be that a minimal required version of sops is explicitly documented for a specific feature. Right now, that is not the case.
|`community.sops` version|`mozilla/sops` version|
|---|---|
|0.1.0|`3.5.0+`|
|1.0.6|`3.5.0+`|
|`main` branch|`3.5.0`, `3.6.0`, `3.7.1`, `3.7.2`, `3.7.3`|
## Tested with Ansible
Tested with the current Ansible 2.9, ansible-base 2.10, ansible-core 2.11, ansible-core 2.12, ansible-core 2.13, and ansible-core 2.14 releases and the current development version of ansible-core. Ansible versions before 2.9.10 are not supported.
The vars plugin requires ansible-base 2.10 or later.
## External requirements
<!-- List any external resources the collection depends on, for example minimum versions of an OS, libraries, or utilities. Do not list other Ansible collections here. -->
You will need to install [`sops`](https://github.com/mozilla/sops) manually before using plugins provided by this
collection.
## Collection Documentation
Browsing the [**latest** collection documentation](https://docs.ansible.com/ansible/latest/collections/community/sops) will show docs for the _latest version released in the Ansible package_, not the latest version of the collection released on Galaxy.
Browsing the [**devel** collection documentation](https://docs.ansible.com/ansible/devel/collections/community/sops) shows docs for the _latest version released on Galaxy_.
We also separately publish [**latest commit** collection documentation](https://ansible-collections.github.io/community.sops/branch/main/) which shows docs for the _latest commit in the `main` branch_.
If you use the Ansible package and do not update collections independently, use **latest**. If you install or update this collection directly from Galaxy, use **devel**. If you are looking to contribute, use **latest commit**.
## Included content
<!-- Galaxy will eventually list the module docs within the UI, but until that is ready, you may need to either describe your plugins etc here, or point to an external docsite to cover that information. -->
This collection provides:
- a [lookup plugin](https://docs.ansible.com/ansible/latest/user_guide/playbooks_lookups.html#playbooks-lookups) `sops` that allows looking up a sops-encrypted file content;
- a [vars plugin](https://docs.ansible.com/ansible/latest/plugins/vars.html) `sops` that allows loading Ansible vars from sops-encrypted files for hosts and groups;
- an [action plugin](https://docs.ansible.com/ansible/latest/plugins/action.html) `load_vars` that allows loading Ansible vars from a sops-encrypted file dynamically during a playbook or role;
- a [module](https://docs.ansible.com/ansible/latest/user_guide/basic_concepts.html#modules) `sops_encrypt` which allows to encrypt data with sops.
- a [role](https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_roles.html) `install` which allows to install sops and GNU Privacy Guard.
- two [playbooks](https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html) `install` and `install_localhost` which allow to install sops and GNU Privacy Guard.
## Using this collection
### Installing sops
To install sops, you can use the ``community.sops.install`` role. The role also installs [GNU Privacy Guard (GPG)](https://en.wikipedia.org/wiki/GNU_Privacy_Guard).
Examples:
```yaml
tasks:
# To use the sops_encrypt module on a remote host, you need to install sops on it:
- name: Install sops on remote hosts
ansible.builtin.include_role:
name: community.sops.install
vars:
sops_version: 2.7.0 # per default installs the latest version
# To use the lookup plugin, filter plugin, vars plugin, or the load_vars action,
# you need sops installed on localhost:
- name: Install sops on localhost
ansible.builtin.include_role:
name: community.sops.install
vars:
sops_install_on_localhost: true
```
### lookup plugin
The lookup plugin can be accessed with the `community.sops.sops` key.
Examples:
```yaml
tasks:
- name: Output secrets to screen (BAD IDEA!)
ansible.builtin.debug:
msg: "Content: {{ lookup('community.sops.sops', '/path/to/sops-encrypted-file.enc.yaml') }}"
- name: Add SSH private key
ansible.builtin.copy:
content: "{{ lookup('community.sops.sops', user + '-id_rsa') }}"
dest: /home/{{ user }}/.ssh/id_rsa
owner: "{{ user }}"
group: "{{ user }}"
mode: 0600
no_log: true # avoid content to be written to log
```
See [Lookup Plugins](https://docs.ansible.com/ansible/latest/plugins/lookup.html) for more details on lookup plugins.
### filter plugin
The filter plugin can be used in Jinja2 expressions by the name `community.sops.decrypt`. It can decrypt sops-encrypted data coming from other sources than files.
Example:
```yaml
tasks:
- name: Load sops encrypted data
ansible.builtin.set_fact:
encrypted_data: "{{ lookup('file', '/path/to/sops-encrypted-file.enc.yaml') }}"
- name: Output secrets to screen (BAD IDEA!)
ansible.builtin.debug:
msg: "Content: {{ encrypted_data | community.sops.decrypt(output_type='yaml') }}"
```
See [Filter Plugins](https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html) for more details on filters.
Please note that if you put a Jinja2 expression in a variable, it will be evaluated **every time it is used**. Decrypting data takes a certain amount of time. If you need to use an expression multiple times, it is better to store its evaluated form as a fact with `ansible.bulitin.set_fact` first:
```yaml
tasks:
- name: Decrypt data once
ansible.builtin.set_fact:
decrypted_data: "{{ encrypted_data | community.sops.decrypt }}"
run_once: true # if encrypted_data is identical on all hosts
- name: Use decrypted secrets multiple times
ansible.builtin.openssl_privatekey:
path: "/path/to/private_{{ item }}.pem"
passphrase: "{{ decrypted_data }}"
cipher: auto
loop:
- foo
- bar
- baz
```
By using `{{ encrypted_data | community.sops.decrypt }}` instead of `{{ decrypted_data }}` in the `openssl_privatekey` task, the data would be decrypted three times for every host this is executed for. With the `ansible.builtin.set_fact` and `run_once: true`, it is evaluated only once.
### vars plugin
Vars plugins only work in ansible >= 2.10 and require explicit enabling. One
way to enable the plugin is by adding the following to the `defaults` section of
your `ansible.cfg`:
```ini
vars_plugins_enabled = host_group_vars,community.sops.sops
```
See [VARIABLE_PLUGINS_ENABLED](https://docs.ansible.com/ansible/devel/reference_appendices/config.html#variable-plugins-enabled) for more details.
After the plugin is enabled, correctly named group and host vars files will be
transparently decrypted with sops.
The files must end with one of these extensions:
* `.sops.yaml`
* `.sops.yml`
* `.sops.json`
Here is an example file structure
```
├── inventory/
│ ├── group_vars/
│ │ └── all.sops.yml
│ ├── host_vars/
│ │ ├── server1.sops.yml
│ │ └── server2/
│ │ └── data.sops.yml
│ └── hosts
├── playbooks/
│ └── setup-server.yml
└── ansible.cfg
```
You could execute the playbook in this example with the following command. The
sops vars files would be decrypted and used.
```console
$ ansible-playbook playbooks/setup-server.yml -i inventory/hosts
```
#### Determine when to load variables
Ansible 2.10 allows to determine [when vars plugins load the data](https://docs.ansible.com/ansible/latest/plugins/vars.html#using-vars-plugins).
To run the sops vars plugin right after importing inventory, you can add the following to `ansible.cfg`:
```ini
[community.sops]
vars_stage = inventory
```
#### Caching variable files
By default, the sops vars plugin caches decrypted files to avoid having to decrypt them every task. If this is not wanted, it can be explicitly disabled in `ansible.cfg`:
```ini
[community.sops]
vars_cache = false
```
Please note that when using vars plugin staging, this setting only has effect if the variables are not only loaded during the `inventory` stage. See the documentation of the `community.sops.sops` vars plugin for more details.
### load_vars action plugin
The `load_vars` action plugin can be used similarly to Ansible's `include_vars`, except that it right now only supports single files. Also, it does not allow to load proper variables (i.e. "unsafe" Jinja2 expressions which evaluate on usage), but only facts. It does allow to evaluate expressions on load-time though.
Examples:
```yaml
tasks:
- name: Load variables from file and store them in a variable
community.sops.load_vars:
file: path/to/sops-encrypted-file.sops.yaml
name: variable_to_store_contents_in
- name: Load variables from file into global namespace, and evaluate Jinja2 expressions
community.sops.load_vars:
file: path/to/sops-encrypted-file-with-jinja2-expressions.sops.yaml
# The following allows to use Jinja2 expressions in the encrypted file!
# They are evaluated right now, i.e. not later like when loaded with include_vars.
expressions: evaluate-on-load
```
### sops_encrypt module
The `sops_encrypt` module can be used to create and update sops encrypted files. It assumes that sops is configured via environment variables or a `.sops.yaml` file.
Examples:
```yaml
tasks:
- name: Store secret text sops encrypted
community.sops.sops_encrypt:
path: path/to/sops-encrypted-file.sops
content_text: This is some secret text.
- name: Store secret binary data sops encrypted
community.sops.sops_encrypt:
path: path/to/sops-encrypted-file.sops
content_binary: "{{ some_secret_binary_data | b64encode }}"
- name: Store secret JSON data
community.sops.sops_encrypt:
path: path/to/sops-encrypted-file.sops.json
content_json:
key1: value1
key2:
- value2
- key3: value3
key4: value5
- name: Store secret YAML data
community.sops.sops_encrypt:
path: path/to/sops-encrypted-file.sops.yaml
content_yaml:
key1: value1
key2:
- value2
- key3: value3
key4: value5
```
## Troubleshooting
### Spurious failures during encryption and decryption with gpg
Sops calls `gpg` with `--use-agent`. When running multiple of these in parallel, for example when loading variables or looking up files for various hosts at once, some of these can randomly fail with messages such as
```
Failed to get the data key required to decrypt the SOPS file.
Group 0: FAILED
D13xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: FAILED
- | could not decrypt data key with PGP key:
| golang.org/x/crypto/openpgp error: Reading PGP message
| failed: openpgp: incorrect key; GPG binary error: exit
| status 2
828xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: FAILED
- | could not decrypt data key with PGP key:
| golang.org/x/crypto/openpgp error: Reading PGP message
| failed: openpgp: incorrect key; GPG binary error: exit
| status 2
Recovery failed because no master key was able to decrypt the file. In
order for SOPS to recover the file, at least one key has to be successful,
but none were.
```
This is a limitation of gpg-agent which can be fixed by adding `auto-expand-secmem` to `~/.gnupg/gpg-agent.conf` ([reference on option](https://www.gnupg.org/documentation/manuals/gnupg/Agent-Options.html#index-ssh_002dfingerprint_002ddigest), [reference on config file](https://www.gnupg.org/documentation/manuals/gnupg/Agent-Configuration.html)).
(See https://github.com/ansible-collections/community.sops/issues/34 and https://dev.gnupg.org/T4146 for more details.)
## Contributing to this collection
<!--Describe how the community can contribute to your collection. At a minimum, include how and where users can create issues to report problems or request features for this collection. List contribution requirements, including preferred workflows and necessary testing, so you can benefit from community PRs. If you are following general Ansible contributor guidelines, you can link to - [Ansible Community Guide](https://docs.ansible.com/ansible/latest/community/index.html). -->
See [CONTRIBUTING.md](./CONTRIBUTING.md)
## Release notes
See [CHANGELOG.rst](https://github.com/ansible-collections/community.sops/blob/main/CHANGELOG.rst).
## Releasing, Versioning and Deprecation
This collection follows [Semantic Versioning](https://semver.org/). More details on versioning can be found [in the Ansible docs](https://docs.ansible.com/ansible/latest/dev_guide/developing_collections.html#collection-versions).
We plan to regularly release new minor or bugfix versions once new features or bugfixes have been implemented.
Releasing the current major version happens from the `main` branch. We will create a `stable-1` branch for 1.x.y versions once we start working on a 2.0.0 release, to allow backporting bugfixes and features from the 2.0.0 branch (`main`) to `stable-1`. A `stable-2` branch will be created once we work on a 3.0.0 release, and so on.
We currently are not planning any deprecations or new major releases like 2.0.0 containing backwards incompatible changes. If backwards incompatible changes are needed, we plan to deprecate the old behavior as early as possible. We also plan to backport at least bugfixes for the old major version for some time after releasing a new major version. We will not block community members from backporting other bugfixes and features from the latest stable version to older release branches, under the condition that these backports are of reasonable quality.
### TODO
- add a role providing sops installation (with version pinning)
- a full test suite
## Code of Conduct
This repository adheres to the [Ansible Community code of conduct](https://docs.ansible.com/ansible/latest/community/code_of_conduct.html)
## More information
<!-- List out where the user can find additional information, such as working group meeting times, slack/IRC channels, or documentation for the product this collection automates. At a minimum, link to: -->
- [Ansible Collection overview](https://github.com/ansible-collections/overview)
- [Ansible User guide](https://docs.ansible.com/ansible/latest/user_guide/index.html)
- [Ansible Developer guide](https://docs.ansible.com/ansible/latest/dev_guide/index.html)
## Licensing
This collection is primarily licensed and distributed as a whole under the GNU General Public License v3.0 or later.
See [LICENSES/GPL-3.0-or-later.txt](https://github.com/ansible-collections/community.sops/blob/main/COPYING) for the full text.
Parts of the collection are licensed under the [BSD 2-Clause license](https://github.com/ansible-collections/community.sops/blob/main/LICENSES/BSD-2-Clause.txt).
All files have a machine readable `SDPX-License-Identifier:` comment denoting its respective license(s) or an equivalent entry in an accompanying `.license` file. Only changelog fragments (which will not be part of a release) are covered by a blanket statement in `.reuse/dep5`. This conforms to the [REUSE specification](https://reuse.software/spec/).

View File

@@ -0,0 +1,254 @@
ancestor: null
releases:
0.1.0:
changes:
release_summary: 'First release of the `community.sops` collection!
This release includes multiple plugins: an `action` plugin, a `lookup` plugin
and a `vars` plugin.'
fragments:
- 0.1.0.yml
modules:
- description: Load sops-encrypted variables from files, dynamically within a
task
name: load_vars
namespace: ''
- description: Encrypt data with sops
name: sops_encrypt
namespace: ''
plugins:
lookup:
- description: Read sops encrypted file contents
name: sops
namespace: null
vars:
- description: Loading sops-encrypted vars files
name: sops
namespace: null
release_date: '2020-10-23'
0.2.0:
changes:
minor_changes:
- community.sops.sops lookup plugin - add ``empty_on_not_exist`` option which
allows to return an empty string instead of an error when the file does not
exist (https://github.com/ansible-collections/community.sops/pull/33).
- community.sops.sops vars plugin - add option to control caching (https://github.com/ansible-collections/community.sops/pull/32).
- community.sops.sops vars plugin - add option to determine when vars are loaded
(https://github.com/ansible-collections/community.sops/pull/32).
release_summary: This release adds features for the lookup and vars plugins.
fragments:
- 0.2.0.yml
- 32-vars-stage.yml
- 33-lookup-empty_on_not_exist.yml
release_date: '2020-12-16'
1.0.0:
changes:
minor_changes:
- 'All plugins and modules: allow to pass generic sops options with new options
``config_path``, ``enable_local_keyservice``, ``keyservice``. Also allow to
pass AWS parameters with options ``aws_profile``, ``aws_access_key_id``, ``aws_secret_access_key``,
and ``aws_session_token`` (https://github.com/ansible-collections/community.sops/pull/47).'
- community.sops.sops_encrypt - allow to pass encryption-specific options ``kms``,
``gcp_kms``, ``azure_kv``, ``hc_vault_transit``, ``pgp``, ``unencrypted_suffix``,
``encrypted_suffix``, ``unencrypted_regex``, ``encrypted_regex``, ``encryption_context``,
and ``shamir_secret_sharing_threshold`` to sops (https://github.com/ansible-collections/community.sops/pull/47).
release_summary: First stable release. This release is expected to be included
in Ansible 3.0.0.
fragments:
- 1.0.0.yml
- 47-sops-options.yml
release_date: '2021-01-14'
1.0.1:
changes:
release_summary: Re-release of 1.0.0 to counteract error during release.
release_date: '2021-01-14'
1.0.2:
changes:
release_summary: Fix of 1.0.1 release which had no changelog entry.
fragments:
- 1.0.2.yml
release_date: '2021-01-14'
1.0.3:
changes:
bugfixes:
- community.sops.sops lookup plugins - fix wrong format of Ansible variables
so that these are actually used (https://github.com/ansible-collections/community.sops/pull/51).
- community.sops.sops vars plugins - remove non-working Ansible variables (https://github.com/ansible-collections/community.sops/pull/51).
release_summary: This release include some fixes to Ansible docs and required
changes for inclusion in Ansible.
fragments:
- 1.0.3.yml
- 51-fix-vars-arguments.yml
release_date: '2021-01-22'
1.0.4:
changes:
release_summary: This is a security release, fixing a potential information
leak in the ``community.sops.sops_encrypt`` module.
security_fixes:
- community.sops.sops_encrypt - mark the ``aws_secret_access_key`` and ``aws_session_token``
parameters as ``no_log`` to avoid leakage of secrets (https://github.com/ansible-collections/community.sops/pull/54).
fragments:
- 1.0.4.yml
- 54-no_log-fixes.yml
release_date: '2021-02-06'
1.0.5:
changes:
bugfixes:
- community.sops.sops_encrypt - use output type ``yaml`` when path ends with
``.yaml`` (https://github.com/ansible-collections/community.sops/pull/56).
release_summary: This release fixes a bug that prevented correct YAML file to
be created when the output was ending in `.yaml`.
fragments:
- 1.0.5.yml
- 56-sops_encrypt-yaml-output.yaml
release_date: '2021-03-05'
1.0.6:
changes:
bugfixes:
- action_module plugin helper - make compatible with latest changes in ansible-core
2.11.0b3 (https://github.com/ansible-collections/community.sops/pull/58).
- community.sops.load_vars - make compatible with latest changes in ansible-core
2.11.0b3 (https://github.com/ansible-collections/community.sops/pull/58).
release_summary: This release makes the collection compatible to the latest
beta release of ansible-core 2.11.
fragments:
- 1.0.6.yml
- 58-actionmodule-plugin-utils-ansible-core-2.11.yml
release_date: '2021-03-21'
1.1.0:
changes:
minor_changes:
- Avoid internal ansible-core module_utils in favor of equivalent public API
available since at least Ansible 2.9 (https://github.com/ansible-collections/community.sops/pull/73).
release_summary: A minor release for inclusion in Ansible 4.2.0.
fragments:
- 1.1.0.yml
- 71-decrypt-filter.yml
- ansible-core-_text.yml
plugins:
filter:
- description: Decrypt sops-encrypted data
name: decrypt
namespace: null
release_date: '2021-06-29'
1.2.0:
changes:
bugfixes:
- Fix error handling in calls of the ``sops`` binary when negative errors are
returned (https://github.com/ansible-collections/community.sops/issues/82,
https://github.com/ansible-collections/community.sops/pull/83).
minor_changes:
- sops lookup and vars plugin - allow to configure almost all generic options
by ansible.cfg entries and environment variables (https://github.com/ansible-collections/community.sops/pull/81).
release_summary: 'Collection release for inclusion in Ansible 4.9.0 and 5.1.0.
This release contains a change allowing to configure generic plugin options
with ansible.cfg keys and env variables.'
fragments:
- 1.2.0.yml
- 81-plugin-options.yml
- 83-fix-error-handling.yml
release_date: '2021-11-16'
1.2.1:
changes:
release_summary: Maintenance release with updated documentation.
fragments:
- 1.2.1.yml
release_date: '2022-03-22'
1.2.2:
changes:
bugfixes:
- Include ``simplified_bsd.txt`` license file for the ``sops`` module utils.
release_summary: Maintenance release.
fragments:
- 1.2.2.yml
- simplified-bsd-license.yml
release_date: '2022-06-02'
1.2.3:
changes:
release_summary: Fix formatting bug in documentation. No code changes.
fragments:
- 1.2.3.yml
release_date: '2022-06-29'
1.3.0:
changes:
minor_changes:
- All software licenses are now in the ``LICENSES/`` directory of the collection
root, and the collection repository conforms to the `REUSE specification <https://reuse.software/spec/>`__
except for the changelog fragments (https://github.com/ansible-collections/community.crypto/sops/108,
https://github.com/ansible-collections/community.sops/pull/113).
- sops vars plugin - added a configuration option to temporarily disable the
vars plugin (https://github.com/ansible-collections/community.sops/pull/114).
release_summary: Feature release.
fragments:
- 1.3.0.yml
- 108-licenses.yml
- 114-disable-vars-plugin.yml
release_date: '2022-08-23'
1.4.0:
changes:
minor_changes:
- Allow to specify age keys as ``age_key``, or age keyfiles as ``age_keyfile``
(https://github.com/ansible-collections/community.sops/issues/116, https://github.com/ansible-collections/community.sops/pull/117).
- sops_encrypt - allow to specify age recipients (https://github.com/ansible-collections/community.sops/issues/116,
https://github.com/ansible-collections/community.sops/pull/117).
release_summary: Feature release.
fragments:
- 1.4.0.yml
- 117-age.yml
release_date: '2022-09-11'
1.4.1:
changes:
bugfixes:
- load_vars - ensure compatibility with newer versions of ansible-core (https://github.com/ansible-collections/community.sops/pull/121).
release_summary: Maintenance release to improve compatibility with future ansible-core
releases.
fragments:
- 1.4.1.yml
- 121-action-module-compat.yml
release_date: '2022-09-23'
1.5.0:
changes:
minor_changes:
- Automatically install GNU Privacy Guard (GPG) in execution environments. To
install Mozilla sops a manual step needs to be added to the EE definition,
see the collection's documentation for details (https://github.com/ansible-collections/community.sops/pull/98).
release_summary: Feature release.
fragments:
- 1.5.0.yml
- 98-playbooks.yml
objects:
playbook:
- description: Installs sops and GNU Privacy Guard on all remote hosts
name: install
namespace: null
- description: Installs sops and GNU Privacy Guard on localhost
name: install_localhost
namespace: null
role:
- description: Install Mozilla sops
name: install
namespace: null
release_date: '2022-12-02'
1.6.0:
changes:
minor_changes:
- install role - add ``sops_github_latest_detection`` option that allows to
configure which method to use for detecting the latest release on GitHub.
By default (``auto``) first tries to retrieve a list of recent releases using
the API, and if that fails due to rate limiting, tries to obtain the latest
GitHub release from a semi-documented URL (https://github.com/ansible-collections/community.sops/pull/133).
- install role - add ``sops_github_token`` option to allow passing a GitHub
token. This can for example be used to avoid rate limits when using the role
in GitHub Actions (https://github.com/ansible-collections/community.sops/pull/132).
- install role - implement another method to determine the latest release on
GitHub than using the GitHub API, which can make installation fail due to
rate-limiting (https://github.com/ansible-collections/community.sops/pull/131).
release_summary: Feature release improving the installation role.
fragments:
- 1.6.0.yml
- 131.yml
- 132.yml
- 133.yml
release_date: '2023-01-01'

View File

@@ -0,0 +1,3 @@
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: Ansible Project

View File

@@ -0,0 +1,35 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
changelog_filename_template: ../CHANGELOG.rst
changelog_filename_version_depth: 0
changes_file: changelog.yaml
changes_format: combined
keep_fragments: false
mention_ancestor: true
new_plugins_after_name: removed_features
notesdir: fragments
prelude_section_name: release_summary
prelude_section_title: Release Summary
sections:
- - major_changes
- Major Changes
- - minor_changes
- Minor Changes
- - breaking_changes
- Breaking Changes / Porting Guide
- - deprecated_features
- Deprecated Features
- - removed_features
- Removed Features (previously deprecated)
- - security_fixes
- Security Fixes
- - bugfixes
- Bugfixes
- - known_issues
- Known Issues
title: Community Sops
trivial_section_name: trivial
use_fqcn: true

View File

@@ -0,0 +1,7 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
fixes:
- "ansible_collections/community/sops/::"

View File

@@ -0,0 +1,6 @@
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
gnupg [platform:dpkg]
gnupg2 [platform:rpm]

View File

@@ -0,0 +1,8 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
version: 1
dependencies:
system: meta/ee-bindep.txt

View File

@@ -0,0 +1,6 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
requires_ansible: '>=2.9.10'

View File

@@ -0,0 +1,12 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
- name: Install sops
gather_facts: true
hosts: all
tasks:
- name: Install sops on remote hosts
ansible.builtin.include_role:
name: community.sops.install

View File

@@ -0,0 +1,14 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
- name: Install sops on localhost
gather_facts: false
hosts: localhost
tasks:
- name: Install sops on localhost
ansible.builtin.include_role:
name: community.sops.install
vars:
sops_install_on_localhost: true

View File

@@ -0,0 +1,88 @@
# Copyright (c) 2020, Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from os import path, walk
import re
from ansible.module_utils.common.validation import check_type_bool, check_type_str
from ansible.module_utils.common._collections_compat import Sequence, Mapping
from ansible.module_utils.six import iteritems, string_types
from ansible.module_utils.common.text.converters import to_native, to_text
from ansible.plugins.action import ActionBase
from ansible.utils.display import Display
from ansible_collections.community.sops.plugins.module_utils.sops import Sops, SopsError, get_sops_argument_spec
from ansible_collections.community.sops.plugins.plugin_utils.action_module import ActionModuleBase, ArgumentSpec
display = Display()
class ActionModule(ActionModuleBase):
def _load(self, filename, module):
def get_option_value(argument_name):
return module.params.get(argument_name)
output = Sops.decrypt(filename, display=display, get_option_value=get_option_value)
data = self._loader.load(output, file_name=filename, show_content=False)
if not data:
data = dict()
if not isinstance(data, dict):
# Should not happen with sops-encrypted files
raise Exception('{0} must be stored as a dictionary/hash'.format(to_native(filename)))
return data
def _evaluate(self, value):
if isinstance(value, string_types):
# must come *before* Sequence, as strings are also instances of Sequence
return self._templar.template(value)
if isinstance(value, Sequence):
return [self._evaluate(v) for v in value]
if isinstance(value, Mapping):
return dict((k, self._evaluate(v)) for k, v in iteritems(value))
return value
@staticmethod
def setup_module():
argument_spec = ArgumentSpec(
argument_spec=dict(
file=dict(type='path', required=True),
name=dict(type='str'),
expressions=dict(type='str', default='ignore', choices=['ignore', 'evaluate-on-load']),
),
)
argument_spec.argument_spec.update(get_sops_argument_spec())
return argument_spec, {}
def run_module(self, module):
data = dict()
files = []
try:
filename = self._find_needle('vars', module.params['file'])
data.update(self._load(filename, module))
files.append(filename)
except Exception as e:
module.fail_json(msg=to_native(e))
name = module.params['name']
if name is None:
value = data
else:
value = dict()
value[name] = data
expressions = module.params['expressions']
if expressions == 'evaluate-on-load':
value = self._evaluate(value)
module.exit_json(
ansible_included_var_files=files,
ansible_facts=value,
_ansible_no_log=True,
)

View File

@@ -0,0 +1,74 @@
# -*- coding: utf-8 -*-
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
class ModuleDocFragment(object):
# Standard documentation fragment
DOCUMENTATION = r'''
options: {}
attributes:
check_mode:
description: Can run in C(check_mode) and return changed status prediction without modifying target.
diff_mode:
description: Will return details on what has changed (or possibly needs changing in C(check_mode)), when in diff mode.
'''
# Should be used together with the standard fragment
INFO_MODULE = r'''
options: {}
attributes:
check_mode:
support: full
details:
- This action does not modify state.
diff_mode:
support: N/A
details:
- This action does not modify state.
'''
FACTS = r'''
options: {}
attributes:
facts:
description: Action returns an C(ansible_facts) dictionary that will update existing host facts.
'''
# Should be used together with the standard fragment and the FACTS fragment
FACTS_MODULE = r'''
options: {}
attributes:
check_mode:
support: full
details:
- This action does not modify state.
diff_mode:
support: N/A
details:
- This action does not modify state.
facts:
support: full
'''
FILES = r'''
options: {}
attributes:
safe_file_operations:
description: Uses Ansible's strict file operation functions to ensure proper permissions and avoid data corruption.
'''
FLOW = r'''
options: {}
attributes:
action:
description: Indicates this has a corresponding action plugin so some parts of the options can be executed on the controller.
async:
description: Supports being used with the C(async) keyword.
'''

View File

@@ -0,0 +1,300 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
class ModuleDocFragment(object):
DOCUMENTATION = r'''
options:
sops_binary:
description:
- Path to the sops binary.
- By default uses C(sops).
type: path
version_added: 1.0.0
age_key:
description:
- One or more age private keys that can be used to decrypt encrypted files.
- Will be set as the C(SOPS_AGE_KEY) environment variable when calling sops.
type: str
version_added: 1.4.0
age_keyfile:
description:
- The file containing the age private keys that sops can use to decrypt
encrypted files.
- Will be set as the C(SOPS_AGE_KEY_FILE) environment variable when calling sops.
- By default, sops looks for C(sops/age/keys.txt) inside your user configuration
directory.
type: path
version_added: 1.4.0
aws_profile:
description:
- The AWS profile to use for requests to AWS.
- This corresponds to the sops C(--aws-profile) option.
type: str
version_added: 1.0.0
aws_access_key_id:
description:
- The AWS access key ID to use for requests to AWS.
- Sets the environment variable C(AWS_ACCESS_KEY_ID) for the sops call.
type: str
version_added: 1.0.0
aws_secret_access_key:
description:
- The AWS secret access key to use for requests to AWS.
- Sets the environment variable C(AWS_SECRET_ACCESS_KEY) for the sops call.
type: str
version_added: 1.0.0
aws_session_token:
description:
- The AWS session token to use for requests to AWS.
- Sets the environment variable C(AWS_SESSION_TOKEN) for the sops call.
type: str
version_added: 1.0.0
config_path:
description:
- Path to the sops configuration file.
- If not set, sops will recursively search for the config file starting at
the file that is encrypted or decrypted.
- This corresponds to the sops C(--config) option.
type: path
version_added: 1.0.0
enable_local_keyservice:
description:
- Tell sops to use local key service.
- This corresponds to the sops C(--enable-local-keyservice) option.
type: bool
default: false
version_added: 1.0.0
keyservice:
description:
- Specify key services to use next to the local one.
- A key service must be specified in the form C(protocol://address), for
example C(tcp://myserver.com:5000).
- This corresponds to the sops C(--keyservice) option.
type: list
elements: str
version_added: 1.0.0
'''
ANSIBLE_VARIABLES = r'''
options:
sops_binary:
vars:
- name: sops_binary
age_key:
vars:
- name: sops_age_key
age_keyfile:
vars:
- name: sops_age_keyfile
aws_profile:
vars:
- name: sops_aws_profile
aws_access_key_id:
vars:
- name: sops_aws_access_key_id
aws_secret_access_key:
vars:
- name: sops_aws_secret_access_key
aws_session_token:
vars:
- name: sops_session_token
- name: sops_aws_session_token
version_added: 1.2.0
config_path:
vars:
- name: sops_config_path
enable_local_keyservice:
vars:
- name: sops_enable_local_keyservice
keyservice:
vars:
- name: sops_keyservice
'''
ANSIBLE_ENV = r'''
options:
sops_binary:
env:
- name: ANSIBLE_SOPS_BINARY
version_added: 1.2.0
age_key:
env:
- name: ANSIBLE_SOPS_AGE_KEY
age_keyfile:
env:
- name: ANSIBLE_SOPS_AGE_KEYFILE
aws_profile:
env:
- name: ANSIBLE_SOPS_AWS_PROFILE
version_added: 1.2.0
aws_access_key_id:
env:
- name: ANSIBLE_SOPS_AWS_ACCESS_KEY_ID
version_added: 1.2.0
aws_secret_access_key:
env:
- name: ANSIBLE_SOPS_AWS_SECRET_ACCESS_KEY
version_added: 1.2.0
aws_session_token:
env:
- name: ANSIBLE_SOPS_AWS_SESSION_TOKEN
version_added: 1.2.0
config_path:
env:
- name: ANSIBLE_SOPS_CONFIG_PATH
version_added: 1.2.0
enable_local_keyservice:
env:
- name: ANSIBLE_SOPS_ENABLE_LOCAL_KEYSERVICE
version_added: 1.2.0
keyservice:
env:
- name: ANSIBLE_SOPS_KEYSERVICE
version_added: 1.2.0
'''
ANSIBLE_INI = r'''
options:
sops_binary:
ini:
- section: community.sops
key: binary
version_added: 1.2.0
# We do not provide an INI key for
# age_key
# to make sure that secrets cannot be provided in ansible.ini. Use environment variables or another mechanism for that.
age_keyfile:
ini:
- section: community.sops
key: age_keyfile
aws_profile:
ini:
- section: community.sops
key: aws_profile
version_added: 1.2.0
aws_access_key_id:
ini:
- section: community.sops
key: aws_access_key_id
version_added: 1.2.0
# We do not provide an INI key for
# aws_secret_access_key
# to make sure that secrets cannot be provided in ansible.ini. Use environment variables or another mechanism for that.
aws_session_token:
ini:
- section: community.sops
key: aws_session_token
version_added: 1.2.0
config_path:
ini:
- section: community.sops
key: config_path
version_added: 1.2.0
enable_local_keyservice:
ini:
- section: community.sops
key: enable_local_keyservice
version_added: 1.2.0
keyservice:
ini:
- section: community.sops
key: keyservice
version_added: 1.2.0
'''
ENCRYPT_SPECIFIC = r'''
options:
age:
description:
- Age fingerprints to use.
- This corresponds to the sops C(--age) option.
type: list
elements: str
version_added: 1.4.0
kms:
description:
- List of KMS ARNs to use.
- This corresponds to the sops C(--kms) option.
type: list
elements: str
version_added: 1.0.0
gcp_kms:
description:
- GCP KMS resource IDs to use.
- This corresponds to the sops C(--gcp-kms) option.
type: list
elements: str
version_added: 1.0.0
azure_kv:
description:
- Azure Key Vault URLs to use.
- This corresponds to the sops C(--azure-kv) option.
type: list
elements: str
version_added: 1.0.0
hc_vault_transit:
description:
- HashiCorp Vault key URIs to use.
- For example, C(https://vault.example.org:8200/v1/transit/keys/dev).
- This corresponds to the sops C(--hc-vault-transit) option.
type: list
elements: str
version_added: 1.0.0
pgp:
description:
- PGP fingerprints to use.
- This corresponds to the sops C(--pgp) option.
type: list
elements: str
version_added: 1.0.0
unencrypted_suffix:
description:
- Override the unencrypted key suffix.
- This corresponds to the sops C(--unencrypted-suffix) option.
type: str
version_added: 1.0.0
encrypted_suffix:
description:
- Override the encrypted key suffix.
- When set to an empty string, all keys will be encrypted that are not explicitly
marked by I(unencrypted_suffix).
- This corresponds to the sops C(--encrypted-suffix) option.
type: str
version_added: 1.0.0
unencrypted_regex:
description:
- Set the unencrypted key suffix.
- When specified, only keys matching the regular expression will be left unencrypted.
- This corresponds to the sops C(--unencrypted-regex) option.
type: str
version_added: 1.0.0
encrypted_regex:
description:
- Set the encrypted key suffix.
- When specified, only keys matching the regular expression will be encrypted.
- This corresponds to the sops C(--encrypted-regex) option.
type: str
version_added: 1.0.0
encryption_context:
description:
- List of KMS encryption context pairs of format C(key:value).
- This corresponds to the sops C(--encryption-context) option.
type: list
elements: str
version_added: 1.0.0
shamir_secret_sharing_threshold:
description:
- The number of distinct keys required to retrieve the data key with
L(Shamir's Secret Sharing, https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing).
- If not set here and in the sops config file, will default to C(0).
- This corresponds to the sops C(--shamir-secret-sharing-threshold) option.
type: int
version_added: 1.0.0
'''

View File

@@ -0,0 +1,75 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2022, Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
name: _latest_version
short_description: "[INTERNAL] Get latest version from a list of versions"
version_added: 1.4.0
author:
- Felix Fontein (@felixfontein)
description:
- B(This is an internal tool and must only be used from roles in this collection!)
If you use it from outside this collection, be warned that its behavior can change
and it can be removed at any time, even in bugfix releases!
- Given a list of version numbers, returns the largest of them.
options:
_input:
description:
- A list of strings. Every string must be a version number.
type: list
elements: string
required: true
'''
EXAMPLES = '''
- name: Print latest version
ansible.builtin.debug:
msg: "{{ versions | community.sops._latest_version }}"
vars:
versions:
- 1.0.0
- 1.0.0rc1
- 1.1.0
'''
RETURN = '''
_value:
description:
- The latest version from the input.
type: string
'''
from ansible.module_utils.six import raise_from
try:
from ansible.module_utils.compat.version import LooseVersion
except ImportError:
try:
from distutils.version import LooseVersion
except ImportError as exc:
msg = (
'To use this plugin or module with ansible-core 2.11, ansible-base 2.10,'
' or Ansible 2.9, you need to use Python < 3.12 with distutils.version present'
)
raise_from(ImportError(msg), exc)
def pick_latest_version(version_list):
'''Pick latest version from a list of versions.'''
if not version_list:
return ''
return sorted(version_list, key=LooseVersion, reverse=True)[0]
class FilterModule(object):
'''Helper filters.'''
def filters(self):
return {
'_latest_version': pick_latest_version,
}

View File

@@ -0,0 +1,172 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
name: decrpyt
short_description: Decrypt sops encrypted data
version_added: 1.1.0
author:
- Felix Fontein (@felixfontein)
description:
- Decrypt sops encrypted data.
- Allows to decrypt data that has been provided by an arbitrary source.
- Note that due to Ansible lazy-evaluating expressions, it is better to use M(ansible.builtin.set_fact)
to store the result of an evaluation in a fact to avoid recomputing the value every time the expression
is used.
options:
_input:
description:
- The data to decrypt.
type: string
required: true
rstrip:
description:
- Whether to remove trailing newlines and spaces.
type: bool
default: true
input_type:
description:
- Tell sops how to interpret the encrypted data.
- There is no auto-detection since we do not have a filename. By default
sops is told to treat the input as YAML. If that is wrong, please set this
option to the correct value.
type: str
choices:
- binary
- json
- yaml
- dotenv
default: yaml
output_type:
description:
- Tell sops how to interpret the decrypted file.
- Please note that the output is always text or bytes, depending on the value of I(decode_output).
To parse the resulting JSON or YAML, use corresponding filters such as C(ansible.builtin.from_json)
and C(ansible.builtin.from_yaml).
type: str
choices:
- binary
- json
- yaml
- dotenv
default: yaml
decode_output:
description:
- Whether to decode the output to bytes.
- When I(output_type=binary), and the file isn't known to contain UTF-8 encoded text,
this should better be set to C(false) to prevent mangling the data with UTF-8 decoding.
type: bool
default: true
extends_documentation_fragment:
- community.sops.sops
seealso:
- plugin: community.sops.sops
plugin_type: lookup
- plugin: community.sops.sops
plugin_type: vars
- module: community.sops.load_vars
'''
EXAMPLES = '''
- name: Decrypt file fetched from URL
hosts: localhost
gather_facts: false
tasks:
- name: Fetch file from URL
ansible.builtin.uri:
url: https://raw.githubusercontent.com/mozilla/sops/master/functional-tests/res/comments.enc.yaml
return_content: true
register: encrypted_content
- name: Show encrypted data
debug:
msg: "{{ encrypted_content.content | ansible.builtin.from_yaml }}"
- name: Decrypt data and decode decrypted YAML
set_fact:
decrypted_data: "{{ encrypted_content.content | community.sops.decrypt | ansible.builtin.from_yaml }}"
- name: Show decrypted data
debug:
msg: "{{ decrypted_data }}"
'''
RETURN = '''
_value:
description:
- Decrypted data as text (I(decode_output=true), default) or binary string (I(decode_output=false)).
type: string
'''
from ansible.errors import AnsibleError, AnsibleFilterError
from ansible.module_utils.common.text.converters import to_bytes, to_native
from ansible.utils.display import Display
from ansible_collections.community.sops.plugins.module_utils.sops import Sops, SopsError
_VALID_TYPES = set(['binary', 'json', 'yaml', 'dotenv'])
def decrypt_filter(data, input_type='yaml', output_type='yaml', sops_binary='sops', rstrip=True, decode_output=True,
aws_profile=None, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None,
config_path=None, enable_local_keyservice=False, keyservice=None, age_key=None, age_keyfile=None):
'''Decrypt sops-encrypted data.'''
# Check parameters
if input_type not in _VALID_TYPES:
raise AnsibleFilterError('input_type must be one of {expected}; got "{value}"'.format(
expected=', '.join(sorted(_VALID_TYPES)), value=input_type))
if output_type not in _VALID_TYPES:
raise AnsibleFilterError('output_type must be one of {expected}; got "{value}"'.format(
expected=', '.join(sorted(_VALID_TYPES)), value=output_type))
# Create option value querier
def get_option_value(argument_name):
if argument_name == 'sops_binary':
return sops_binary
if argument_name == 'age_key':
return age_key
if argument_name == 'age_keyfile':
return age_keyfile
if argument_name == 'aws_profile':
return aws_profile
if argument_name == 'aws_access_key_id':
return aws_access_key_id
if argument_name == 'aws_secret_access_key':
return aws_secret_access_key
if argument_name == 'aws_session_token':
return aws_session_token
if argument_name == 'config_path':
return config_path
if argument_name == 'enable_local_keyservice':
return enable_local_keyservice
if argument_name == 'keyservice':
return keyservice
raise AssertionError('internal error: should not be reached')
# Decode
data = to_bytes(data)
try:
output = Sops.decrypt(
None, content=data, display=Display(), rstrip=rstrip, decode_output=decode_output,
input_type=input_type, output_type=output_type, get_option_value=get_option_value)
except SopsError as e:
raise AnsibleFilterError(to_native(e))
return output
class FilterModule(object):
'''Ansible jinja2 filters'''
def filters(self):
return {
'decrypt': decrypt_filter,
}

View File

@@ -0,0 +1,160 @@
# -*- coding: utf-8 -*-
#
# Copyright 2018 Edoardo Tenani <e.tenani@arduino.cc> (@endorama)
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
name: sops
author: Edoardo Tenani (@endorama) <e.tenani@arduino.cc>
short_description: Read sops encrypted file contents
version_added: '0.1.0'
description:
- This lookup returns the contents from a file on the Ansible controller's file system.
- This lookup requires the C(sops) executable to be available in the controller PATH.
options:
_terms:
description: Path(s) of files to read.
required: true
rstrip:
description: Whether to remove trailing newlines and spaces.
type: bool
default: true
base64:
description:
- Base64-encodes the parsed result.
- Use this if you want to store binary data in Ansible variables.
type: bool
default: false
input_type:
description:
- Tell sops how to interpret the encrypted file.
- By default, sops will chose the input type from the file extension.
If it detects the wrong type for a file, this could result in decryption
failing.
type: str
choices:
- binary
- json
- yaml
- dotenv
output_type:
description:
- Tell sops how to interpret the decrypted file.
- By default, sops will chose the output type from the file extension.
If it detects the wrong type for a file, this could result in decryption
failing.
type: str
choices:
- binary
- json
- yaml
- dotenv
empty_on_not_exist:
description:
- When set to C(true), will not raise an error when a file cannot be found,
but return an empty string instead.
type: bool
default: false
extends_documentation_fragment:
- community.sops.sops
- community.sops.sops.ansible_variables
- community.sops.sops.ansible_env
- community.sops.sops.ansible_ini
notes:
- This lookup does not understand 'globbing' - use the fileglob lookup instead.
seealso:
- ref: community.sops.decrypt filter <ansible_collections.community.sops.decrypt_filter>
description: The decrypt filter can be used to descrypt sops-encrypted in-memory data.
# - plugin: community.sops.decrypt
# plugin_type: filter
- ref: community.sops.sops vars plugin <ansible_collections.community.sops.sops_vars>
description: The sops vars plugin can be used to load sops-encrypted host or group variables.
# - plugin: community.sops.sops
# plugin_type: vars
- module: community.sops.load_vars
"""
EXAMPLES = """
- name: Output secrets to screen (BAD IDEA!)
ansible.builtin.debug:
msg: "Content: {{ lookup('community.sops.sops', item) }}"
loop:
- sops-encrypted-file.enc.yaml
- name: Add SSH private key
ansible.builtin.copy:
# Note that rstrip=false is necessary for some SSH versions to be able to use the key
content: "{{ lookup('community.sops.sops', user + '-id_rsa', rstrip=false) }}"
dest: /home/{{ user }}/.ssh/id_rsa
owner: "{{ user }}"
group: "{{ user }}"
mode: 0600
no_log: true # avoid content to be written to log
- name: The file file.json is a YAML file, which contains the encryption of binary data
ansible.builtin.debug:
msg: "Content: {{ lookup('community.sops.sops', 'file.json', input_type='yaml', output_type='binary') }}"
"""
RETURN = """
_raw:
description: Decrypted file content.
type: list
elements: str
"""
import base64
from ansible.errors import AnsibleLookupError
from ansible.plugins.lookup import LookupBase
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.community.sops.plugins.module_utils.sops import Sops, SopsError
from ansible.utils.display import Display
display = Display()
class LookupModule(LookupBase):
def run(self, terms, variables=None, **kwargs):
self.set_options(var_options=variables, direct=kwargs)
rstrip = self.get_option('rstrip')
use_base64 = self.get_option('base64')
input_type = self.get_option('input_type')
output_type = self.get_option('output_type')
empty_on_not_exist = self.get_option('empty_on_not_exist')
ret = []
def get_option_value(argument_name):
return self.get_option(argument_name)
for term in terms:
display.debug("Sops lookup term: %s" % term)
lookupfile = self.find_file_in_search_path(variables, 'files', term, ignore_missing=empty_on_not_exist)
display.vvvv(u"Sops lookup using %s as file" % lookupfile)
if not lookupfile:
if empty_on_not_exist:
ret.append('')
continue
raise AnsibleLookupError("could not locate file in lookup: %s" % to_native(term))
try:
output = Sops.decrypt(
lookupfile, display=display, rstrip=rstrip, decode_output=not use_base64,
input_type=input_type, output_type=output_type, get_option_value=get_option_value)
except SopsError as e:
raise AnsibleLookupError(to_native(e))
if use_base64:
output = to_native(base64.b64encode(output))
ret.append(output)
return ret

View File

@@ -0,0 +1,53 @@
# Copyright (c), Yanis Guenane <yanis+ansible@guenane.org>, 2016
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import os
import tempfile
# This is taken from community.crypto
def write_file(module, content):
'''
Writes content into destination file as securely as possible.
Uses file arguments from module.
'''
# Find out parameters for file
file_args = module.load_file_common_arguments(module.params)
# Create tempfile name
tmp_fd, tmp_name = tempfile.mkstemp(prefix=b'.ansible_tmp')
try:
os.close(tmp_fd)
except Exception:
pass
module.add_cleanup_file(tmp_name) # if we fail, let Ansible try to remove the file
try:
try:
# Create tempfile
file = os.open(tmp_name, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
os.write(file, content)
os.close(file)
except Exception as e:
try:
os.remove(tmp_name)
except Exception:
pass
module.fail_json(msg='Error while writing result into temporary file: {0}'.format(e))
# Update destination to wanted permissions
if os.path.exists(file_args['path']):
module.set_fs_attributes_if_different(file_args, False)
# Move tempfile to final destination
module.atomic_move(tmp_name, file_args['path'])
# Try to update permissions again
module.set_fs_attributes_if_different(file_args, False)
except Exception as e:
try:
os.remove(tmp_name)
except Exception:
pass
module.fail_json(msg='Error while writing result: {0}'.format(e))

View File

@@ -0,0 +1,305 @@
# Copyright (c), Edoardo Tenani <e.tenani@arduino.cc>, 2018-2020
# Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
# SPDX-License-Identifier: BSD-2-Clause
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import abc
import os
from ansible.module_utils import six
from ansible.module_utils.common.text.converters import to_text, to_native
# Since this is used both by plugins and modules, we need subprocess in case the `module` parameter is not used
from subprocess import Popen, PIPE
# From https://github.com/mozilla/sops/blob/master/cmd/sops/codes/codes.go
# Should be manually updated
SOPS_ERROR_CODES = {
1: "ErrorGeneric",
2: "CouldNotReadInputFile",
3: "CouldNotWriteOutputFile",
4: "ErrorDumpingTree",
5: "ErrorReadingConfig",
6: "ErrorInvalidKMSEncryptionContextFormat",
7: "ErrorInvalidSetFormat",
8: "ErrorConflictingParameters",
21: "ErrorEncryptingMac",
23: "ErrorEncryptingTree",
24: "ErrorDecryptingMac",
25: "ErrorDecryptingTree",
49: "CannotChangeKeysFromNonExistentFile",
51: "MacMismatch",
52: "MacNotFound",
61: "ConfigFileNotFound",
85: "KeyboardInterrupt",
91: "InvalidTreePathFormat",
100: "NoFileSpecified",
128: "CouldNotRetrieveKey",
111: "NoEncryptionKeyFound",
200: "FileHasNotBeenModified",
201: "NoEditorFound",
202: "FailedToCompareVersions",
203: "FileAlreadyEncrypted"
}
def _create_single_arg(argument_name):
def f(value, arguments, env):
arguments.extend([argument_name, to_native(value)])
return f
def _create_comma_separated(argument_name):
def f(value, arguments, env):
arguments.extend([argument_name, ','.join([to_native(v) for v in value])])
return f
def _create_repeated(argument_name):
def f(value, arguments, env):
for v in value:
arguments.extend([argument_name, to_native(v)])
return f
def _create_boolean(argument_name):
def f(value, arguments, env):
if value:
arguments.append(argument_name)
return f
def _create_env_variable(argument_name):
def f(value, arguments, env):
env[argument_name] = value
return f
GENERAL_OPTIONS = {
'age_key': _create_env_variable('SOPS_AGE_KEY'),
'age_keyfile': _create_env_variable('SOPS_AGE_KEY_FILE'),
'aws_profile': _create_single_arg('--aws-profile'),
'aws_access_key_id': _create_env_variable('AWS_ACCESS_KEY_ID'),
'aws_secret_access_key': _create_env_variable('AWS_SECRET_ACCESS_KEY'),
'aws_session_token': _create_env_variable('AWS_SESSION_TOKEN'),
'config_path': _create_single_arg('--config'),
'enable_local_keyservice': _create_boolean('--enable-local-keyservice'),
'keyservice': _create_repeated('--keyservice'),
}
ENCRYPT_OPTIONS = {
'age': _create_comma_separated('--age'),
'kms': _create_comma_separated('--kms'),
'gcp_kms': _create_comma_separated('--gcp-kms'),
'azure_kv': _create_comma_separated('--azure-kv'),
'hc_vault_transit': _create_comma_separated('--hc-vault-transit'),
'pgp': _create_comma_separated('--pgp'),
'unencrypted_suffix': _create_single_arg('--unencrypted-suffix'),
'encrypted_suffix': _create_single_arg('--encrypted-suffix'),
'unencrypted_regex': _create_single_arg('--unencrypted-regex'),
'encrypted_regex': _create_single_arg('--encrypted-regex'),
'encryption_context': _create_comma_separated('--encryption-context'),
'shamir_secret_sharing_threshold': _create_single_arg('--shamir-secret-sharing-threshold'),
}
class SopsError(Exception):
''' Extend Exception class with sops specific informations '''
def __init__(self, filename, exit_code, message, decryption=True):
if exit_code in SOPS_ERROR_CODES:
exception_name = SOPS_ERROR_CODES[exit_code]
message = "error with file %s: %s exited with code %d: %s" % (
filename, exception_name, exit_code, to_native(message))
else:
message = "could not %s file %s; Unknown sops error code: %s; message: %s" % (
'decrypt' if decryption else 'encrypt', filename, exit_code, to_native(message))
super(SopsError, self).__init__(message)
class Sops():
''' Utility class to perform sops CLI actions '''
@staticmethod
def _add_options(command, env, get_option_value, options):
if get_option_value is None:
return
for option, f in options.items():
v = get_option_value(option)
if v is not None:
f(v, command, env)
@staticmethod
def get_sops_binary(get_option_value):
cmd = get_option_value('sops_binary') if get_option_value else None
if cmd is None:
cmd = 'sops'
return cmd
@staticmethod
def decrypt(encrypted_file, content=None,
display=None, decode_output=True, rstrip=True, input_type=None, output_type=None, get_option_value=None, module=None):
# Run sops directly, python module is deprecated
command = [Sops.get_sops_binary(get_option_value)]
env = os.environ.copy()
Sops._add_options(command, env, get_option_value, GENERAL_OPTIONS)
if input_type is not None:
command.extend(["--input-type", input_type])
if output_type is not None:
command.extend(["--output-type", output_type])
if content is not None:
encrypted_file = '/dev/stdin'
command.extend(["--decrypt", encrypted_file])
if module:
exit_code, output, err = module.run_command(command, environ_update=env, encoding=None, data=content, binary_data=True)
else:
process = Popen(command, stdin=None if content is None else PIPE, stdout=PIPE, stderr=PIPE, env=env)
(output, err) = process.communicate(input=content)
exit_code = process.returncode
if decode_output:
# output is binary, we want UTF-8 string
output = to_text(output, errors='surrogate_or_strict')
# the process output is the decrypted secret; be cautious
# sops logs always to stderr, as stdout is used for
# file content
if err and display:
display.vvvv(to_text(err, errors='surrogate_or_strict'))
if exit_code != 0:
raise SopsError(encrypted_file, exit_code, err, decryption=True)
if rstrip:
output = output.rstrip()
return output
@staticmethod
def encrypt(data, display=None, cwd=None, input_type=None, output_type=None, get_option_value=None, module=None):
# Run sops directly, python module is deprecated
command = [Sops.get_sops_binary(get_option_value)]
env = os.environ.copy()
Sops._add_options(command, env, get_option_value, GENERAL_OPTIONS)
Sops._add_options(command, env, get_option_value, ENCRYPT_OPTIONS)
if input_type is not None:
command.extend(["--input-type", input_type])
if output_type is not None:
command.extend(["--output-type", output_type])
command.extend(["--encrypt", "/dev/stdin"])
if module:
exit_code, output, err = module.run_command(command, data=data, binary_data=True, cwd=cwd, environ_update=env, encoding=None)
else:
process = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=cwd, env=env)
(output, err) = process.communicate(input=data)
exit_code = process.returncode
# sops logs always to stderr, as stdout is used for
# file content
if err and display:
display.vvvv(to_text(err, errors='surrogate_or_strict'))
if exit_code != 0:
raise SopsError('to stdout', exit_code, err, decryption=False)
return output
def get_sops_argument_spec(add_encrypt_specific=False):
argument_spec = {
'sops_binary': {
'type': 'path',
},
'age_key': {
'type': 'str',
'no_log': True,
},
'age_keyfile': {
'type': 'path',
},
'aws_profile': {
'type': 'str',
},
'aws_access_key_id': {
'type': 'str',
},
'aws_secret_access_key': {
'type': 'str',
'no_log': True,
},
'aws_session_token': {
'type': 'str',
'no_log': True,
},
'config_path': {
'type': 'path',
},
'enable_local_keyservice': {
'type': 'bool',
'default': False,
},
'keyservice': {
'type': 'list',
'elements': 'str',
},
}
if add_encrypt_specific:
argument_spec.update({
'age': {
'type': 'list',
'elements': 'str',
},
'kms': {
'type': 'list',
'elements': 'str',
},
'gcp_kms': {
'type': 'list',
'elements': 'str',
},
'azure_kv': {
'type': 'list',
'elements': 'str',
},
'hc_vault_transit': {
'type': 'list',
'elements': 'str',
},
'pgp': {
'type': 'list',
'elements': 'str',
},
'unencrypted_suffix': {
'type': 'str',
},
'encrypted_suffix': {
'type': 'str',
},
'unencrypted_regex': {
'type': 'str',
},
'encrypted_regex': {
'type': 'str',
},
'encryption_context': {
'type': 'list',
'elements': 'str',
},
'shamir_secret_sharing_threshold': {
'type': 'int',
'no_log': False,
},
})
return argument_spec

View File

@@ -0,0 +1,117 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
author: Felix Fontein (@felixfontein)
module: load_vars
short_description: Load sops-encrypted variables from files, dynamically within a task
version_added: '0.1.0'
description:
- Loads sops-encrypted YAML/JSON variables dynamically from a file during task runtime.
- To assign included variables to a different host than C(inventory_hostname),
use C(delegate_to) and set C(delegate_facts=true).
options:
file:
description:
- The file name from which variables should be loaded.
- If the path is relative, it will look for the file in C(vars/) subdirectory of a role or relative to playbook.
type: path
name:
description:
- The name of a variable into which assign the included vars.
- If omitted (C(null)) they will be made top level vars.
type: str
expressions:
description:
- This option controls how Jinja2 expressions in values in the loaded file are handled.
- If set to C(ignore), expressions will not be evaluated, but treated as regular strings.
- If set to C(evaluate-on-load), expressions will be evaluated on execution of this module,
in other words, when the file is loaded.
- Unfortunately, there is no way for non-core modules to handle expressions "unsafe",
in other words, evaluate them only on use. This can only achieved by M(ansible.builtin.include_vars),
which unfortunately cannot handle sops-encrypted files.
type: str
default: ignore
choices:
- ignore
- evaluate-on-load
extends_documentation_fragment:
- community.sops.sops
- community.sops.attributes
- community.sops.attributes.facts
- community.sops.attributes.flow
attributes:
action:
support: full
async:
support: none
details:
- This action runs completely on the controller.
check_mode:
support: full
diff_mode:
support: N/A
details:
- This action does not modify state.
facts:
support: full
seealso:
- module: ansible.builtin.set_fact
- module: ansible.builtin.include_vars
- ref: playbooks_delegation
description: More information related to task delegation.
- ref: community.sops.sops lookup <ansible_collections.community.sops.sops_lookup>
description: The sops lookup can be used decrypt sops-encrypted files.
# - plugin: community.sops.sops
# plugin_type: lookup
- ref: community.sops.decrypt filter <ansible_collections.community.sops.decrypt_filter>
description: The decrypt filter can be used to descrypt sops-encrypted in-memory data.
# - plugin: community.sops.decrypt
# plugin_type: filter
- ref: community.sops.sops vars plugin <ansible_collections.community.sops.sops_vars>
description: The sops vars plugin can be used to load sops-encrypted host or group variables.
# - plugin: community.sops.sops
# plugin_type: vars
'''
EXAMPLES = r'''
- name: Include variables of stuff.sops.yaml into the 'stuff' variable
community.sops.load_vars:
file: stuff.sops.yaml
name: stuff
expressions: evaluate-on-load # interpret Jinja2 expressions in stuf.sops.yaml on load-time!
- name: Conditionally decide to load in variables into 'plans' when x is 0, otherwise do not
community.sops.load_vars:
file: contingency_plan.sops.yaml
name: plans
expressions: ignore # do not interpret possible Jinja2 expressions
when: x == 0
- name: Load variables into the global namespace
community.sops.load_vars:
file: contingency_plan.sops.yaml
'''
RETURN = r'''
ansible_facts:
description: Variables that were included and their values.
returned: success
type: dict
sample: {'variable': 'value'}
ansible_included_var_files:
description: A list of files that were successfully included
returned: success
type: list
elements: str
sample: [ /path/to/file.sops.yaml ]
'''

View File

@@ -0,0 +1,237 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
author: Felix Fontein (@felixfontein)
module: sops_encrypt
short_description: Encrypt data with sops
version_added: '0.1.0'
description:
- Allows to encrypt binary data (Base64 encoded), text data, JSON or YAML data with sops.
options:
path:
description:
- The sops encrypt file.
type: path
required: true
force:
description:
- Force rewriting the encrypted file.
type: bool
default: false
content_text:
description:
- The data to encrypt. Must be a Unicode text.
- Please note that the module might not be idempotent if the text can be parsed as JSON or YAML.
- Exactly one of I(content_text), I(content_binary), I(content_json) and I(content_yaml) must be specified.
type: str
content_binary:
description:
- The data to encrypt. Must be L(Base64 encoded,https://en.wikipedia.org/wiki/Base64) binary data.
- Please note that the module might not be idempotent if the data can be parsed as JSON or YAML.
- Exactly one of I(content_text), I(content_binary), I(content_json) and I(content_yaml) must be specified.
type: str
content_json:
description:
- The data to encrypt. Must be a JSON dictionary.
- Exactly one of I(content_text), I(content_binary), I(content_json) and I(content_yaml) must be specified.
type: dict
content_yaml:
description:
- The data to encrypt. Must be a YAML dictionary.
- Please note that Ansible only allows to pass data that can be represented as a JSON dictionary.
- Exactly one of I(content_text), I(content_binary), I(content_json) and I(content_yaml) must be specified.
type: dict
extends_documentation_fragment:
- ansible.builtin.files
- community.sops.sops
- community.sops.sops.encrypt_specific
- community.sops.attributes
- community.sops.attributes.files
attributes:
check_mode:
support: full
diff_mode:
support: none
safe_file_operations:
support: full
seealso:
- ref: community.sops.sops lookup <ansible_collections.community.sops.sops_lookup>
description: The sops lookup can be used decrypt sops-encrypted files.
# - plugin: community.sops.sops
# plugin_type: lookup
'''
EXAMPLES = r'''
- name: Encrypt a secret text
community.sops.sops_encrypt:
path: text-data.sops
content_text: This is a secret text.
- name: Encrypt the contents of a file
community.sops.sops_encrypt:
path: binary-data.sops
content_binary: "{{ lookup('ansible.builtin.file', '/path/to/file', rstrip=false) | b64encode }}"
- name: Encrypt some datastructure as YAML
community.sops.sops_encrypt:
path: stuff.sops.yaml
content_yaml: "{{ result }}"
'''
RETURN = r''' # '''
import base64
import json
import os
import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_text
from ansible_collections.community.sops.plugins.module_utils.io import write_file
from ansible_collections.community.sops.plugins.module_utils.sops import Sops, SopsError, get_sops_argument_spec
try:
import yaml
YAML_IMP_ERR = None
HAS_YAML = True
except ImportError:
YAML_IMP_ERR = traceback.format_exc()
HAS_YAML = False
yaml = None
def get_data_type(module):
if module.params['content_text'] is not None:
return 'binary'
if module.params['content_binary'] is not None:
return 'binary'
if module.params['content_json'] is not None:
return 'json'
if module.params['content_yaml'] is not None:
return 'yaml'
module.fail_json(msg='Internal error: unknown content type')
def compare_encoded_content(module, binary_data, content):
if module.params['content_text'] is not None:
return content == module.params['content_text'].encode('utf-8')
if module.params['content_binary'] is not None:
return content == binary_data
if module.params['content_json'] is not None:
# Compare JSON
try:
return json.loads(content) == module.params['content_json']
except Exception:
# Treat parsing errors as content not equal
return False
if module.params['content_yaml'] is not None:
# Compare YAML
try:
return yaml.safe_load(content) == module.params['content_yaml']
except Exception:
# Treat parsing errors as content not equal
return False
module.fail_json(msg='Internal error: unknown content type')
def get_encoded_type_content(module, binary_data):
if module.params['content_text'] is not None:
return 'binary', module.params['content_text'].encode('utf-8')
if module.params['content_binary'] is not None:
return 'binary', binary_data
if module.params['content_json'] is not None:
return 'json', json.dumps(module.params['content_json']).encode('utf-8')
if module.params['content_yaml'] is not None:
return 'yaml', yaml.safe_dump(module.params['content_yaml']).encode('utf-8')
module.fail_json(msg='Internal error: unknown content type')
def main():
argument_spec = dict(
path=dict(type='path', required=True),
force=dict(type='bool', default=False),
content_text=dict(type='str', no_log=True),
content_binary=dict(type='str', no_log=True),
content_json=dict(type='dict', no_log=True),
content_yaml=dict(type='dict', no_log=True),
)
argument_spec.update(get_sops_argument_spec(add_encrypt_specific=True))
module = AnsibleModule(
argument_spec=argument_spec,
mutually_exclusive=[
('content_text', 'content_binary', 'content_json', 'content_yaml'),
],
required_one_of=[
('content_text', 'content_binary', 'content_json', 'content_yaml'),
],
supports_check_mode=True,
add_file_common_args=True,
)
# Check YAML
if module.params['content_yaml'] is not None and not HAS_YAML:
module.fail_json(msg=missing_required_lib('pyyaml'), exception=YAML_IMP_ERR)
# Decode binary data
binary_data = None
if module.params['content_binary'] is not None:
try:
binary_data = base64.b64decode(module.params['content_binary'])
except Exception as e:
module.fail_json(msg='Cannot decode Base64 encoded data: {0}'.format(e))
path = module.params['path']
directory = os.path.dirname(path) or None
changed = False
def get_option_value(argument_name):
return module.params.get(argument_name)
try:
if module.params['force'] or not os.path.exists(path):
# Simply encrypt
changed = True
else:
# Change detection: check if encrypted data equals new data
decrypted_content = Sops.decrypt(
path, decode_output=False, output_type=get_data_type(module), rstrip=False,
get_option_value=get_option_value, module=module,
)
if not compare_encoded_content(module, binary_data, decrypted_content):
changed = True
if changed and not module.check_mode:
input_type, input_data = get_encoded_type_content(module, binary_data)
output_type = None
if path.endswith('.json'):
output_type = 'json'
elif path.endswith('.yaml'):
output_type = 'yaml'
data = Sops.encrypt(
data=input_data, cwd=directory, input_type=input_type, output_type=output_type,
get_option_value=get_option_value, module=module,
)
write_file(module, data)
except SopsError as e:
module.fail_json(msg=to_text(e))
file_args = module.load_file_common_arguments(module.params)
changed = module.set_fs_attributes_if_different(file_args, changed)
module.exit_json(changed=changed)
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,781 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2013 Michael DeHaan <michael.dehaan@gmail.com>
# Copyright (c) 2016 Toshio Kuratomi <tkuratomi@ansible.com>
# Copyright (c) 2019 Ansible Project
# Copyright (c) 2020 Felix Fontein <felix@fontein.de>
# Copyright (c) 2021 Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
# Parts taken from ansible.module_utils.basic and ansible.module_utils.common.warnings.
# NOTE: THIS IS ONLY FOR ACTION PLUGINS!
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import abc
import copy
import traceback
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.module_utils import six
from ansible.module_utils.basic import AnsibleFallbackNotFound, SEQUENCETYPE, remove_values
from ansible.module_utils.common._collections_compat import (
Mapping
)
from ansible.module_utils.common.parameters import (
PASS_VARS,
PASS_BOOLS,
)
from ansible.module_utils.common.validation import (
check_mutually_exclusive,
check_required_arguments,
check_required_by,
check_required_if,
check_required_one_of,
check_required_together,
count_terms,
check_type_bool,
check_type_bits,
check_type_bytes,
check_type_float,
check_type_int,
check_type_jsonarg,
check_type_list,
check_type_dict,
check_type_path,
check_type_raw,
check_type_str,
safe_eval,
)
from ansible.module_utils.common.text.formatters import (
lenient_lowercase,
)
from ansible.module_utils.parsing.convert_bool import BOOLEANS_FALSE, BOOLEANS_TRUE
from ansible.module_utils.six import (
binary_type,
string_types,
text_type,
)
from ansible.module_utils.common.text.converters import to_native, to_text
from ansible.plugins.action import ActionBase
try:
# For ansible-core 2.11, we can use the ArgumentSpecValidator. We also import
# ModuleArgumentSpecValidator since that indicates that the 'classical' approach
# will no longer work.
from ansible.module_utils.common.arg_spec import (
ArgumentSpecValidator,
ModuleArgumentSpecValidator, # noqa
)
from ansible.module_utils.errors import UnsupportedError
HAS_ARGSPEC_VALIDATOR = True
except ImportError:
# For ansible-base 2.10 and Ansible 2.9, we need to use the 'classical' approach
from ansible.module_utils.common.parameters import (
handle_aliases,
list_deprecations,
list_no_log_values,
)
HAS_ARGSPEC_VALIDATOR = False
class _ModuleExitException(Exception):
def __init__(self, result):
super(_ModuleExitException, self).__init__()
self.result = result
class AnsibleActionModule(object):
def __init__(self, action_plugin, argument_spec, bypass_checks=False,
mutually_exclusive=None, required_together=None,
required_one_of=None, supports_check_mode=False,
required_if=None, required_by=None):
# Internal data
self.__action_plugin = action_plugin
self.__warnings = []
self.__deprecations = []
# AnsibleModule data
self._name = self.__action_plugin._task.action
self.argument_spec = argument_spec
self.supports_check_mode = supports_check_mode
self.check_mode = self.__action_plugin._play_context.check_mode
self.bypass_checks = bypass_checks
self.no_log = self.__action_plugin._play_context.no_log
self.mutually_exclusive = mutually_exclusive
self.required_together = required_together
self.required_one_of = required_one_of
self.required_if = required_if
self.required_by = required_by
self._diff = self.__action_plugin._play_context.diff
self._verbosity = self.__action_plugin._display.verbosity
self.aliases = {}
self._legal_inputs = []
self._options_context = list()
self.params = copy.deepcopy(self.__action_plugin._task.args)
self.no_log_values = set()
if HAS_ARGSPEC_VALIDATOR:
self._validator = ArgumentSpecValidator(
self.argument_spec,
self.mutually_exclusive,
self.required_together,
self.required_one_of,
self.required_if,
self.required_by,
)
self._validation_result = self._validator.validate(self.params)
self.params.update(self._validation_result.validated_parameters)
self.no_log_values.update(self._validation_result._no_log_values)
try:
error = self._validation_result.errors[0]
except IndexError:
error = None
# We cannot use ModuleArgumentSpecValidator directly since it uses mechanisms for reporting
# warnings and deprecations that do not work in plugins. This is a copy of that code adjusted
# for our use-case:
for d in self._validation_result._deprecations:
self.deprecate(
"Alias '{name}' is deprecated. See the module docs for more information".format(name=d['name']),
version=d.get('version'), date=d.get('date'), collection_name=d.get('collection_name'))
for w in self._validation_result._warnings:
self.warn('Both option {option} and its alias {alias} are set.'.format(option=w['option'], alias=w['alias']))
# Fail for validation errors, even in check mode
if error:
msg = self._validation_result.errors.msg
if isinstance(error, UnsupportedError):
msg = "Unsupported parameters for ({name}) {kind}: {msg}".format(name=self._name, kind='module', msg=msg)
self.fail_json(msg=msg)
else:
self._set_fallbacks()
# append to legal_inputs and then possibly check against them
try:
self.aliases = self._handle_aliases()
except (ValueError, TypeError) as e:
# Use exceptions here because it isn't safe to call fail_json until no_log is processed
raise _ModuleExitException(dict(failed=True, msg="Module alias error: %s" % to_native(e)))
# Save parameter values that should never be logged
self._handle_no_log_values()
self._check_arguments()
# check exclusive early
if not bypass_checks:
self._check_mutually_exclusive(mutually_exclusive)
self._set_defaults(pre=True)
self._CHECK_ARGUMENT_TYPES_DISPATCHER = {
'str': self._check_type_str,
'list': check_type_list,
'dict': check_type_dict,
'bool': check_type_bool,
'int': check_type_int,
'float': check_type_float,
'path': check_type_path,
'raw': check_type_raw,
'jsonarg': check_type_jsonarg,
'json': check_type_jsonarg,
'bytes': check_type_bytes,
'bits': check_type_bits,
}
if not bypass_checks:
self._check_required_arguments()
self._check_argument_types()
self._check_argument_values()
self._check_required_together(required_together)
self._check_required_one_of(required_one_of)
self._check_required_if(required_if)
self._check_required_by(required_by)
self._set_defaults(pre=False)
# deal with options sub-spec
self._handle_options()
def _handle_aliases(self, spec=None, param=None, option_prefix=''):
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
# this uses exceptions as it happens before we can safely call fail_json
alias_warnings = []
alias_results, self._legal_inputs = handle_aliases(spec, param, alias_warnings=alias_warnings) # pylint: disable=used-before-assignment
for option, alias in alias_warnings:
self.warn('Both option %s and its alias %s are set.' % (option_prefix + option, option_prefix + alias))
deprecated_aliases = []
for i in spec.keys():
if 'deprecated_aliases' in spec[i].keys():
for alias in spec[i]['deprecated_aliases']:
deprecated_aliases.append(alias)
for deprecation in deprecated_aliases:
if deprecation['name'] in param.keys():
self.deprecate("Alias '%s' is deprecated. See the module docs for more information" % deprecation['name'],
version=deprecation.get('version'), date=deprecation.get('date'),
collection_name=deprecation.get('collection_name'))
return alias_results
def _handle_no_log_values(self, spec=None, param=None):
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
try:
self.no_log_values.update(list_no_log_values(spec, param)) # pylint: disable=used-before-assignment
except TypeError as te:
self.fail_json(msg="Failure when processing no_log parameters. Module invocation will be hidden. "
"%s" % to_native(te), invocation={'module_args': 'HIDDEN DUE TO FAILURE'})
for message in list_deprecations(spec, param): # pylint: disable=used-before-assignment
self.deprecate(message['msg'], version=message.get('version'), date=message.get('date'),
collection_name=message.get('collection_name'))
def _check_arguments(self, spec=None, param=None, legal_inputs=None):
self._syslog_facility = 'LOG_USER'
unsupported_parameters = set()
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
if legal_inputs is None:
legal_inputs = self._legal_inputs
for k in list(param.keys()):
if k not in legal_inputs:
unsupported_parameters.add(k)
for k in PASS_VARS:
# handle setting internal properties from internal ansible vars
param_key = '_ansible_%s' % k
if param_key in param:
if k in PASS_BOOLS:
setattr(self, PASS_VARS[k][0], self.boolean(param[param_key]))
else:
setattr(self, PASS_VARS[k][0], param[param_key])
# clean up internal top level params:
if param_key in self.params:
del self.params[param_key]
else:
# use defaults if not already set
if not hasattr(self, PASS_VARS[k][0]):
setattr(self, PASS_VARS[k][0], PASS_VARS[k][1])
if unsupported_parameters:
msg = "Unsupported parameters for (%s) module: %s" % (self._name, ', '.join(sorted(list(unsupported_parameters))))
if self._options_context:
msg += " found in %s." % " -> ".join(self._options_context)
supported_parameters = list()
for key in sorted(spec.keys()):
if 'aliases' in spec[key] and spec[key]['aliases']:
supported_parameters.append("%s (%s)" % (key, ', '.join(sorted(spec[key]['aliases']))))
else:
supported_parameters.append(key)
msg += " Supported parameters include: %s" % (', '.join(supported_parameters))
self.fail_json(msg=msg)
if self.check_mode and not self.supports_check_mode:
self.exit_json(skipped=True, msg="action module (%s) does not support check mode" % self._name)
def _count_terms(self, check, param=None):
if param is None:
param = self.params
return count_terms(check, param)
def _check_mutually_exclusive(self, spec, param=None):
if param is None:
param = self.params
try:
check_mutually_exclusive(spec, param)
except TypeError as e:
msg = to_native(e)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def _check_required_one_of(self, spec, param=None):
if spec is None:
return
if param is None:
param = self.params
try:
check_required_one_of(spec, param)
except TypeError as e:
msg = to_native(e)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def _check_required_together(self, spec, param=None):
if spec is None:
return
if param is None:
param = self.params
try:
check_required_together(spec, param)
except TypeError as e:
msg = to_native(e)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def _check_required_by(self, spec, param=None):
if spec is None:
return
if param is None:
param = self.params
try:
check_required_by(spec, param)
except TypeError as e:
self.fail_json(msg=to_native(e))
def _check_required_arguments(self, spec=None, param=None):
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
try:
check_required_arguments(spec, param)
except TypeError as e:
msg = to_native(e)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def _check_required_if(self, spec, param=None):
''' ensure that parameters which conditionally required are present '''
if spec is None:
return
if param is None:
param = self.params
try:
check_required_if(spec, param)
except TypeError as e:
msg = to_native(e)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def _check_argument_values(self, spec=None, param=None):
''' ensure all arguments have the requested values, and there are no stray arguments '''
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
for (k, v) in spec.items():
choices = v.get('choices', None)
if choices is None:
continue
if isinstance(choices, SEQUENCETYPE) and not isinstance(choices, (binary_type, text_type)):
if k in param:
# Allow one or more when type='list' param with choices
if isinstance(param[k], list):
diff_list = ", ".join([item for item in param[k] if item not in choices])
if diff_list:
choices_str = ", ".join([to_native(c) for c in choices])
msg = "value of %s must be one or more of: %s. Got no match for: %s" % (k, choices_str, diff_list)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
elif param[k] not in choices:
# PyYaml converts certain strings to bools. If we can unambiguously convert back, do so before checking
# the value. If we can't figure this out, module author is responsible.
lowered_choices = None
if param[k] == 'False':
lowered_choices = lenient_lowercase(choices)
overlap = BOOLEANS_FALSE.intersection(choices)
if len(overlap) == 1:
# Extract from a set
(param[k],) = overlap
if param[k] == 'True':
if lowered_choices is None:
lowered_choices = lenient_lowercase(choices)
overlap = BOOLEANS_TRUE.intersection(choices)
if len(overlap) == 1:
(param[k],) = overlap
if param[k] not in choices:
choices_str = ", ".join([to_native(c) for c in choices])
msg = "value of %s must be one of: %s, got: %s" % (k, choices_str, param[k])
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
else:
msg = "internal error: choices for argument %s are not iterable: %s" % (k, choices)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def safe_eval(self, value, locals=None, include_exceptions=False):
return safe_eval(value, locals, include_exceptions)
def _check_type_str(self, value, param=None, prefix=''):
opts = {
'error': False,
'warn': False,
'ignore': True
}
# Ignore, warn, or error when converting to a string.
allow_conversion = opts.get(C.STRING_CONVERSION_ACTION, True)
try:
return check_type_str(value, allow_conversion)
except TypeError:
common_msg = 'quote the entire value to ensure it does not change.'
from_msg = '{0!r}'.format(value)
to_msg = '{0!r}'.format(to_text(value))
if param is not None:
if prefix:
param = '{0}{1}'.format(prefix, param)
from_msg = '{0}: {1!r}'.format(param, value)
to_msg = '{0}: {1!r}'.format(param, to_text(value))
if C.STRING_CONVERSION_ACTION == 'error':
msg = common_msg.capitalize()
raise TypeError(to_native(msg))
elif C.STRING_CONVERSION_ACTION == 'warn':
msg = ('The value "{0}" (type {1.__class__.__name__}) was converted to "{2}" (type string). '
'If this does not look like what you expect, {3}').format(from_msg, value, to_msg, common_msg)
self.warn(to_native(msg))
return to_native(value, errors='surrogate_or_strict')
def _handle_options(self, argument_spec=None, params=None, prefix=''):
''' deal with options to create sub spec '''
if argument_spec is None:
argument_spec = self.argument_spec
if params is None:
params = self.params
for (k, v) in argument_spec.items():
wanted = v.get('type', None)
if wanted == 'dict' or (wanted == 'list' and v.get('elements', '') == 'dict'):
spec = v.get('options', None)
if v.get('apply_defaults', False):
if spec is not None:
if params.get(k) is None:
params[k] = {}
else:
continue
elif spec is None or k not in params or params[k] is None:
continue
self._options_context.append(k)
if isinstance(params[k], dict):
elements = [params[k]]
else:
elements = params[k]
for idx, param in enumerate(elements):
if not isinstance(param, dict):
self.fail_json(msg="value of %s must be of type dict or list of dict" % k)
new_prefix = prefix + k
if wanted == 'list':
new_prefix += '[%d]' % idx
new_prefix += '.'
self._set_fallbacks(spec, param)
options_aliases = self._handle_aliases(spec, param, option_prefix=new_prefix)
options_legal_inputs = list(spec.keys()) + list(options_aliases.keys())
self._check_arguments(spec, param, options_legal_inputs)
# check exclusive early
if not self.bypass_checks:
self._check_mutually_exclusive(v.get('mutually_exclusive', None), param)
self._set_defaults(pre=True, spec=spec, param=param)
if not self.bypass_checks:
self._check_required_arguments(spec, param)
self._check_argument_types(spec, param, new_prefix)
self._check_argument_values(spec, param)
self._check_required_together(v.get('required_together', None), param)
self._check_required_one_of(v.get('required_one_of', None), param)
self._check_required_if(v.get('required_if', None), param)
self._check_required_by(v.get('required_by', None), param)
self._set_defaults(pre=False, spec=spec, param=param)
# handle multi level options (sub argspec)
self._handle_options(spec, param, new_prefix)
self._options_context.pop()
def _get_wanted_type(self, wanted, k):
if not callable(wanted):
if wanted is None:
# Mostly we want to default to str.
# For values set to None explicitly, return None instead as
# that allows a user to unset a parameter
wanted = 'str'
try:
type_checker = self._CHECK_ARGUMENT_TYPES_DISPATCHER[wanted]
except KeyError:
self.fail_json(msg="implementation error: unknown type %s requested for %s" % (wanted, k))
else:
# set the type_checker to the callable, and reset wanted to the callable's name (or type if it doesn't have one, ala MagicMock)
type_checker = wanted
wanted = getattr(wanted, '__name__', to_native(type(wanted)))
return type_checker, wanted
def _handle_elements(self, wanted, param, values):
type_checker, wanted_name = self._get_wanted_type(wanted, param)
validated_params = []
# Get param name for strings so we can later display this value in a useful error message if needed
# Only pass 'kwargs' to our checkers and ignore custom callable checkers
kwargs = {}
if wanted_name == 'str' and isinstance(wanted, string_types):
if isinstance(param, string_types):
kwargs['param'] = param
elif isinstance(param, dict):
kwargs['param'] = list(param.keys())[0]
for value in values:
try:
validated_params.append(type_checker(value, **kwargs))
except (TypeError, ValueError) as e:
msg = "Elements value for option %s" % param
if self._options_context:
msg += " found in '%s'" % " -> ".join(self._options_context)
msg += " is of type %s and we were unable to convert to %s: %s" % (type(value), wanted_name, to_native(e))
self.fail_json(msg=msg)
return validated_params
def _check_argument_types(self, spec=None, param=None, prefix=''):
''' ensure all arguments have the requested type '''
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
for (k, v) in spec.items():
wanted = v.get('type', None)
if k not in param:
continue
value = param[k]
if value is None:
continue
type_checker, wanted_name = self._get_wanted_type(wanted, k)
# Get param name for strings so we can later display this value in a useful error message if needed
# Only pass 'kwargs' to our checkers and ignore custom callable checkers
kwargs = {}
if wanted_name == 'str' and isinstance(type_checker, string_types):
kwargs['param'] = list(param.keys())[0]
# Get the name of the parent key if this is a nested option
if prefix:
kwargs['prefix'] = prefix
try:
param[k] = type_checker(value, **kwargs)
wanted_elements = v.get('elements', None)
if wanted_elements:
if wanted != 'list' or not isinstance(param[k], list):
msg = "Invalid type %s for option '%s'" % (wanted_name, param)
if self._options_context:
msg += " found in '%s'." % " -> ".join(self._options_context)
msg += ", elements value check is supported only with 'list' type"
self.fail_json(msg=msg)
param[k] = self._handle_elements(wanted_elements, k, param[k])
except (TypeError, ValueError) as e:
msg = "argument %s is of type %s" % (k, type(value))
if self._options_context:
msg += " found in '%s'." % " -> ".join(self._options_context)
msg += " and we were unable to convert to %s: %s" % (wanted_name, to_native(e))
self.fail_json(msg=msg)
def _set_defaults(self, pre=True, spec=None, param=None):
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
for (k, v) in spec.items():
default = v.get('default', None)
if pre is True:
# this prevents setting defaults on required items
if default is not None and k not in param:
param[k] = default
else:
# make sure things without a default still get set None
if k not in param:
param[k] = default
def _set_fallbacks(self, spec=None, param=None):
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
for (k, v) in spec.items():
fallback = v.get('fallback', (None,))
fallback_strategy = fallback[0]
fallback_args = []
fallback_kwargs = {}
if k not in param and fallback_strategy is not None:
for item in fallback[1:]:
if isinstance(item, dict):
fallback_kwargs = item
else:
fallback_args = item
try:
param[k] = fallback_strategy(*fallback_args, **fallback_kwargs)
except AnsibleFallbackNotFound:
continue
def warn(self, warning):
# Copied from ansible.module_utils.common.warnings:
if isinstance(warning, string_types):
self.__warnings.append(warning)
else:
raise TypeError("warn requires a string not a %s" % type(warning))
def deprecate(self, msg, version=None, date=None, collection_name=None):
if version is not None and date is not None:
raise AssertionError("implementation error -- version and date must not both be set")
# Copied from ansible.module_utils.common.warnings:
if isinstance(msg, string_types):
# For compatibility, we accept that neither version nor date is set,
# and treat that the same as if version would haven been set
if date is not None:
self.__deprecations.append({'msg': msg, 'date': date, 'collection_name': collection_name})
else:
self.__deprecations.append({'msg': msg, 'version': version, 'collection_name': collection_name})
else:
raise TypeError("deprecate requires a string not a %s" % type(msg))
def _return_formatted(self, kwargs):
if 'invocation' not in kwargs:
kwargs['invocation'] = {'module_args': self.params}
if 'warnings' in kwargs:
if isinstance(kwargs['warnings'], list):
for w in kwargs['warnings']:
self.warn(w)
else:
self.warn(kwargs['warnings'])
if self.__warnings:
kwargs['warnings'] = self.__warnings
if 'deprecations' in kwargs:
if isinstance(kwargs['deprecations'], list):
for d in kwargs['deprecations']:
if isinstance(d, SEQUENCETYPE) and len(d) == 2:
self.deprecate(d[0], version=d[1])
elif isinstance(d, Mapping):
self.deprecate(d['msg'], version=d.get('version'), date=d.get('date'),
collection_name=d.get('collection_name'))
else:
self.deprecate(d) # pylint: disable=ansible-deprecated-no-version
else:
self.deprecate(kwargs['deprecations']) # pylint: disable=ansible-deprecated-no-version
if self.__deprecations:
kwargs['deprecations'] = self.__deprecations
kwargs = remove_values(kwargs, self.no_log_values)
raise _ModuleExitException(kwargs)
def exit_json(self, **kwargs):
result = dict(kwargs)
if 'failed' not in result:
result['failed'] = False
self._return_formatted(result)
def fail_json(self, msg, **kwargs):
result = dict(kwargs)
result['failed'] = True
result['msg'] = msg
self._return_formatted(result)
@six.add_metaclass(abc.ABCMeta)
class ActionModuleBase(ActionBase):
@abc.abstractmethod
def setup_module(self):
"""Return pair (ArgumentSpec, kwargs)."""
pass
@abc.abstractmethod
def run_module(self, module):
"""Run module code"""
module.fail_json(msg='Not implemented.')
def run(self, tmp=None, task_vars=None):
if task_vars is None:
task_vars = dict()
result = super(ActionModuleBase, self).run(tmp, task_vars)
del tmp # tmp no longer has any effect
try:
argument_spec, kwargs = self.setup_module()
module = argument_spec.create_ansible_module_helper(AnsibleActionModule, (self, ), **kwargs)
self.run_module(module)
raise AnsibleError('Internal error: action module did not call module.exit_json()')
except _ModuleExitException as mee:
result.update(mee.result)
return result
except Exception as dummy:
result['failed'] = True
result['msg'] = 'MODULE FAILURE'
result['exception'] = traceback.format_exc()
return result
class ArgumentSpec:
def __init__(self, argument_spec, mutually_exclusive=None, required_together=None, required_one_of=None, required_if=None, required_by=None):
self.argument_spec = argument_spec
self.mutually_exclusive = mutually_exclusive or []
self.required_together = required_together or []
self.required_one_of = required_one_of or []
self.required_if = required_if or []
self.required_by = required_by or {}
def create_ansible_module_helper(self, clazz, args, **kwargs):
return clazz(
*args,
argument_spec=self.argument_spec,
mutually_exclusive=self.mutually_exclusive,
required_together=self.required_together,
required_one_of=self.required_one_of,
required_if=self.required_if,
required_by=self.required_by,
**kwargs)

View File

@@ -0,0 +1,165 @@
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018 Edoardo Tenani <e.tenani@arduino.cc> (@endorama)
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
name: sops
author: Edoardo Tenani (@endorama) <e.tenani@arduino.cc>
short_description: Loading sops-encrypted vars files
version_added: '0.1.0'
description:
- Load encrypted YAML files into corresponding groups/hosts in group_vars/ and host_vars/ directories.
- Files are encrypted prior to reading, making this plugin an effective companion to host_group_vars plugin.
- Files are restricted to .sops.yaml, .sops.yml, .sops.json extensions.
- Hidden files are ignored.
options:
_valid_extensions:
default: [".sops.yml", ".sops.yaml", ".sops.json"]
description:
- "Check all of these extensions when looking for 'variable' files which should be YAML or JSON or vaulted versions of these."
- 'This affects vars_files, include_vars, inventory and vars plugins among others.'
type: list
elements: string
stage:
version_added: 0.2.0
ini:
- key: vars_stage
section: community.sops
env:
- name: ANSIBLE_VARS_SOPS_PLUGIN_STAGE
cache:
description:
- Whether to cache decrypted files or not.
- If the cache is disabled, the files will be decrypted for almost every task. This is very slow!
- Only disable caching if you modify the variable files during a playbook run and want the updated
result to be available from the next task on.
- "Note that setting I(stage) to C(inventory) has the same effect as setting I(cache) to C(true):
the variables will be loaded only once (during inventory loading) and the vars plugin will not
be called for every task."
type: bool
default: true
version_added: 0.2.0
ini:
- key: vars_cache
section: community.sops
env:
- name: ANSIBLE_VARS_SOPS_PLUGIN_CACHE
_disable_vars_plugin_temporarily:
description:
- Temporarily disable this plugin.
- Useful if ansible-inventory is supposed to be run without decrypting secrets (in AWX for instance).
type: bool
default: false
version_added: 1.3.0
env:
- name: SOPS_ANSIBLE_AWX_DISABLE_VARS_PLUGIN_TEMPORARILY
extends_documentation_fragment:
- ansible.builtin.vars_plugin_staging
- community.sops.sops
- community.sops.sops.ansible_env
- community.sops.sops.ansible_ini
seealso:
- ref: community.sops.sops lookup <ansible_collections.community.sops.sops_lookup>
description: The sops lookup can be used decrypt sops-encrypted files.
# - plugin: community.sops.sops
# plugin_type: lookup
- ref: community.sops.decrypt filter <ansible_collections.community.sops.decrypt_filter>
description: The decrypt filter can be used to descrypt sops-encrypted in-memory data.
# - plugin: community.sops.decrypt
# plugin_type: filter
- module: community.sops.load_vars
'''
import os
from ansible.errors import AnsibleParserError
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
from ansible.plugins.vars import BaseVarsPlugin
from ansible.inventory.host import Host
from ansible.inventory.group import Group
from ansible.utils.vars import combine_vars
from ansible_collections.community.sops.plugins.module_utils.sops import Sops, SopsError
from ansible.utils.display import Display
display = Display()
FOUND = {}
DECRYPTED = {}
DEFAULT_VALID_EXTENSIONS = [".sops.yaml", ".sops.yml", ".sops.json"]
class VarsModule(BaseVarsPlugin):
def get_vars(self, loader, path, entities, cache=None):
''' parses the inventory file '''
if not isinstance(entities, list):
entities = [entities]
super(VarsModule, self).get_vars(loader, path, entities)
def get_option_value(argument_name):
return self.get_option(argument_name)
if cache is None:
cache = self.get_option('cache')
if self.get_option('_disable_vars_plugin_temporarily'):
return {}
data = {}
for entity in entities:
if isinstance(entity, Host):
subdir = 'host_vars'
elif isinstance(entity, Group):
subdir = 'group_vars'
else:
raise AnsibleParserError("Supplied entity must be Host or Group, got %s instead" % (type(entity)))
# avoid 'chroot' type inventory hostnames /path/to/chroot
if not entity.name.startswith(os.path.sep):
try:
found_files = []
# load vars
b_opath = os.path.realpath(to_bytes(os.path.join(self._basedir, subdir)))
opath = to_text(b_opath)
key = '%s.%s' % (entity.name, opath)
self._display.vvvv("key: %s" % (key))
if cache and key in FOUND:
found_files = FOUND[key]
else:
# no need to do much if path does not exist for basedir
if os.path.exists(b_opath):
if os.path.isdir(b_opath):
self._display.debug("\tprocessing dir %s" % opath)
# NOTE: iterating without extension allow retriving files recursively
# A filter is then applied by iterating on all results and filtering by
# extension.
# See:
# - https://github.com/ansible-collections/community.sops/pull/6
found_files = loader.find_vars_files(opath, entity.name, extensions=DEFAULT_VALID_EXTENSIONS, allow_dir=False)
found_files.extend([file_path for file_path in loader.find_vars_files(opath, entity.name)
if any(to_text(file_path).endswith(extension) for extension in DEFAULT_VALID_EXTENSIONS)])
FOUND[key] = found_files
else:
self._display.warning("Found %s that is not a directory, skipping: %s" % (subdir, opath))
for found in found_files:
if cache and found in DECRYPTED:
file_content = DECRYPTED[found]
else:
file_content = Sops.decrypt(found, display=display, get_option_value=get_option_value)
DECRYPTED[found] = file_content
new_data = loader.load(file_content)
if new_data: # ignore empty files
data = combine_vars(data, new_data)
except Exception as e:
raise AnsibleParserError(to_native(e))
return data

View File

@@ -0,0 +1,7 @@
<!--
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: 2022, Felix Fontein
-->
See [the documentation](https://docs.ansible.com/ansible/devel/collections/community/sops/).

View File

@@ -0,0 +1,7 @@
---
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: 2022, Felix Fontein
sops_install_on_localhost: false
sops_become_on_install: true

View File

@@ -0,0 +1,11 @@
---
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: 2022, Felix Fontein
galaxy_info:
standalone: false
description: >
[INTERNAL] Install age (https://github.com/FiloSottile/age/).
dependencies: []

View File

@@ -0,0 +1,64 @@
---
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: 2022, Felix Fontein
- name: Gather required information on localhost
when: sops_install_on_localhost
ansible.builtin.setup:
gather_subset:
- '!all'
- '!min'
- architecture
- distribution
- distribution_major_version
- distribution_version
- os_family
delegate_to: localhost
delegate_facts: true
run_once: true
- vars:
_community_sops_install_age_facts: >-
{{ hostvars['localhost' if sops_install_on_localhost else inventory_hostname].ansible_facts }}
block:
- name: Show system information
ansible.builtin.debug:
msg: |-
Architecture: {{ _community_sops_install_age_facts.architecture }}
Distribution: {{ _community_sops_install_age_facts.distribution }} {{ _community_sops_install_age_facts.distribution_major_version }}
Distribution version: {{ _community_sops_install_age_facts.distribution_version }}
OS family: {{ _community_sops_install_age_facts.os_family }}
- name: Include distribution specific variables
ansible.builtin.include_vars: '{{ lookup("ansible.builtin.first_found", params) }}'
vars:
params:
files:
- >-
D-{{ _community_sops_install_age_facts.distribution }}-{{ _community_sops_install_age_facts.distribution_version }}.yml
- >-
D-{{ _community_sops_install_age_facts.distribution }}-{{ _community_sops_install_age_facts.distribution_major_version }}.yml
- >-
D-{{ _community_sops_install_age_facts.distribution }}.yml
- >-
OS-{{ _community_sops_install_age_facts.os_family }}-{{ _community_sops_install_age_facts.distribution_major_version }}.yml
- >-
OS-{{ _community_sops_install_age_facts.os_family }}.yml
- default.yml
paths:
- '{{ role_path }}/vars'
- name: Install system packages
ansible.builtin.package:
name: '{{ _community_sops_install_age_system_packages }}'
become: '{{ sops_become_on_install }}'
delegate_to: '{{ "localhost" if sops_install_on_localhost else omit }}'
run_once: '{{ sops_install_on_localhost or omit }}'
when: _community_sops_install_age_system_packages | length > 0
- name: Set results
ansible.builtin.set_fact:
age_installed: "{{ _community_sops_install_age_has_age }}"
delegate_to: '{{ "localhost" if sops_install_on_localhost else omit }}'
delegate_facts: '{{ true if sops_install_on_localhost else omit }}'

View File

@@ -0,0 +1,9 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
_community_sops_install_age_system_packages:
- age
_community_sops_install_age_has_age: true

View File

@@ -0,0 +1,9 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
_community_sops_install_age_system_packages:
- age
_community_sops_install_age_has_age: true

View File

@@ -0,0 +1,8 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
_community_sops_install_age_system_packages: []
_community_sops_install_age_has_age: false

View File

@@ -0,0 +1,9 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
_community_sops_install_age_system_packages:
- age
_community_sops_install_age_has_age: true

View File

@@ -0,0 +1,8 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
_community_sops_install_age_system_packages: []
_community_sops_install_age_has_age: false

View File

@@ -0,0 +1,8 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
_community_sops_install_age_system_packages: []
_community_sops_install_age_has_age: false

View File

@@ -0,0 +1,8 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
_community_sops_install_age_system_packages: []
_community_sops_install_age_has_age: false

View File

@@ -0,0 +1,9 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
_community_sops_install_age_system_packages:
- age
_community_sops_install_age_has_age: true

View File

@@ -0,0 +1,8 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
_community_sops_install_age_system_packages: []
_community_sops_install_age_has_age: false

View File

@@ -0,0 +1,7 @@
<!--
GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
SPDX-License-Identifier: GPL-3.0-or-later
SPDX-FileCopyrightText: 2022, Felix Fontein
-->
See [the documentation](https://docs.ansible.com/ansible/devel/collections/community/sops/).

View File

@@ -0,0 +1,10 @@
---
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: 2022, Felix Fontein
sops_version: latest
sops_source: auto
sops_install_on_localhost: false
sops_become_on_install: true
sops_github_latest_detection: auto

View File

@@ -0,0 +1,72 @@
---
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: 2022, Felix Fontein
argument_specs:
main:
short_description: Install Mozilla sops
version_added: 1.5.0
description:
- This role installs L(Mozilla sops,https://github.com/mozilla/sops) and Gnu Privacy Guard (GPG).
- >-
This role supports the following operating systems:
Alpine (new enough),
Arch Linux,
CentOS 7, Stream 8, or newer,
Debian 10 (Buster) or newer,
Fedora (new enough),
RHEL 7 or newer,
Ubuntu 16.04 or newer LTS versions
- The Ansible facts C(ansible_facts.architecture), C(ansible_facts.distribution), C(ansible_facts.distribution_major_version),
C(ansible_facts.distribution_version), and C(ansible_facts.os_family) are expected to be present if I(sops_install_on_localhost) is C(false).
author:
- Felix Fontein (@felixfontein)
options:
sops_version:
default: latest
description:
- The version of sops to install.
- Should be a version like C(3.7.2). The special value C(latest) will select the latest version available form the given source.
type: str
sops_source:
default: auto
description:
- Determines the source from where sops is installed.
- The value C(github) will install sops from the Mozilla sops releases on GitHub (U(https://github.com/mozilla/sops/releases/)).
- The value C(system) will install sops from the system packages. Note that not all system package repositories support sops.
- The value C(auto) will determine the best source to install sops from. Here, system package repositories are preferred over GitHub.
type: str
choices:
- auto
- github
- system
sops_install_on_localhost:
default: false
description:
- Installs sops on the Ansible controller (C(localhost)) instead of the remote host.
type: bool
sops_become_on_install:
default: true
description:
- 'Whether the role should use C(become: true) when installing packages.'
type: bool
sops_github_latest_detection:
description:
- When installing the latest sops version from GitHub, configures how the latest release is detected.
- C(auto) tries C(api) first and then uses C(latest-release).
- C(api) asks the GitHub API for a list of recent releases and picks the highest version.
- C(latest-release) uses a not fully documented URL to retrieve the release marked as "latest" by the repository maintainers.
type: str
choices:
- auto
- api
- latest-release
version_added: 1.6.0
sops_github_token:
description:
- Token to provide when querying the GitHub API for the latest release. Without the token
there are rather strict rate limits.
- Should mainly be used in GitHub Actions.
type: str
version_added: 1.6.0

View File

@@ -0,0 +1,11 @@
---
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: 2022, Felix Fontein
galaxy_info:
standalone: false
description: >
Install Mozilla sops (https://github.com/mozilla/sops).
dependencies: []

View File

@@ -0,0 +1,26 @@
---
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: 2022, Felix Fontein
- name: Check whether system packages are a valid source of sops {{ sops_version }}
when:
- _community_sops_install_system_has_system
- not (sops_version != 'latest' and _community_sops_install_system_has_system_latest_only)
ansible.builtin.set_fact:
_community_sops_install_effective_sops_source: system
- name: Check whether GitHub is a valid source of sops
when:
- _community_sops_install_system_has_github
- _community_sops_install_effective_sops_source == 'auto'
ansible.builtin.set_fact:
_community_sops_install_effective_sops_source: github
- name: Ensure that something was detected
ansible.builtin.fail:
msg: >-
Was not able to determine installation source for sops {{ sops_version }}
for {{ _community_sops_install_facts.distribution }} {{ _community_sops_install_facts.distribution_version }}.
Please open an issue in https://github.com/ansible-collections/community.sops/issues if you think this should work.
when: _community_sops_install_effective_sops_source == 'auto'

View File

@@ -0,0 +1,50 @@
---
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: 2022, Felix Fontein
- name: Make sure that sops can be installed from GitHub
ansible.builtin.fail:
msg: >-
Sops cannot be installed from GitHub for
{{ _community_sops_install_facts.distribution }} {{ _community_sops_install_facts.distribution_version }}.
when: not _community_sops_install_system_has_github
- name: Start determining sops version
ansible.builtin.set_fact:
_community_sops_install_effective_sops_version: '{{ "" if sops_version == "latest" else sops_version }}'
# This method uses the GitHub API, which is rate-limited.
- name: Determine latest version (fallback)
when:
- _community_sops_install_effective_sops_version == ''
- sops_github_latest_detection in ['auto', 'api']
ansible.builtin.include_tasks: github_api.yml
# This method asks GitHub for the latest release, which depends on the release to be
# correctly marked as "latest" in the GitHub UI. Fortunately this is not as aggressively
# rate-limited as the API (used in the fallback).
- name: Determine latest version
when:
- _community_sops_install_effective_sops_version == ''
- sops_github_latest_detection in ['auto', 'latest-release']
ansible.builtin.include_tasks: github_latest_release.yml
- name: Fail when latest version could not be selected
ansible.builtin.fail:
msg: Could not determine the latest GitHub release
when: _community_sops_install_effective_sops_version == ''
- name: Show selected version
ansible.builtin.debug:
msg: The latest sops version is sops {{ _community_sops_install_effective_sops_version }}.
when: sops_version == 'latest'
- name: Set variables
ansible.builtin.set_fact:
_community_sops_install_system_packages_actual: >-
{{ _community_sops_install_system_packages + _community_sops_install_system_packages_github }}
_community_sops_install_system_packages_unsigned_actual: >-
{{ _community_sops_install_system_packages_unsigned + _community_sops_install_system_packages_unsigned_github }}
_community_sops_install_system_package_deb_actual: >-
{{ _community_sops_install_system_package_deb_github }}

View File

@@ -0,0 +1,38 @@
---
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: 2022, Felix Fontein
- name: Fetch list of releases from GitHub
ansible.builtin.uri:
headers:
Accept: application/vnd.github+json
Authorization: "{{ ('Bearer ' ~ sops_github_token) if sops_github_token is defined and sops_github_token else '' }}"
status_code:
- 200
- 403 # "HTTP Error 403: rate limit exceeded"
url: https://api.github.com/repos/mozilla/sops/releases
register: _community_sops_install_github_releases
delegate_to: localhost
run_once: true
- name: In case rate limit was exceeded, inform user
ansible.builtin.debug:
msg: >-
Rate limit exceeded! Make sure to provide a GitHub token
as `sops_github_token` to reduce the chance of this error.
when: _community_sops_install_github_releases.status == 403
- name: Determine the latest release
ansible.builtin.set_fact:
_community_sops_install_effective_sops_version: >-
{{
(
_community_sops_install_github_releases.json
| rejectattr("prerelease")
| rejectattr("draft")
| map(attribute="tag_name")
| map("ansible.builtin.regex_replace", "^v", "")
| community.sops._latest_version
) if _community_sops_install_github_releases.status == 200 else ''
}}

View File

@@ -0,0 +1,34 @@
---
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: 2022, Felix Fontein
- name: Fetch the latest release from GitHub
ansible.builtin.uri:
follow_redirects: false
status_code:
- 302
- 307
url: https://github.com/mozilla/sops/releases/latest/
register: _community_sops_install_github_latest_release
delegate_to: localhost
run_once: true
- name: Determine the latest release
ansible.builtin.set_fact:
_community_sops_install_effective_sops_version: >-
{{
_community_sops_install_github_latest_release.location
| default("", true)
| ansible.builtin.regex_search("(?<=/releases/tag/)([0-9a-z._-]+)")
| default("", true)
| ansible.builtin.regex_replace("^v", "")
}}
- name: In case this failed, inform user
ansible.builtin.debug:
msg: >-
Could not obtain latest version from https://github.com/mozilla/sops/releases/latest/.
Please create an issue in https://github.com/ansible-collections/community.sops/issues/
if there is not already one.
when: _community_sops_install_effective_sops_version == ''

View File

@@ -0,0 +1,100 @@
---
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: 2022, Felix Fontein
- name: Gather required information on localhost
when: sops_install_on_localhost
ansible.builtin.setup:
gather_subset:
- '!all'
- '!min'
- architecture
- distribution
- distribution_major_version
- distribution_version
- os_family
delegate_to: localhost
delegate_facts: true
run_once: true
- vars:
_community_sops_install_facts: >-
{{ hostvars['localhost' if sops_install_on_localhost else inventory_hostname].ansible_facts }}
block:
- name: Show system information
ansible.builtin.debug:
msg: |-
Architecture: {{ _community_sops_install_facts.architecture }}
Distribution: {{ _community_sops_install_facts.distribution }} {{ _community_sops_install_facts.distribution_major_version }}
Distribution version: {{ _community_sops_install_facts.distribution_version }}
OS family: {{ _community_sops_install_facts.os_family }}
- name: Include distribution specific variables
ansible.builtin.include_vars: '{{ lookup("ansible.builtin.first_found", params) }}'
vars:
params:
files:
- >-
D-{{ _community_sops_install_facts.distribution }}-{{ _community_sops_install_facts.distribution_version }}.yml
- >-
D-{{ _community_sops_install_facts.distribution }}-{{ _community_sops_install_facts.distribution_major_version }}.yml
- >-
D-{{ _community_sops_install_facts.distribution }}.yml
- >-
OS-{{ _community_sops_install_facts.os_family }}-{{ _community_sops_install_facts.distribution_major_version }}.yml
- >-
OS-{{ _community_sops_install_facts.os_family }}.yml
- default.yml
paths:
- '{{ role_path }}/vars'
- name: Start determining source
ansible.builtin.set_fact:
_community_sops_install_effective_sops_source: '{{ sops_source }}'
- name: Auto-detect source to install sops from
ansible.builtin.include_tasks: detect_source.yml
when: _community_sops_install_effective_sops_source == 'auto'
- name: Install Mozilla sops from GitHub
ansible.builtin.include_tasks: github.yml
when: _community_sops_install_effective_sops_source == 'github'
- name: Install Mozilla sops from system package repositories
ansible.builtin.include_tasks: system.yml
when: _community_sops_install_effective_sops_source == 'system'
- name: Install system packages
ansible.builtin.package:
name: '{{ _community_sops_install_system_packages_actual }}'
allow_downgrade: '{{ true if _community_sops_install_allow_downgrade and sops_version != "latest" else omit }}'
become: '{{ sops_become_on_install }}'
delegate_to: '{{ "localhost" if sops_install_on_localhost else omit }}'
run_once: '{{ sops_install_on_localhost or omit }}'
when: _community_sops_install_system_packages_actual | length > 0
- name: Install unsigned system packages
ansible.builtin.package:
name: '{{ _community_sops_install_system_packages_unsigned_actual }}'
allow_downgrade: '{{ true if _community_sops_install_allow_downgrade and sops_version != "latest" else omit }}'
disable_gpg_check: true
become: '{{ sops_become_on_install }}'
delegate_to: '{{ "localhost" if sops_install_on_localhost else omit }}'
run_once: '{{ sops_install_on_localhost or omit }}'
when: _community_sops_install_system_packages_unsigned_actual | length > 0
- name: Install packages from URL/path (Debian)
ansible.builtin.apt:
deb: '{{ _community_sops_install_system_package_deb_actual }}'
allow_downgrade: '{{ true if _community_sops_install_allow_downgrade and sops_version != "latest" else omit }}'
become: '{{ sops_become_on_install }}'
delegate_to: '{{ "localhost" if sops_install_on_localhost else omit }}'
run_once: '{{ sops_install_on_localhost or omit }}'
when: _community_sops_install_system_package_deb_actual is string
- name: Set results
ansible.builtin.set_fact:
sops_installed: true
delegate_to: '{{ "localhost" if sops_install_on_localhost else omit }}'
delegate_facts: '{{ true if sops_install_on_localhost else omit }}'

View File

@@ -0,0 +1,26 @@
---
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: 2022, Felix Fontein
- name: Make sure that sops can be installed from system packages
ansible.builtin.fail:
msg: >-
Sops cannot be installed from system packages for
{{ _community_sops_install_facts.distribution }} {{ _community_sops_install_facts.distribution_version }}.
when: not _community_sops_install_system_has_system
- name: Make sure that systems only supporting 'latest' are not told to install another version
ansible.builtin.fail:
msg: >-
Sops version {{ sops_version }} was requested, but we can only install latest sops from system packages.
when: sops_version != 'latest' and _community_sops_install_system_has_system_latest_only
- name: Set variables
ansible.builtin.set_fact:
_community_sops_install_system_packages_actual: >-
{{ _community_sops_install_system_packages + _community_sops_install_system_packages_system }}
_community_sops_install_system_packages_unsigned_actual: >-
{{ _community_sops_install_system_packages_unsigned + _community_sops_install_system_packages_unsigned_system }}
_community_sops_install_system_package_deb_actual: >-
{{ _community_sops_install_system_package_deb_system }}

View File

@@ -0,0 +1,23 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
_community_sops_install_system_has_system: true
_community_sops_install_system_has_system_latest_only: true
_community_sops_install_system_has_github: false
_community_sops_install_allow_downgrade: false
_community_sops_install_system_packages:
- gpg
_community_sops_install_system_packages_unsigned: []
_community_sops_install_system_package_deb_github: false
_community_sops_install_system_packages_github: []
_community_sops_install_system_packages_unsigned_github: []
_community_sops_install_system_package_deb_system: false
_community_sops_install_system_packages_system:
- sops
_community_sops_install_system_packages_unsigned_system: []

View File

@@ -0,0 +1,23 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
_community_sops_install_system_has_system: true
_community_sops_install_system_has_system_latest_only: true
_community_sops_install_system_has_github: false
_community_sops_install_allow_downgrade: false
_community_sops_install_system_packages:
- gnupg
_community_sops_install_system_packages_unsigned: []
_community_sops_install_system_package_deb_github: false
_community_sops_install_system_packages_github: []
_community_sops_install_system_packages_unsigned_github: []
_community_sops_install_system_package_deb_system: false
_community_sops_install_system_packages_system:
- sops
_community_sops_install_system_packages_unsigned_system: []

View File

@@ -0,0 +1,31 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
_community_sops_install_system_has_system: false
_community_sops_install_system_has_system_latest_only: true
_community_sops_install_system_has_github: true
_community_sops_install_allow_downgrade: '{{ ansible_version.full is version("2.12", ">=") }}'
_community_sops_install_system_packages:
- gnupg
_community_sops_install_system_packages_unsigned: []
_community_sops_install_arch_transform:
x86_64: amd64
_community_sops_install_system_package_deb_github: >-
https://github.com/mozilla/sops/releases/download/v{{
_community_sops_install_effective_sops_version
}}/sops_{{
_community_sops_install_effective_sops_version
}}_{{
_community_sops_install_arch_transform.get(ansible_facts.architecture, ansible_facts.architecture)
}}.deb
_community_sops_install_system_packages_github: []
_community_sops_install_system_packages_unsigned_github: []
_community_sops_install_system_package_deb_system: false
_community_sops_install_system_packages_system: []
_community_sops_install_system_packages_unsigned_system: []

View File

@@ -0,0 +1,32 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
_community_sops_install_system_has_system: false
_community_sops_install_system_has_system_latest_only: true
_community_sops_install_system_has_github: true
_community_sops_install_allow_downgrade: true
_community_sops_install_system_packages:
- gnupg2
_community_sops_install_system_packages_unsigned: []
_community_sops_install_system_package_deb_github: false
_community_sops_install_system_packages_github: []
_community_sops_install_system_packages_unsigned_github:
- >-
https://github.com/mozilla/sops/releases/download/v{{
_community_sops_install_effective_sops_version
}}/sops-{{
(_community_sops_install_effective_sops_version is version('3.6.0', '<')) | ternary('v', '')
}}{{
_community_sops_install_effective_sops_version
}}-1.{{
ansible_facts.architecture
}}.rpm
_community_sops_install_system_package_deb_system: false
_community_sops_install_system_packages_system: []
_community_sops_install_system_packages_unsigned_system: []

View File

@@ -0,0 +1,21 @@
---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
_community_sops_install_system_has_system: false
_community_sops_install_system_has_system_latest_only: true
_community_sops_install_system_has_github: false
_community_sops_install_allow_downgrade: false
_community_sops_install_system_packages: []
_community_sops_install_system_packages_unsigned: []
_community_sops_install_system_package_deb_github: false
_community_sops_install_system_packages_github: []
_community_sops_install_system_packages_unsigned_github: []
_community_sops_install_system_package_deb_system: false
_community_sops_install_system_packages_system: []
_community_sops_install_system_packages_unsigned_system: []