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,494 @@
================================
theforeman.foreman Release Notes
================================
.. contents:: Topics
This changelog describes changes after version 0.8.1.
v3.8.0
======
Minor Changes
-------------
- job_template - add ``default`` option to the ``template_inputs`` parameter
- location, organization - add ``ignore_types`` parameter to adjust automatic association of resources
- redhat_manifest - Search by UUID on the server side if UUID is known. This is faster and allows fetching of manifest in big accounts (>1000 allocations).
- redhat_manifest - return the UUID of the manifest so it can be reused later
- redhat_manifest - set default ``quantity`` to 1 (https://github.com/theforeman/foreman-ansible-modules/pull/1499)
Bugfixes
--------
- activation_key - properly fetch *all* repositories when managing content overrides (https://bugzilla.redhat.com/show_bug.cgi?id=2134605)
- redhat_manifest - properly report http errors (https://github.com/theforeman/foreman-ansible-modules/issues/1497)
- repository_sync - report an error instead of syncing the whole product when the repository could not be found
New Modules
-----------
- theforeman.foreman.snapshot_info - Fetch information about Foreman Snapshots
v3.7.0
======
Minor Changes
-------------
- repository - add support for ``include_tags`` and ``exclude_tags`` parameters for Katello 4.4+
- subscription_manifest - increase the import timeout to 10 minutes (https://github.com/theforeman/foreman-ansible-modules/issues/1474)
- sync_plans role - document the ``enabled`` parameter (https://github.com/theforeman/foreman-ansible-modules/issues/1477)
- sync_plans role - expose the ``state`` parameter of the underlying module, thus allowing to delete plans (https://github.com/theforeman/foreman-ansible-modules/issues/1477)
Bugfixes
--------
- Properly use FQCN notation when redirecting the old ``foreman_*`` and ``katello_*`` module names. (https://github.com/theforeman/foreman-ansible-modules/issues/1484)
- convert2rhel role - Content views for activation keys (https://bugzilla.redhat.com/2118790)
v3.6.0
======
New Modules
-----------
- theforeman.foreman.content_export_repository - Manage repository content exports
- theforeman.foreman.content_export_version - Manage content view version content exports
v3.5.0
======
Minor Changes
-------------
- add execution environment metadata
- installation_medium, operatingsystem, partition_table - add ``Fcos``, ``Rhcos``, ``VRP`` OS families
- job_template - add ``hidden_value`` to ``template_inputs`` parameters
- job_template - allow ``value_type`` to be ``resource``
- operatingsystems role - make ``provisioning_template`` parameter optional
- repositories role - add ``ansible_collection_requirements``
- repositories role - add ``arch`` and ``os_versions`` parameters
- repositories role - support ``mirroring_policy``
- repository, smart_proxy - document deprecation/removal status of ``download_policy=background``
- setting - the ``foreman_setting`` return entry is deprecated and kept for backwards compatibility, please use ``entity`` as with any other module
- smart_proxy - add ``inherit`` to possible values of ``download_policy`` (https://github.com/theforeman/foreman-ansible-modules/issues/1438)
- smart_proxy - add ``streamed`` download policy
- snapshot - add include_ram option when creating VMWare snapshot
New Modules
-----------
- theforeman.foreman.content_export_info - List pulp3 content exports
- theforeman.foreman.content_export_library - Manage content exports
- theforeman.foreman.discovery_rule - Manage Host Discovery Rules
v3.4.0
======
Minor Changes
-------------
- add support for module defaults groups for Ansible core 2.12 (https://github.com/theforeman/foreman-ansible-modules/issues/1015)
- all modules - report smaller diffs by dropping ``null`` values. This should result in not showing fields that were unset to begin with, and mark fields that were explicitly removed as "deleted" instead of "replaced by ``null``"
- compute_resource - update libvirt examples (https://bugzilla.redhat.com/show_bug.cgi?id=1990119)
- content_view - add support to set label during creation.
- repository - add ``rhel-9`` to os version filter choices
- repository - add support for ``mirroring_policy`` for Katello 4.4+ (https://github.com/theforeman/foreman-ansible-modules/issues/1388)
Bugfixes
--------
- content_upload - properly detect SRPMs and ensure idempotency during uploads (https://github.com/theforeman/foreman-ansible-modules/issues/1274)
- inventory plugin - fix caching for Report API (https://github.com/theforeman/foreman-ansible-modules/issues/1246)
- operatingsystem - find operatingsystems by title or full (name,major,minor) tuple (https://github.com/theforeman/foreman-ansible-modules/issues/1401)
- os_default_template, provisioning_template - don't document invalid template kind ``ptable`` (https://bugzilla.redhat.com/show_bug.cgi?id=1970132)
v3.3.0
======
Minor Changes
-------------
- content_upload - add support for OSTree content uploads (https://github.com/theforeman/foreman-ansible-modules/issues/628, https://projects.theforeman.org/issues/33299)
- os_default_template, provisioning_template - add ``host_init_config`` to list of possible template types
v3.2.0
======
Minor Changes
-------------
- new ``auth_sources_ldap`` role to manage LDAP authentication sources
Bugfixes
--------
- content_upload - clarify that ``src`` refers to a remote file (https://bugzilla.redhat.com/show_bug.cgi?id=2055416)
v3.1.0
======
Minor Changes
-------------
- Warn if the user tries to use a plain HTTP server URL and fail if the URL is neither HTTPS nor HTTP.
- new ``compute_profiles`` role to manage compute profiles
- new ``compute_resources`` role to manage compute resources
- new ``content_view_publish`` role to publish a list of content views (https://github.com/theforeman/foreman-ansible-modules/issues/1209)
- new ``domains`` role to manage domains
- new ``operatingsystems`` role to manage operating systems
- new ``provisioning_templates`` role to manage provisioning templates
- new ``settings`` role to manage settings
- new ``subnets`` role to manage subnets
- repository - new ``download_concurrency`` parameter (https://github.com/theforeman/foreman-ansible-modules/issues/1273)
Bugfixes
--------
- callback plugin - include timezone information in the callback reported data (https://github.com/theforeman/foreman-ansible-modules/issues/1171)
- hostgroup, location - don't fail when trying to delete a Hostgroup or Location where the parent is already absent
- inventory plugin - fetch *all* facts, not only the first 250, when using the old Hosts API
v3.0.0
======
Minor Changes
-------------
- Add a role `convert2rhel` to perform setup for converting systems to RHEL
- inventory plugin - enable certificate validation by default
- repository - add ``arch`` parameter to limit architectures of the repository (https://github.com/theforeman/foreman-ansible-modules/issues/1265)
Breaking Changes / Porting Guide
--------------------------------
- Set use_reports_api default value to true for the inventory plugin
- Support for Ansible 2.8 is removed
Bugfixes
--------
- host, hostgroup - fix updating puppetclasses while also updating description (or other string-like attributes) (https://github.com/theforeman/foreman-ansible-modules/issues/1231)
v2.2.0
======
Minor Changes
-------------
- repository - add support for filtering repositories by OS version based on API feature apidoc/v2/repositories/create.html
Bugfixes
--------
- host, hostgroup - don't accidentally duplicate ``kt_activation_keys`` param (https://github.com/theforeman/foreman-ansible-modules/issues/1268)
v2.1.2
======
Bugfixes
--------
- activation_key - submit organization_id when querying subs, required for Katello 4.1
- content_view_version_cleanup - sort content view versions before deleting (https://github.com/RedHatSatellite/satellite-ansible-collection/issues/30, https://bugzilla.redhat.com/show_bug.cgi?id=1980274)
- content_view_version_cleanup role - properly clean up when users set keep=0 (https://bugzilla.redhat.com/show_bug.cgi?id=1974314)
- host, compute_profile - when resolving cluster and other values in vm_attrs, compare them as strings (https://github.com/theforeman/foreman-ansible-modules/issues/1245)
- subscription_info - mark ``organization`` parameter as required, to match Katello
v2.1.1
======
Bugfixes
--------
- external_usergroup - always lookup the ID of the usergroup, instead of passing the name to the API (https://bugzilla.redhat.com/show_bug.cgi?id=1967649)
- host, hostgroup - don't override already set parameters when passing an activation key only (and vice versa) (https://bugzilla.redhat.com/show_bug.cgi?id=1967904)
v2.1.0
======
Minor Changes
-------------
- Add a domain_info module
- Add a hostgroups role (https://github.com/theforeman/foreman-ansible-modules/issues/1116)
- Add a role `content_rhel` to perform basic setup for registering and syncing RHEL content hosts
- Add content credentials role
- callback plugin - collect facts during the run, merge them correctly and upload them once at the end
- compute_resource - add ``cloud`` param for the AzureRm provider, to select which Azure cloud to use
- compute_resource - add ``sub_id`` parameter for handling the Azure Subscription ID instead of the ``user`` parameter
- host - Add ``Redfish`` to list of possible BMC providers of an interface
- host, compute_profile - look up the correct id for storage pods and domains given as part of ``volumes_attributes`` (https://bugzilla.redhat.com/show_bug.cgi?id=1885234)
- hostgroup - add a ``ansible_roles`` parameter (https://github.com/theforeman/foreman-ansible-modules/issues/1123)
- new ``content_views`` role to manage content views (https://github.com/theforeman/foreman-ansible-modules/issues/1111)
- new ``organizations`` role to manage organizations (https://github.com/theforeman/foreman-ansible-modules/issues/1109)
- subnet - add ``bmc_proxy`` parameter to configure BMC proxies for subnets
Bugfixes
--------
- host - pass the right image id to the compute resource when creating a host (https://github.com/theforeman/foreman-ansible-modules/issues/1160, https://bugzilla.redhat.com/show_bug.cgi?id=1911670)
New Modules
-----------
- theforeman.foreman.content_view_info - Fetch information about Content Views
- theforeman.foreman.content_view_version_info - Fetch information about Content Views
- theforeman.foreman.domain_info - Fetch information about Domains
- theforeman.foreman.host_errata_info - Fetch information about Host Errata
- theforeman.foreman.repository_set_info - Fetch information about Red Hat Repositories
- theforeman.foreman.setting_info - Fetch information about Settings
- theforeman.foreman.subnet_info - Fetch information about Subnets
- theforeman.foreman.subscription_info - Fetch information about Subscriptions
v2.0.1
======
Bugfixes
--------
- host - don't filter ``false`` values for ``interfaces_attributes`` (https://github.com/theforeman/foreman-ansible-modules/issues/1148)
- host_info, repository_info - correctly fetch all entities when neither ``name`` nor ``search`` is set
- host_info, repository_info - enforce mutual exclusivity of ``name`` and ``search``
v2.0.0
======
Minor Changes
-------------
- Add a role `activation_keys` to manage activation keys
- Add a role `lifecycle_environments` to manage lifecycle environments
- Add a role `repositories` to manage products, repositories, and repository_sets
- Add a role `sync_plans` to manage sync plans
- activation_key - add support for selecting subscriptions by ``upstream_pool_id``
- compute_resource - add ``set_console_password``, ``keyboard_layout`` and ``public_key`` parameters (https://github.com/theforeman/foreman-ansible-modules/issues/1052)
- host - clarify that ``owner`` refers to a users login, not their full name (https://github.com/theforeman/foreman-ansible-modules/issues/1045)
- host - look up the correct network id for a network given as part of ``interfaces_attributes`` (https://github.com/theforeman/foreman-ansible-modules/issues/1104)
- host, hostgroup - add ``activation_keys`` parameter to ease configuring activation keys for deploments
Breaking Changes / Porting Guide
--------------------------------
- All role variables are now prefixed with ``foreman_`` to avoid clashes with similarly named variables from roles outside this collection.
Bugfixes
--------
- content_view_version - make the ``version`` parameter not fail when the version was entered without a minor part (https://github.com/theforeman/foreman-ansible-modules/issues/1087)
- host - allow moving hosts between Organizations and Locations (https://bugzilla.redhat.com/show_bug.cgi?id=1901716)
- host - fix subnet/domain assignment when multiple interfaces are defined (https://github.com/theforeman/foreman-ansible-modules/issues/1095)
- host, hostgroup - select kickstart_repository based on lifecycle_environment and content_view if those are set (https://github.com/theforeman/foreman-ansible-modules/issues/1090, https://bugzilla.redhat.com/1915872)
- resource_info - correctly show the exact resource when passing ``id`` in ``params``
New Modules
-----------
- theforeman.foreman.host_info - Fetch information about Hosts
- theforeman.foreman.puppetclasses_import - Import Puppet Classes from a Proxy
- theforeman.foreman.repository_info - Fetch information about Repositories
v1.5.0
======
Minor Changes
-------------
- content_upload - use ``to_native`` to decode RPM headers if needed (RPM 4.15+ returns strings)
- content_view_version - provide examples how to obtain detailed information about content view versions (https://bugzilla.redhat.com/show_bug.cgi?id=1868145)
- content_view_version_cleanup - new role for cleaning up unused content view versions (https://github.com/theforeman/foreman-ansible-modules/issues/497)
- host - allow management of interfaces (https://github.com/theforeman/foreman-ansible-modules/issues/757)
- inventory plugin - add support for the Report API present in Foreman 1.24 and later
- inventory plugin - allow to compose the ``inventory_hostname`` (https://github.com/theforeman/foreman-ansible-modules/issues/1070)
- manifest - new role for easier handling of subscription manifest workflows
- subnet - add new ``externalipam_group`` parameter
- update vendored ``apypie`` to 0.3.2
Bugfixes
--------
- content_upload - Fix upload of files bigger than 2MB in Pulp3-based setups (https://github.com/theforeman/foreman-ansible-modules/issues/1043)
- job_invocation - properly submit ``ssh``, ``recurrence``, ``scheduling`` and ``concurrency_control`` to the server
- repository - don't emit a false warning about ``organization_id`` not being supported by the server (https://github.com/theforeman/foreman-ansible-modules/issues/1055)
- repository_set, repository - clarify documentation which module should be used for Red Hat Repositories (https://github.com/theforeman/foreman-ansible-modules/issues/1059)
v1.4.0
======
Minor Changes
-------------
- global_parameter - allow to set hidden flag (https://github.com/theforeman/foreman-ansible-modules/issues/1024)
- job_template - stricter validation of ``template_inputs`` sub-options
- redhat_manifest - allow configuring content access mode (https://github.com/theforeman/foreman-ansible-modules/issues/820)
- subnet - verify the server has the ``remote_execution`` plugin when specifying ``remote_execution_proxies``
- the ``apypie`` library is vendored inside the collection, so users only have to install ``requests`` manually now.
Bugfixes
--------
- Don't try to update an entity, if only parameters that aren't supported by the server are detected as changed. (https://github.com/theforeman/foreman-ansible-modules/issues/975)
- allow to pass an empty string when refering to entities, thus unsetting the value (https://github.com/theforeman/foreman-ansible-modules/issues/969)
- compute_profile - don't fail when trying to update compute attributes of a profile (https://github.com/theforeman/foreman-ansible-modules/issues/997)
- host, hostgroup - support ``None`` as the ``pxe_loader`` (https://github.com/theforeman/foreman-ansible-modules/issues/971)
- job_template - don't fail when trying to update template_inputs
- os_default_template - document possible template kind choices (https://bugzilla.redhat.com/show_bug.cgi?id=1889952)
- smart_class_parameters - don't fail when trying to update override_values
New Modules
-----------
- theforeman.foreman.job_invocation - Invoke Remote Execution Jobs
- theforeman.foreman.smart_proxy - Manage Smart Proxies
v1.3.0
======
Minor Changes
-------------
- external_usergroup - rename the ``auth_source_ldap`` parameter to ``auth_source`` (``auth_source_ldap`` is still supported via an alias)
- server URL and credentials can now also be specified using environment variables (https://github.com/theforeman/foreman-ansible-modules/issues/837)
- subnet - add support for external IPAM (https://github.com/theforeman/foreman-ansible-modules/issues/966)
Bugfixes
--------
- content_view - remove CVs from lifecycle environments before deleting them (https://bugzilla.redhat.com/show_bug.cgi?id=1875314)
- external_usergroup - support non-LDAP external groups (https://github.com/theforeman/foreman-ansible-modules/issues/956)
- host - properly scope image lookups by the compute resource (https://bugzilla.redhat.com/show_bug.cgi?id=1878693)
- inventory plugin - include empty parent groups in the inventory (https://github.com/theforeman/foreman-ansible-modules/issues/919)
New Modules
-----------
- theforeman.foreman.status_info - Get status info
v1.2.0
======
Minor Changes
-------------
- compute_resource - added ``caching_enabled`` option for VMware compute resources
- domain, host, hostgroup, operatingsystem, subnet - manage parameters in a single API call (https://bugzilla.redhat.com/show_bug.cgi?id=1855008)
- host - add ``compute_attributes`` parameter to module (https://bugzilla.redhat.com/show_bug.cgi?id=1871815)
- provisioning_template - update list of possible template kinds (https://bugzilla.redhat.com/show_bug.cgi?id=1871978)
- repository - update supported parameters (https://github.com/theforeman/foreman-ansible-modules/issues/935)
Bugfixes
--------
- image - fix quoting of search values (https://github.com/theforeman/foreman-ansible-modules/issues/927)
v1.1.0
======
Minor Changes
-------------
- activation_key - add ``description`` parameter (https://github.com/theforeman/foreman-ansible-modules/issues/915)
- callback plugin - add reporter to report logs sent to Foreman (https://github.com/theforeman/foreman-ansible-modules/issues/836)
- document return values of modules (https://github.com/theforeman/foreman-ansible-modules/pull/901)
- inventory plugin - allow to control batch size when pulling hosts from Foreman (https://github.com/theforeman/foreman-ansible-modules/pull/865)
- subnet - Require mask/cidr only on ipv4 (https://github.com/theforeman/foreman-ansible-modules/issues/878)
Bugfixes
--------
- inventory plugin - fix want_params handling (https://github.com/theforeman/foreman-ansible-modules/issues/847)
New Modules
-----------
- theforeman.foreman.http_proxy - Manage HTTP Proxies
v1.0.1
======
Release Summary
---------------
Documentation fixes to reflect the correct module names.
v1.0.0
======
Release Summary
---------------
This is the first stable release of the ``theforeman.foreman`` collection.
Breaking Changes / Porting Guide
--------------------------------
- All modules were renamed to drop the ``foreman_`` and ``katello_`` prefixes.
Additionally to the prefix removal, the following modules were further ranamed:
* katello_upload to content_upload
* katello_sync to repository_sync
* katello_manifest to subscription_manifest
* foreman_search_facts to resource_info
* foreman_ptable to partition_table
* foreman_model to hardware_model
* foreman_environment to puppet_environment
New Modules
-----------
- theforeman.foreman.activation_key - Manage Activation Keys
- theforeman.foreman.architecture - Manage Architectures
- theforeman.foreman.auth_source_ldap - Manage LDAP Authentication Sources
- theforeman.foreman.bookmark - Manage Bookmarks
- theforeman.foreman.compute_attribute - Manage Compute Attributes
- theforeman.foreman.compute_profile - Manage Compute Profiles
- theforeman.foreman.compute_resource - Manage Compute Resources
- theforeman.foreman.config_group - Manage (Puppet) Config Groups
- theforeman.foreman.content_credential - Manage Content Credentials
- theforeman.foreman.content_upload - Upload content to a repository
- theforeman.foreman.content_view - Manage Content Views
- theforeman.foreman.content_view_filter - Manage Content View Filters
- theforeman.foreman.content_view_version - Manage Content View Versions
- theforeman.foreman.domain - Manage Domains
- theforeman.foreman.external_usergroup - Manage External User Groups
- theforeman.foreman.global_parameter - Manage Global Parameters
- theforeman.foreman.hardware_model - Manage Hardware Models
- theforeman.foreman.host - Manage Hosts
- theforeman.foreman.host_collection - Manage Host Collections
- theforeman.foreman.host_power - Manage Power State of Hosts
- theforeman.foreman.hostgroup - Manage Hostgroups
- theforeman.foreman.image - Manage Images
- theforeman.foreman.installation_medium - Manage Installation Media
- theforeman.foreman.job_template - Manage Job Templates
- theforeman.foreman.lifecycle_environment - Manage Lifecycle Environments
- theforeman.foreman.location - Manage Locations
- theforeman.foreman.operatingsystem - Manage Operating Systems
- theforeman.foreman.organization - Manage Organizations
- theforeman.foreman.os_default_template - Manage Default Template Associations To Operating Systems
- theforeman.foreman.partition_table - Manage Partition Table Templates
- theforeman.foreman.product - Manage Products
- theforeman.foreman.provisioning_template - Manage Provisioning Templates
- theforeman.foreman.puppet_environment - Manage Puppet Environments
- theforeman.foreman.realm - Manage Realms
- theforeman.foreman.redhat_manifest - Interact with a Red Hat Satellite Subscription Manifest
- theforeman.foreman.repository - Manage Repositories
- theforeman.foreman.repository_set - Enable/disable Repositories in Repository Sets
- theforeman.foreman.repository_sync - Sync a Repository or Product
- theforeman.foreman.resource_info - Gather information about resources
- theforeman.foreman.role - Manage Roles
- theforeman.foreman.scap_content - Manage SCAP content
- theforeman.foreman.scap_tailoring_file - Manage SCAP Tailoring Files
- theforeman.foreman.scc_account - Manage SUSE Customer Center Accounts
- theforeman.foreman.scc_product - Subscribe SUSE Customer Center Account Products
- theforeman.foreman.setting - Manage Settings
- theforeman.foreman.smart_class_parameter - Manage Smart Class Parameters
- theforeman.foreman.snapshot - Manage Snapshots
- theforeman.foreman.subnet - Manage Subnets
- theforeman.foreman.subscription_manifest - Manage Subscription Manifests
- theforeman.foreman.sync_plan - Manage Sync Plans
- theforeman.foreman.templates_import - Sync Templates from a repository
- theforeman.foreman.user - Manage Users
- theforeman.foreman.usergroup - Manage User Groups

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@@ -0,0 +1,120 @@
{
"collection_info": {
"namespace": "theforeman",
"name": "foreman",
"version": "3.8.0",
"authors": [
"Adam R\u016f\u017ei\u010dka <aruzicka@redhat.com>",
"AlanCoding <arominge@redhat.com>",
"Andrew Kofink <ajkofink@gmail.com>",
"Anthony Green <green@moxielogic.com>",
"Anton <nesanton@gmail.com>",
"Baptiste Agasse <baptiste.agasse@gmail.com>",
"Bernhard Hopfenm\u00fcller <hopfenmueller@atix.de>",
"Bernhard Suttner <sbernhard@users.noreply.github.com>",
"Bryan Kearney <bkearney@redhat.com>",
"Chris Forkner <gen2fish@gmail.com>",
"Chris Hindman <chindman@chindman.remote.csb>",
"Chris Snell <chsnell@users.noreply.github.com>",
"Christoffer Reijer <ephracis@gmail.com>",
"Dave Thomas <11580510+dthomastx@users.noreply.github.com>",
"Deric Crago <deric.crago@gmail.com>",
"Eric D. Helms <ericdhelms@gmail.com>",
"Eric L <ericzolf@users.noreply.github.com>",
"Ethan <smithe2413@gmail.com>",
"Evgeni Golov <evgeni@golov.de>",
"Ewoud Kohl van Wijngaarden <ewoud@kohlvanwijngaarden.nl>",
"Felix Fontein <felix@fontein.de>",
"Gerald Vogt <gvde@users.noreply.github.com>",
"Greg Swift <gregswift@gmail.com>",
"Griffin Sullivan <gsulliva@redhat.com>",
"Hideki Saito <saito@fgrep.org>",
"Ismael Puerto <ismaelpuerto@users.noreply.github.com>",
"Jameer Pathan <jpathan@redhat.com>",
"James Jeffers <jjeffers@redhat.com>",
"James Stuart <james@stuart.name>",
"Jeffrey van Pelt <jeff@vanpelt.one>",
"Jeremy Albinet <jalbinet@scaleway.com>",
"Jeremy Lenz <jlenz@redhat.com>",
"Jesper Reenberg <jesper.reenberg@gmail.com>",
"John Berninger <john.berninger@gmail.com>",
"Josh Swanson <jswanson@redhat.com>",
"Kenny Tordeurs <ktordeur@redhat.com>",
"Kirill Shirinkin <fodojyko@gmail.com>",
"Leos Stejskal <lstejska@redhat.com>",
"Lester Claudio <claudiol@redhat.com>",
"Lucas Bickel <hairmare@rabe.ch>",
"Luk\u00e1\u0161 Zapletal <lzap+git@redhat.com>",
"Manisha Singhal <manisha1595@gmail.com>",
"Manuel Bonk <githubMB@bonkii.com>",
"Marcelo Moreira de Mello <tchello.mello@gmail.com>",
"Marek Czernek <mczernek@redhat.com>",
"Mark Hlawatschek <hlawatschek@atix.de>",
"Markus Bucher <bucher@atix.de>",
"Martin Schlossarek <martin.schlossarek@gmail.com>",
"Matthias Dellweg <2500@gmx.de>",
"Miikka Joutsenvirta <miikka.joutsenvirta@dna.fi>",
"Nikhil Jain <jainnikhil30@gmail.com>",
"Olivier <oliverf1ca@yahoo.com>",
"Ondrej Prazak <oprazak@redhat.com>",
"Ond\u0159ej Ezr <oezr@redhat.com>",
"Ond\u0159ej Gajdu\u0161ek <ogajduse@redhat.com>",
"Patrick C. F. Ernzer <pcfe@pcfe.net>",
"Patrick Creech <pcreech@redhat.com>",
"Paul Armstrong <parmstro@users.noreply.github.com>",
"Paul Belanger <pabelanger@redhat.com>",
"Paul Gration <pmgration@gmail.com>",
"Peter Ondrejka <pondrejk@redhat.com>",
"Philipp <philipp98.joos@gmail.com>",
"Quirin Pamp <pamp@atix.de>",
"Richard Stempfl <richielatk@gmail.com>",
"Sam <samcalvert@me.com>",
"Samir Jha <sjha4@ncsu.edu>",
"Sean O'Keeffe <seanokeeffe797@gmail.com>",
"Sorin Sbarnea <sorin.sbarnea@gmail.com>",
"Stoned Elipot <stoned.elipot@gmail.com>",
"TTherouanne <thomas@therouanne.com>",
"Thomas Mueller <thomas@chaschperli.ch>",
"William Bradford Clark <wclark@redhat.com>",
"Yifat Makias <ymakias@redhat.com>",
"achevalet <anthony.chevalet@gmail.com>",
"bob <57952350+TheRedGreek@users.noreply.github.com>",
"calvingsmith <4283930+calvingsmith@users.noreply.github.com>",
"divialth <65872926+divialth@users.noreply.github.com>",
"furhouse <furhouse@users.noreply.github.com>",
"gardar <gardar@users.noreply.github.com>",
"igramic <36156377+igramic@users.noreply.github.com>",
"jerrejkw <43955357+jerrejkw@users.noreply.github.com>",
"marco <marco.markgraf@transporeon.com>",
"metalcated <mike.gomon@gmail.com>",
"russianguppie <46544650+russianguppie@users.noreply.github.com>",
"willtome <willtome@gmail.com>"
],
"readme": "README.md",
"tags": [
"foreman",
"katello",
"satellite",
"orcharhino",
"infrastructure"
],
"description": "Ansible Modules to manage Foreman and Katello installations",
"license": [
"GPL-3.0-or-later"
],
"license_file": null,
"dependencies": {},
"repository": "https://github.com/theforeman/foreman-ansible-modules",
"documentation": "https://theforeman.org/plugins/foreman-ansible-modules/",
"homepage": "https://theforeman.org/",
"issues": "https://github.com/theforeman/foreman-ansible-modules/issues"
},
"file_manifest_file": {
"name": "FILES.json",
"ftype": "file",
"chksum_type": "sha256",
"chksum_sha256": "47fc3807d36541cd5bd00b364780fdb9a6696d6c83daa9245c9a470287bb09aa",
"format": 1
},
"format": 1
}

View File

@@ -0,0 +1,48 @@
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
--------------------------------------------
1. This LICENSE AGREEMENT is between the Python Software Foundation
("PSF"), and the Individual or Organization ("Licensee") accessing and
otherwise using this software ("Python") in source or binary form and
its associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python alone or in any derivative version,
provided, however, that PSF's License Agreement and PSF's notice of copyright,
i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 Python Software Foundation;
All Rights Reserved" are retained in Python alone or in any derivative version
prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python.
4. PSF is making Python available to Licensee on an "AS IS"
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any
relationship of agency, partnership, or joint venture between PSF and
Licensee. This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote
products or services of Licensee, or any third party.
8. By copying, installing or otherwise using Python, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.

View File

@@ -0,0 +1,146 @@
# Foreman Ansible Modules ![Build Status](https://github.com/theforeman/foreman-ansible-modules/workflows/CI/badge.svg)
Ansible modules for interacting with the Foreman API and various plugin APIs such as Katello.
## Documentation
A list of all modules and their documentation can be found at [theforeman.org/plugins/foreman-ansible-modules](https://theforeman.org/plugins/foreman-ansible-modules/).
## Support
### Supported Foreman and plugins versions
Modules should support any currently stable Foreman release and the matching set of plugins.
Some modules have additional features/arguments that are only applied when the corresponding plugin is installed.
We actively test the modules against the latest stable Foreman release and the matching set of plugins.
### Supported Ansible Versions
The supported Ansible versions are aligned with currently maintained Ansible versions that support Collections (2.9+).
You can find the list of maintained Ansible versions [here](https://docs.ansible.com/ansible/devel/reference_appendices/release_and_maintenance.html).
### Supported Python Versions
Ansible only supports Python 2.7 and 3.5 (and higher). These are also the only Python versions we develop and test the modules against.
### Known issues
* Some modules, e.g. `repository_sync` and `content_view_version`, trigger long running tasks on the server side. It might be beneficial to your playbook to wait for their completion in an asynchronous manner.
As Ansible has facilities to do so, the modules will wait unconditionally. See the [Ansible documentation](https://docs.ansible.com/ansible/latest/user_guide/playbooks_async.html) for putting tasks in the background.
Please make sure to set a high enough `async` value, as otherwise Ansible might abort the execution of the module while there is still a task running on the server, making status reporting fail.
* According to [Ansible documentation](https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html), using loop over Ansible resources can leak sensitive data. This applies to all modules, but especially those which require more secrets than the API credentials (`auth_source_ldap`, `compute_resource`, `host`, `hostgroup`, `http_proxy`, `image`, `repository`, `scc_account`, `user`). You can prevent this by using `no_log: yes` on the task.
eg:
```yaml
- name: Create compute resources
theforeman.foreman.compute_resource:
server_url: https://foreman.example.com
username: admin
password: changeme
validate_certs: yes
name: "{{ item.name }}"
organizations: "{{ item.organizations | default(omit) }}"
locations: "{{ item.locations | default(omit) }}"
description: "{{ item.description | default(omit) }}"
provider: "{{ item.provider }}"
provider_params: "{{ item.provider_params | default(omit) }}"
state: "{{ item.state | default('present') }}"
loop: "{{ compute_resources }}"
no_log: yes
```
* Modules require write access to `~/.cache` (or wherever `$XDG_CACHE_HOME` points at). Otherwise the API documentation cannot be downloaded and you get errors like `[Errno 13] Permission denied: '/home/runner/.cache/apypie`. If on your system `~/.cache` is not writeable, please set the `$XDG_CACHE_HOME` environment variable to a directory Ansible can write to.
## Installation
There are currently two ways to use the modules in your setup: install from Ansible Galaxy or via RPM.
### Installation from Ansible Galaxy
You can install the collection from [Ansible Galaxy](https://galaxy.ansible.com/theforeman/foreman) by running `ansible-galaxy collection install theforeman.foreman`.
After the installation, the modules are available as `theforeman.foreman.<module_name>`. Please see the [Using Ansible collections documentation](https://docs.ansible.com/ansible/devel/user_guide/collections_using.html) for further details.
### Installation via RPM
The collection is also available as `ansible-collection-theforeman-foreman` from the `plugins` repository on `yum.theforeman.org`.
After installing the RPM, you can use the modules in the same way as when they are installed directly from Ansible Galaxy.
## Installation From Source
For development or testing purposes, you can install the collection from source git repository. For production usage, see the instructions above on installing the latest stable release.
### Installation from Github Repository
With Ansible >= 2.10, you can install from a Github repository (such as this one or your fork):
```console
$ ansible-galaxy collection install git+https://github.com/theforeman/foreman-ansible-modules.git
```
If you have configured GitHub to use SSH instead of HTTPS, you can do:
```console
$ ansible-galaxy collection install git@github.com/theforeman/foreman-ansible-modules.git
```
You can also specify a branch to use such as `devel` (below) or a feature branch that you are working with:
```console
$ ansible-galaxy collection install git+https://github.com/theforeman/foreman-ansible-modules.git,devel
```
To install from a `requirements.yml` file (useful when installing multiple collections) add a snippet to your `requirements.yml` like
```yaml
---
collections:
- name: https://github.com/theforeman/foreman-ansible-modules.git
type: git
version: devel
```
And install all specified requirements with `ansible-galaxy install -r requirements.yml`
### Building and Installing the Collection Locally
For all currently supported versions of Ansible (i.e. Ansible >= 2.9, and particularly Ansible < 2.10 where the above approach is not yet supported), you can build the collection locally:
```console
$ make dist
```
And install it with:
```console
$ ansible-galaxy collection install ./theforeman-foreman-*.tar.gz
```
## Dependencies
These dependencies are required for the Ansible controller, not the Foreman server.
* [`PyYAML`](https://pypi.org/project/PyYAML/)
* [`requests`](https://pypi.org/project/requests/)
* [`ipaddress`](https://pypi.org/project/ipaddress/) for the `subnet` module on Python 2.7
* `rpm` for the RPM support in the `content_upload` module
* `debian` for the DEB support in the `content_upload` module
# Foreman Ansible Roles
Roles using the Foreman Ansible Modules to configure Foreman and its plugins.
## Documentation
For individual role documentation, check the README defined at `roles/rolename/README.md`.
### Common Role Variables
- `foreman_server_url`: URL of the Foreman server. If the variable is not specified, the value of environment variable `FOREMAN_SERVER_URL` will be used instead.
- `foreman_username`: Username accessing the Foreman server. If the variable is not specified, the value of environment variable `FOREMAN_USERNAME` will be used instead.
- `foreman_password`: Password of the user accessing the Foreman server. If the variable is not specified, the value of environment variable `FOREMAN_PASSWORD` will be used instead.
- `foreman_validate_certs`: Whether or not to verify the TLS certificates of the Foreman server. If the variable is not specified, the value of environment variable `FOREMAN_VALIDATE_CERTS` will be used instead.
- `foreman_organization`: Organization where configuration will be applied.

View File

@@ -0,0 +1,3 @@
python3-rpm [(platform:redhat platform:base-py3)]
rpm-python [(platform:redhat platform:base-py2)]
python38-requests [platform:centos-8 platform:rhel-8]

View File

@@ -0,0 +1,704 @@
ancestor: 0.8.1
releases:
1.0.0:
changes:
breaking_changes:
- |
All modules were renamed to drop the ``foreman_`` and ``katello_`` prefixes.
Additionally to the prefix removal, the following modules were further ranamed:
* katello_upload to content_upload
* katello_sync to repository_sync
* katello_manifest to subscription_manifest
* foreman_search_facts to resource_info
* foreman_ptable to partition_table
* foreman_model to hardware_model
* foreman_environment to puppet_environment
release_summary: |
This is the first stable release of the ``theforeman.foreman`` collection.
modules:
- description: Manage Activation Keys
name: activation_key
namespace: ''
- description: Manage Architectures
name: architecture
namespace: ''
- description: Manage LDAP Authentication Sources
name: auth_source_ldap
namespace: ''
- description: Manage Bookmarks
name: bookmark
namespace: ''
- description: Manage Compute Attributes
name: compute_attribute
namespace: ''
- description: Manage Compute Profiles
name: compute_profile
namespace: ''
- description: Manage Compute Resources
name: compute_resource
namespace: ''
- description: Manage (Puppet) Config Groups
name: config_group
namespace: ''
- description: Manage Content Credentials
name: content_credential
namespace: ''
- description: Upload content to a repository
name: content_upload
namespace: ''
- description: Manage Content Views
name: content_view
namespace: ''
- description: Manage Content View Filters
name: content_view_filter
namespace: ''
- description: Manage Content View Versions
name: content_view_version
namespace: ''
- description: Manage Domains
name: domain
namespace: ''
- description: Manage External User Groups
name: external_usergroup
namespace: ''
- description: Manage Global Parameters
name: global_parameter
namespace: ''
- description: Manage Hardware Models
name: hardware_model
namespace: ''
- description: Manage Hosts
name: host
namespace: ''
- description: Manage Host Collections
name: host_collection
namespace: ''
- description: Manage Power State of Hosts
name: host_power
namespace: ''
- description: Manage Hostgroups
name: hostgroup
namespace: ''
- description: Manage Images
name: image
namespace: ''
- description: Manage Installation Media
name: installation_medium
namespace: ''
- description: Manage Job Templates
name: job_template
namespace: ''
- description: Manage Lifecycle Environments
name: lifecycle_environment
namespace: ''
- description: Manage Locations
name: location
namespace: ''
- description: Manage Operating Systems
name: operatingsystem
namespace: ''
- description: Manage Organizations
name: organization
namespace: ''
- description: Manage Default Template Associations To Operating Systems
name: os_default_template
namespace: ''
- description: Manage Partition Table Templates
name: partition_table
namespace: ''
- description: Manage Products
name: product
namespace: ''
- description: Manage Provisioning Templates
name: provisioning_template
namespace: ''
- description: Manage Puppet Environments
name: puppet_environment
namespace: ''
- description: Manage Realms
name: realm
namespace: ''
- description: Interact with a Red Hat Satellite Subscription Manifest
name: redhat_manifest
namespace: ''
- description: Manage Repositories
name: repository
namespace: ''
- description: Enable/disable Repositories in Repository Sets
name: repository_set
namespace: ''
- description: Sync a Repository or Product
name: repository_sync
namespace: ''
- description: Gather information about resources
name: resource_info
namespace: ''
- description: Manage Roles
name: role
namespace: ''
- description: Manage SCAP content
name: scap_content
namespace: ''
- description: Manage SCAP Tailoring Files
name: scap_tailoring_file
namespace: ''
- description: Manage SUSE Customer Center Accounts
name: scc_account
namespace: ''
- description: Subscribe SUSE Customer Center Account Products
name: scc_product
namespace: ''
- description: Manage Settings
name: setting
namespace: ''
- description: Manage Smart Class Parameters
name: smart_class_parameter
namespace: ''
- description: Manage Snapshots
name: snapshot
namespace: ''
- description: Manage Subnets
name: subnet
namespace: ''
- description: Manage Subscription Manifests
name: subscription_manifest
namespace: ''
- description: Manage Sync Plans
name: sync_plan
namespace: ''
- description: Sync Templates from a repository
name: templates_import
namespace: ''
- description: Manage Users
name: user
namespace: ''
- description: Manage User Groups
name: usergroup
namespace: ''
release_date: '2020-06-19'
1.0.1:
changes:
release_summary: |
Documentation fixes to reflect the correct module names.
release_date: '2020-06-29'
1.1.0:
changes:
bugfixes:
- inventory plugin - fix want_params handling (https://github.com/theforeman/foreman-ansible-modules/issues/847)
minor_changes:
- activation_key - add ``description`` parameter (https://github.com/theforeman/foreman-ansible-modules/issues/915)
- callback plugin - add reporter to report logs sent to Foreman (https://github.com/theforeman/foreman-ansible-modules/issues/836)
- document return values of modules (https://github.com/theforeman/foreman-ansible-modules/pull/901)
- inventory plugin - allow to control batch size when pulling hosts from Foreman
(https://github.com/theforeman/foreman-ansible-modules/pull/865)
- subnet - Require mask/cidr only on ipv4 (https://github.com/theforeman/foreman-ansible-modules/issues/878)
fragments:
- 836-add-reporter-to-callback.yaml
- 847-want_params-fix.yaml
- 865-limit-inventory-per-host.yaml
- 878-cidr-only-v4.yaml
- 901-document-return-values.yaml
- 915-activation_key-description.yaml
modules:
- description: Manage HTTP Proxies
name: http_proxy
namespace: ''
release_date: '2020-08-17'
1.2.0:
changes:
bugfixes:
- image - fix quoting of search values (https://github.com/theforeman/foreman-ansible-modules/issues/927)
minor_changes:
- compute_resource - added ``caching_enabled`` option for VMware compute resources
- domain, host, hostgroup, operatingsystem, subnet - manage parameters in a
single API call (https://bugzilla.redhat.com/show_bug.cgi?id=1855008)
- host - add ``compute_attributes`` parameter to module (https://bugzilla.redhat.com/show_bug.cgi?id=1871815)
- provisioning_template - update list of possible template kinds (https://bugzilla.redhat.com/show_bug.cgi?id=1871978)
- repository - update supported parameters (https://github.com/theforeman/foreman-ansible-modules/issues/935)
fragments:
- 927-image-quoting.yaml
- 932-host-add-compute_attributes.yaml
- 935-repository-params.yaml
- 939-compute_resource-added_caching_enabled.yaml
- bz1855008-single_call_parameters.yaml
- bz1871978-template_kinds.yaml
release_date: '2020-09-03'
1.3.0:
changes:
bugfixes:
- content_view - remove CVs from lifecycle environments before deleting them
(https://bugzilla.redhat.com/show_bug.cgi?id=1875314)
- external_usergroup - support non-LDAP external groups (https://github.com/theforeman/foreman-ansible-modules/issues/956)
- host - properly scope image lookups by the compute resource (https://bugzilla.redhat.com/show_bug.cgi?id=1878693)
- inventory plugin - include empty parent groups in the inventory (https://github.com/theforeman/foreman-ansible-modules/issues/919)
minor_changes:
- external_usergroup - rename the ``auth_source_ldap`` parameter to ``auth_source``
(``auth_source_ldap`` is still supported via an alias)
- server URL and credentials can now also be specified using environment variables
(https://github.com/theforeman/foreman-ansible-modules/issues/837)
- subnet - add support for external IPAM (https://github.com/theforeman/foreman-ansible-modules/issues/966)
fragments:
- 837-env-fallback.yaml
- 919-include-empty-parent-groups.yml
- 956-external_usergroup-non-ldap.yaml
- 966-subnet-external_ipam.yaml
- bz1875314-content_view-remove.yaml
- bz1878693-scope_image_lookups.yaml
modules:
- description: Get status info
name: status_info
namespace: ''
release_date: '2020-09-22'
1.4.0:
changes:
bugfixes:
- Don't try to update an entity, if only parameters that aren't supported by
the server are detected as changed. (https://github.com/theforeman/foreman-ansible-modules/issues/975)
- allow to pass an empty string when refering to entities, thus unsetting the
value (https://github.com/theforeman/foreman-ansible-modules/issues/969)
- compute_profile - don't fail when trying to update compute attributes of a
profile (https://github.com/theforeman/foreman-ansible-modules/issues/997)
- host, hostgroup - support ``None`` as the ``pxe_loader`` (https://github.com/theforeman/foreman-ansible-modules/issues/971)
- job_template - don't fail when trying to update template_inputs
- os_default_template - document possible template kind choices (https://bugzilla.redhat.com/show_bug.cgi?id=1889952)
- smart_class_parameters - don't fail when trying to update override_values
minor_changes:
- global_parameter - allow to set hidden flag (https://github.com/theforeman/foreman-ansible-modules/issues/1024)
- job_template - stricter validation of ``template_inputs`` sub-options
- redhat_manifest - allow configuring content access mode (https://github.com/theforeman/foreman-ansible-modules/issues/820)
- subnet - verify the server has the ``remote_execution`` plugin when specifying
``remote_execution_proxies``
- the ``apypie`` library is vendored inside the collection, so users only have
to install ``requests`` manually now.
fragments:
- 820-redhat_manifest-sca.yaml
- 969-allow-unset-entity.yml
- 971-pxe_loader-none.yaml
- 975-filter-update-payload.yml
- 997-compute_profile-update.yaml
- bz1889952-os_default_template-kind.yaml
- global_parameter-hidden_values.yaml
- job_template-template_inputs-validation.yaml
- rex-proxy-subnet-check.yaml
- venored_apypie.yaml
modules:
- description: Invoke Remote Execution Jobs
name: job_invocation
namespace: ''
- description: Manage Smart Proxies
name: smart_proxy
namespace: ''
release_date: '2020-10-21'
1.5.0:
changes:
bugfixes:
- content_upload - Fix upload of files bigger than 2MB in Pulp3-based setups
(https://github.com/theforeman/foreman-ansible-modules/issues/1043)
- job_invocation - properly submit ``ssh``, ``recurrence``, ``scheduling`` and
``concurrency_control`` to the server
- repository - don't emit a false warning about ``organization_id`` not being
supported by the server (https://github.com/theforeman/foreman-ansible-modules/issues/1055)
- repository_set, repository - clarify documentation which module should be
used for Red Hat Repositories (https://github.com/theforeman/foreman-ansible-modules/issues/1059)
minor_changes:
- content_upload - use ``to_native`` to decode RPM headers if needed (RPM 4.15+
returns strings)
- content_view_version - provide examples how to obtain detailed information
about content view versions (https://bugzilla.redhat.com/show_bug.cgi?id=1868145)
- content_view_version_cleanup - new role for cleaning up unused content view
versions (https://github.com/theforeman/foreman-ansible-modules/issues/497)
- host - allow management of interfaces (https://github.com/theforeman/foreman-ansible-modules/issues/757)
- inventory plugin - add support for the Report API present in Foreman 1.24
and later
- inventory plugin - allow to compose the ``inventory_hostname`` (https://github.com/theforeman/foreman-ansible-modules/issues/1070)
- manifest - new role for easier handling of subscription manifest workflows
- subnet - add new ``externalipam_group`` parameter
- update vendored ``apypie`` to 0.3.2
fragments:
- 1043-chunked_content_upload.yml
- 1059-repository_set-docs.yml
- 1062-warnings.yml
- 1070-compose_inventory_hostname.yml
- 757-host_interfaces.yml
- bz1868145-cv_version_examples.yml
- content_upload-decode-old-rpm.yml
- inventory_plugin_report_api.yml
- subnet-externalipam_group.yml
- theforeman.foreman.content_view_version_cleanup_role.yml
- theforeman.foreman.manifest_role.yml
release_date: '2020-12-03'
2.0.0:
changes:
breaking_changes:
- All role variables are now prefixed with ``foreman_`` to avoid clashes with
similarly named variables from roles outside this collection.
bugfixes:
- content_view_version - make the ``version`` parameter not fail when the version
was entered without a minor part (https://github.com/theforeman/foreman-ansible-modules/issues/1087)
- host - allow moving hosts between Organizations and Locations (https://bugzilla.redhat.com/show_bug.cgi?id=1901716)
- host - fix subnet/domain assignment when multiple interfaces are defined (https://github.com/theforeman/foreman-ansible-modules/issues/1095)
- host, hostgroup - select kickstart_repository based on lifecycle_environment
and content_view if those are set (https://github.com/theforeman/foreman-ansible-modules/issues/1090,
https://bugzilla.redhat.com/1915872)
- resource_info - correctly show the exact resource when passing ``id`` in ``params``
minor_changes:
- Add a role `activation_keys` to manage activation keys
- Add a role `lifecycle_environments` to manage lifecycle environments
- Add a role `repositories` to manage products, repositories, and repository_sets
- Add a role `sync_plans` to manage sync plans
- activation_key - add support for selecting subscriptions by ``upstream_pool_id``
- compute_resource - add ``set_console_password``, ``keyboard_layout`` and ``public_key``
parameters (https://github.com/theforeman/foreman-ansible-modules/issues/1052)
- host - clarify that ``owner`` refers to a users login, not their full name
(https://github.com/theforeman/foreman-ansible-modules/issues/1045)
- host - look up the correct network id for a network given as part of ``interfaces_attributes``
(https://github.com/theforeman/foreman-ansible-modules/issues/1104)
- host, hostgroup - add ``activation_keys`` parameter to ease configuring activation
keys for deploments
fragments:
- 1027-repositories_role.yml
- 1045-host-owner.yml
- 1052-compute_resource-params.yaml
- 1065-sync-plans_role.yml
- 1068-activation-keys_role.yml
- 1087-content_view_version-safenet.yml
- 1090-scope_kickstart_repository_tighter.yml
- 1095-nested_list-lookup-fix.yml
- 1096-lifecycle-environments-role.yml
- 1104-network_id-lookup.yml
- 1145-role_prefix.yml
- 541-activation-key-upstream-pool.yml
- bz1901716-dont_scope_requests.yml
- host-hostgroup-ak-parameter.yml
- resource_info-params-id.yml
modules:
- description: Fetch information about Hosts
name: host_info
namespace: ''
- description: Import Puppet Classes from a Proxy
name: puppetclasses_import
namespace: ''
- description: Fetch information about Repositories
name: repository_info
namespace: ''
release_date: '2021-02-22'
2.0.1:
changes:
bugfixes:
- host - don't filter ``false`` values for ``interfaces_attributes`` (https://github.com/theforeman/foreman-ansible-modules/issues/1148)
- host_info, repository_info - correctly fetch all entities when neither ``name``
nor ``search`` is set
- host_info, repository_info - enforce mutual exclusivity of ``name`` and ``search``
fragments:
- 1148-dont-filter-false-params.yml
- 20210224-info_module_fixes.yml
release_date: '2021-03-02'
2.1.0:
changes:
bugfixes:
- host - pass the right image id to the compute resource when creating a host
(https://github.com/theforeman/foreman-ansible-modules/issues/1160, https://bugzilla.redhat.com/show_bug.cgi?id=1911670)
minor_changes:
- Add a domain_info module
- Add a hostgroups role (https://github.com/theforeman/foreman-ansible-modules/issues/1116)
- Add a role `content_rhel` to perform basic setup for registering and syncing
RHEL content hosts
- Add content credentials role
- callback plugin - collect facts during the run, merge them correctly and upload
them once at the end
- compute_resource - add ``cloud`` param for the AzureRm provider, to select
which Azure cloud to use
- compute_resource - add ``sub_id`` parameter for handling the Azure Subscription
ID instead of the ``user`` parameter
- host - Add ``Redfish`` to list of possible BMC providers of an interface
- host, compute_profile - look up the correct id for storage pods and domains
given as part of ``volumes_attributes`` (https://bugzilla.redhat.com/show_bug.cgi?id=1885234)
- hostgroup - add a ``ansible_roles`` parameter (https://github.com/theforeman/foreman-ansible-modules/issues/1123)
- new ``content_views`` role to manage content views (https://github.com/theforeman/foreman-ansible-modules/issues/1111)
- new ``organizations`` role to manage organizations (https://github.com/theforeman/foreman-ansible-modules/issues/1109)
- subnet - add ``bmc_proxy`` parameter to configure BMC proxies for subnets
fragments:
- 1097-content-rhel-role.yml
- 1109-organizations-role.yml
- 1111-content_views_role.yml
- 1116-hostgroups-role.yml
- 1123-ansible-roles-for-hostgroups.yml
- 1160-pass-image-in-compute-attributes.yml
- 1196-content_credentials-role.yml
- azure-clouds.yml
- azure-subid.yml
- bz1885234-storage-lookup.yml
- domain-info-module.yml
- foreman-fact-upload.yml
- host-redfish-bmc.yml
- subnet-bmc-proxy-param.yml
modules:
- description: Fetch information about Content Views
name: content_view_info
namespace: ''
- description: Fetch information about Content Views
name: content_view_version_info
namespace: ''
- description: Fetch information about Domains
name: domain_info
namespace: ''
- description: Fetch information about Host Errata
name: host_errata_info
namespace: ''
- description: Fetch information about Red Hat Repositories
name: repository_set_info
namespace: ''
- description: Fetch information about Settings
name: setting_info
namespace: ''
- description: Fetch information about Subnets
name: subnet_info
namespace: ''
- description: Fetch information about Subscriptions
name: subscription_info
namespace: ''
release_date: '2021-05-20'
2.1.1:
changes:
bugfixes:
- external_usergroup - always lookup the ID of the usergroup, instead of passing
the name to the API (https://bugzilla.redhat.com/show_bug.cgi?id=1967649)
- host, hostgroup - don't override already set parameters when passing an activation
key only (and vice versa) (https://bugzilla.redhat.com/show_bug.cgi?id=1967904)
fragments:
- bz1967649-usergroup_lookup.yml
- bz1967904-dont_override_params.yml
release_date: '2021-06-22'
2.1.2:
changes:
bugfixes:
- activation_key - submit organization_id when querying subs, required for Katello
4.1
- content_view_version_cleanup - sort content view versions before deleting
(https://github.com/RedHatSatellite/satellite-ansible-collection/issues/30,
https://bugzilla.redhat.com/show_bug.cgi?id=1980274)
- content_view_version_cleanup role - properly clean up when users set keep=0
(https://bugzilla.redhat.com/show_bug.cgi?id=1974314)
- host, compute_profile - when resolving cluster and other values in vm_attrs,
compare them as strings (https://github.com/theforeman/foreman-ansible-modules/issues/1245)
- subscription_info - mark ``organization`` parameter as required, to match
Katello
fragments:
- 1245-search_vm_attr_as_string.yml
- BZ1974314-cv_cleanup_keep_0.yml
- bz1980274.yml
- katello41-subscription-org-required.yml
release_date: '2021-07-13'
2.2.0:
changes:
bugfixes:
- host, hostgroup - don't accidentally duplicate ``kt_activation_keys`` param
(https://github.com/theforeman/foreman-ansible-modules/issues/1268)
minor_changes:
- repository - add support for filtering repositories by OS version based on
API feature apidoc/v2/repositories/create.html
fragments:
- 1268-ak_param_duplicate.yml
- repository.yml
release_date: '2021-08-24'
3.0.0:
changes:
breaking_changes:
- Set use_reports_api default value to true for the inventory plugin
- Support for Ansible 2.8 is removed
bugfixes:
- host, hostgroup - fix updating puppetclasses while also updating description
(or other string-like attributes) (https://github.com/theforeman/foreman-ansible-modules/issues/1231)
minor_changes:
- Add a role `convert2rhel` to perform setup for converting systems to RHEL
- inventory plugin - enable certificate validation by default
- repository - add ``arch`` parameter to limit architectures of the repository
(https://github.com/theforeman/foreman-ansible-modules/issues/1265)
fragments:
- 1231-puppetclasses-and-description-update.yml
- 1265-repository-arch.yml
- 1291-foreman-ansible-inventory-default.yml
- convert2rhel.yml
- drop-ansible28.yml
- validate-inventory-certs.yml
release_date: '2021-11-11'
3.1.0:
changes:
bugfixes:
- callback plugin - include timezone information in the callback reported data
(https://github.com/theforeman/foreman-ansible-modules/issues/1171)
- hostgroup, location - don't fail when trying to delete a Hostgroup or Location
where the parent is already absent
- inventory plugin - fetch *all* facts, not only the first 250, when using the
old Hosts API
minor_changes:
- Warn if the user tries to use a plain HTTP server URL and fail if the URL
is neither HTTPS nor HTTP.
- new ``compute_profiles`` role to manage compute profiles
- new ``compute_resources`` role to manage compute resources
- new ``content_view_publish`` role to publish a list of content views (https://github.com/theforeman/foreman-ansible-modules/issues/1209)
- new ``domains`` role to manage domains
- new ``operatingsystems`` role to manage operating systems
- new ``provisioning_templates`` role to manage provisioning templates
- new ``settings`` role to manage settings
- new ``subnets`` role to manage subnets
- repository - new ``download_concurrency`` parameter (https://github.com/theforeman/foreman-ansible-modules/issues/1273)
fragments:
- 1171-timezone.yml
- 1209-content_views_role.yml
- 1301-failsafe-parents.yml
- 1303-foreman-repository-download-concurrency.yml
- add-compute-profile-role.yml
- add-compute-resource-role.yml
- add-domains-role.yml
- add-operatingsystems-role.yml
- add-provisioning-templates-role.yml
- add-settings-role.yml
- add-subnets-role.yml
- explicit-http-warning.yml
- inventory-facts-batch-size.yml
release_date: '2022-01-14'
3.2.0:
changes:
bugfixes:
- content_upload - clarify that ``src`` refers to a remote file (https://bugzilla.redhat.com/show_bug.cgi?id=2055416)
minor_changes:
- new ``auth_sources_ldap`` role to manage LDAP authentication sources
fragments:
- add-auth-source-ldaps-role.yml
- bz2055416.yaml
release_date: '2022-03-01'
3.3.0:
changes:
minor_changes:
- content_upload - add support for OSTree content uploads (https://github.com/theforeman/foreman-ansible-modules/issues/628,
https://projects.theforeman.org/issues/33299)
- os_default_template, provisioning_template - add ``host_init_config`` to list
of possible template types
fragments:
- 1297-host_init_config.yml
- 628-ostree.yml
release_date: '2022-04-04'
3.4.0:
changes:
bugfixes:
- content_upload - properly detect SRPMs and ensure idempotency during uploads
(https://github.com/theforeman/foreman-ansible-modules/issues/1274)
- inventory plugin - fix caching for Report API (https://github.com/theforeman/foreman-ansible-modules/issues/1246)
- operatingsystem - find operatingsystems by title or full (name,major,minor)
tuple (https://github.com/theforeman/foreman-ansible-modules/issues/1401)
- os_default_template, provisioning_template - don't document invalid template
kind ``ptable`` (https://bugzilla.redhat.com/show_bug.cgi?id=1970132)
minor_changes:
- add support for module defaults groups for Ansible core 2.12 (https://github.com/theforeman/foreman-ansible-modules/issues/1015)
- all modules - report smaller diffs by dropping ``null`` values. This should
result in not showing fields that were unset to begin with, and mark fields
that were explicitly removed as "deleted" instead of "replaced by ``null``"
- compute_resource - update libvirt examples (https://bugzilla.redhat.com/show_bug.cgi?id=1990119)
- content_view - add support to set label during creation.
- repository - add ``rhel-9`` to os version filter choices
- repository - add support for ``mirroring_policy`` for Katello 4.4+ (https://github.com/theforeman/foreman-ansible-modules/issues/1388)
fragments:
- 1015-action_groups.yml
- 1246-inventory_reports_cache.yml
- 1274-content_upload-srpm.yml
- 1388-repository-mirroring_policy.yml
- 1397-content_view-label.yml
- 1401-os-search-title.yml
- 1970132-no-ptable-kind.yml
- 1990119-libvirt-examples.yml
- repository-rhel9.yml
- smaller-diffs.yml
release_date: '2022-05-17'
3.5.0:
changes:
minor_changes:
- add execution environment metadata
- installation_medium, operatingsystem, partition_table - add ``Fcos``, ``Rhcos``,
``VRP`` OS families
- job_template - add ``hidden_value`` to ``template_inputs`` parameters
- job_template - allow ``value_type`` to be ``resource``
- operatingsystems role - make ``provisioning_template`` parameter optional
- repositories role - add ``ansible_collection_requirements``
- repositories role - add ``arch`` and ``os_versions`` parameters
- repositories role - support ``mirroring_policy``
- repository, smart_proxy - document deprecation/removal status of ``download_policy=background``
- setting - the ``foreman_setting`` return entry is deprecated and kept for
backwards compatibility, please use ``entity`` as with any other module
- smart_proxy - add ``inherit`` to possible values of ``download_policy`` (https://github.com/theforeman/foreman-ansible-modules/issues/1438)
- smart_proxy - add ``streamed`` download policy
- snapshot - add include_ram option when creating VMWare snapshot
fragments:
- 1438-smart_proxy-download_policy-inherit.yml
- setting-return-deprecate.yml
modules:
- description: List pulp3 content exports
name: content_export_info
namespace: ''
- description: Manage content exports
name: content_export_library
namespace: ''
- description: Manage Host Discovery Rules
name: discovery_rule
namespace: ''
release_date: '2022-08-22'
3.6.0:
modules:
- description: Manage repository content exports
name: content_export_repository
namespace: ''
- description: Manage content view version content exports
name: content_export_version
namespace: ''
release_date: '2022-09-01'
3.7.0:
changes:
bugfixes:
- Properly use FQCN notation when redirecting the old ``foreman_*`` and ``katello_*``
module names. (https://github.com/theforeman/foreman-ansible-modules/issues/1484)
- convert2rhel role - Content views for activation keys (https://bugzilla.redhat.com/2118790)
minor_changes:
- repository - add support for ``include_tags`` and ``exclude_tags`` parameters
for Katello 4.4+
- subscription_manifest - increase the import timeout to 10 minutes (https://github.com/theforeman/foreman-ansible-modules/issues/1474)
- sync_plans role - document the ``enabled`` parameter (https://github.com/theforeman/foreman-ansible-modules/issues/1477)
- sync_plans role - expose the ``state`` parameter of the underlying module,
thus allowing to delete plans (https://github.com/theforeman/foreman-ansible-modules/issues/1477)
fragments:
- 1474-subscription_manifest-timeout.yaml
- 1477-sync_plans-enhancements.yml
- 1484-redirect-fqcn.yaml
- bz2118790.yml
- repository-include-exclude-tags.yaml
release_date: '2022-10-05'
3.8.0:
changes:
bugfixes:
- activation_key - properly fetch *all* repositories when managing content overrides
(https://bugzilla.redhat.com/show_bug.cgi?id=2134605)
- redhat_manifest - properly report http errors (https://github.com/theforeman/foreman-ansible-modules/issues/1497)
- repository_sync - report an error instead of syncing the whole product when
the repository could not be found
minor_changes:
- job_template - add ``default`` option to the ``template_inputs`` parameter
- location, organization - add ``ignore_types`` parameter to adjust automatic
association of resources
- redhat_manifest - Search by UUID on the server side if UUID is known. This
is faster and allows fetching of manifest in big accounts (>1000 allocations).
- redhat_manifest - return the UUID of the manifest so it can be reused later
- redhat_manifest - set default ``quantity`` to 1 (https://github.com/theforeman/foreman-ansible-modules/pull/1499)
fragments:
- 1497-redhat_manifest-report-error.yml
- 1509-taxonomy-ignore_types.yaml
- 1519-job_template-input-default.yml
- 2134605-ak-product_contents-per_page.yml
- manifest-uuid-return.yml
- redhat_manifest-default_quantity.yml
- redhat_manifest-uuid-search.yml
- repository_sync-no-failsaife-repository.yml
modules:
- description: Fetch information about Foreman Snapshots
name: snapshot_info
namespace: ''
release_date: '2022-12-20'

View File

@@ -0,0 +1,12 @@
---
version: 1
build_arg_defaults:
EE_BASE_IMAGE: 'quay.io/ansible/ansible-runner:latest'
dependencies:
# File paths are relative to collection root folder when collection is
# installed but relative to meta/ when it is built, so we need symlink magic
# See https://github.com/ansible/ansible-builder/issues/406#issuecomment-1195584188
python: requirements.txt
system: bindep.txt

View File

@@ -0,0 +1,184 @@
---
action_groups:
foreman:
- activation_key
- architecture
- auth_source_ldap
- bookmark
- compute_attribute
- compute_profile
- compute_resource
- config_group
- content_credential
- content_export_info
- content_export_library
- content_export_repository
- content_export_version
- content_upload
- content_view
- content_view_filter
- content_view_info
- content_view_version
- content_view_version_info
- discovery_rule
- domain
- domain_info
- external_usergroup
- global_parameter
- hardware_model
- host
- host_collection
- host_errata_info
- host_info
- host_power
- hostgroup
- http_proxy
- image
- installation_medium
- job_invocation
- job_template
- lifecycle_environment
- location
- operatingsystem
- organization
- organization_info
- os_default_template
- partition_table
- product
- provisioning_template
- puppet_environment
- puppetclasses_import
- realm
- repository
- repository_info
- repository_set
- repository_set_info
- repository_sync
- resource_info
- role
- scap_content
- scap_tailoring_file
- scc_account
- scc_product
- setting
- setting_info
- smart_class_parameter
- smart_proxy
- snapshot
- snapshot_info
- status_info
- subnet
- subnet_info
- subscription_info
- subscription_manifest
- sync_plan
- templates_import
- user
- usergroup
plugin_routing:
modules:
foreman_architecture:
redirect: theforeman.foreman.architecture
foreman_auth_source_ldap:
redirect: theforeman.foreman.auth_source_ldap
foreman_bookmark:
redirect: theforeman.foreman.bookmark
foreman_compute_attribute:
redirect: theforeman.foreman.compute_attribute
foreman_compute_profile:
redirect: theforeman.foreman.compute_profile
foreman_compute_resource:
redirect: theforeman.foreman.compute_resource
foreman_config_group:
redirect: theforeman.foreman.config_group
foreman_domain:
redirect: theforeman.foreman.domain
foreman_environment:
redirect: theforeman.foreman.puppet_environment
foreman_external_usergroup:
redirect: theforeman.foreman.external_usergroup
foreman_global_parameter:
redirect: theforeman.foreman.global_parameter
foreman_host:
redirect: theforeman.foreman.host
foreman_host_power:
redirect: theforeman.foreman.host_power
foreman_hostgroup:
redirect: theforeman.foreman.hostgroup
foreman_image:
redirect: theforeman.foreman.image
foreman_installation_medium:
redirect: theforeman.foreman.installation_medium
foreman_job_template:
redirect: theforeman.foreman.job_template
foreman_location:
redirect: theforeman.foreman.location
foreman_model:
redirect: theforeman.foreman.hardware_model
foreman_operatingsystem:
redirect: theforeman.foreman.operatingsystem
foreman_organization:
redirect: theforeman.foreman.organization
foreman_os_default_template:
redirect: theforeman.foreman.os_default_template
foreman_provisioning_template:
redirect: theforeman.foreman.provisioning_template
foreman_ptable:
redirect: theforeman.foreman.partition_table
foreman_realm:
redirect: theforeman.foreman.realm
foreman_role:
redirect: theforeman.foreman.role
foreman_scap_content:
redirect: theforeman.foreman.scap_content
foreman_scap_tailoring_file:
redirect: theforeman.foreman.scap_tailoring_file
foreman_scc_account:
redirect: theforeman.foreman.scc_account
foreman_scc_product:
redirect: theforeman.foreman.scc_product
foreman_search_facts:
redirect: theforeman.foreman.resource_info
foreman_setting:
redirect: theforeman.foreman.setting
foreman_smart_class_parameter:
redirect: theforeman.foreman.smart_class_parameter
foreman_snapshot:
redirect: theforeman.foreman.snapshot
foreman_subnet:
redirect: theforeman.foreman.subnet
foreman_templates_import:
redirect: theforeman.foreman.templates_import
foreman_user:
redirect: theforeman.foreman.user
foreman_usergroup:
redirect: theforeman.foreman.usergroup
katello_activation_key:
redirect: theforeman.foreman.activation_key
katello_content_credential:
redirect: theforeman.foreman.content_credential
katello_content_view:
redirect: theforeman.foreman.content_view
katello_content_view_filter:
redirect: theforeman.foreman.content_view_filter
katello_content_view_version:
redirect: theforeman.foreman.content_view_version
katello_host_collection:
redirect: theforeman.foreman.host_collection
katello_lifecycle_environment:
redirect: theforeman.foreman.lifecycle_environment
katello_manifest:
redirect: theforeman.foreman.subscription_manifest
katello_product:
redirect: theforeman.foreman.product
katello_repository:
redirect: theforeman.foreman.repository
katello_repository_set:
redirect: theforeman.foreman.repository_set
katello_sync:
redirect: theforeman.foreman.repository_sync
katello_sync_plan:
redirect: theforeman.foreman.sync_plan
katello_upload:
redirect: theforeman.foreman.content_upload
requires_ansible: '>=2.9'

View File

@@ -0,0 +1,395 @@
# -*- coding: utf-8 -*-
# (c) 2015, 2016 Daniel Lobato <elobatocs@gmail.com>
# (c) 2016 Guido Günther <agx@sigxcpu.org>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# pylint: disable=super-with-arguments
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
name: foreman
type: notification
short_description: Sends events to Foreman
description:
- This callback will report facts and task events to Foreman
requirements:
- whitelisting in configuration
- requests (python library)
options:
report_type:
description:
- "endpoint type for reports: foreman or proxy"
env:
- name: FOREMAN_REPORT_TYPE
default: foreman
ini:
- section: callback_foreman
key: report_type
url:
description:
- URL of the Foreman server.
env:
- name: FOREMAN_URL
- name: FOREMAN_SERVER_URL
- name: FOREMAN_SERVER
required: True
ini:
- section: callback_foreman
key: url
proxy_url:
description:
- URL of the Foreman Smart Proxy server.
env:
- name: FOREMAN_PROXY_URL
ini:
- section: callback_foreman
key: proxy_url
client_cert:
description:
- X509 certificate to authenticate to Foreman if https is used
env:
- name: FOREMAN_SSL_CERT
default: /etc/foreman/client_cert.pem
ini:
- section: callback_foreman
key: ssl_cert
- section: callback_foreman
key: client_cert
aliases: [ ssl_cert ]
client_key:
description:
- the corresponding private key
env:
- name: FOREMAN_SSL_KEY
default: /etc/foreman/client_key.pem
ini:
- section: callback_foreman
key: ssl_key
- section: callback_foreman
key: client_key
aliases: [ ssl_key ]
verify_certs:
description:
- Toggle to decide whether to verify the Foreman certificate.
- It can be set to '1' to verify SSL certificates using the installed CAs or to a path pointing to a CA bundle.
- Set to '0' to disable certificate checking.
env:
- name: FOREMAN_SSL_VERIFY
default: 1
ini:
- section: callback_foreman
key: verify_certs
dir_store:
description:
- When set, callback does not perform HTTP calls but stores results in a given directory.
- For each report, new file in the form of SEQ_NO-hostname.json is created.
- For each facts, new file in the form of SEQ_NO-hostname.json is created.
- The value must be a valid directory.
- This is meant for debugging and testing purposes.
- When set to blank (default) this functionality is turned off.
env:
- name: FOREMAN_DIR_STORE
default: ''
ini:
- section: callback_foreman
key: dir_store
disable_callback:
description:
- Toggle to make the callback plugin disable itself even if it is loaded.
- It can be set to '1' to prevent the plugin from being used even if it gets loaded.
env:
- name: FOREMAN_CALLBACK_DISABLE
default: 0
'''
import os
from datetime import datetime
from collections import defaultdict
import json
import time
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
from ansible.module_utils._text import to_text
from ansible.module_utils.parsing.convert_bool import boolean as to_bool
from ansible.plugins.callback import CallbackBase
def build_log_foreman(data_list):
"""
Transform the internal log structure to one accepted by Foreman's
config_report API.
"""
for data in data_list:
result = data.pop('result')
task = data.pop('task')
result['failed'] = data.get('failed')
result['module'] = task.get('action')
if data.get('failed'):
level = 'err'
elif result.get('changed'):
level = 'notice'
else:
level = 'info'
yield {
"log": {
'sources': {
'source': task.get('name'),
},
'messages': {
'message': json.dumps(result, sort_keys=True),
},
'level': level,
}
}
def get_time():
"""
Return the time for measuring duration. Prefers monotonic time but
falls back to the regular time on older Python versions.
"""
try:
return time.monotonic()
except AttributeError:
return time.time()
def get_now():
"""
Return the current timestamp as a string to be sent over the network.
The time is always in UTC *with* timezone information, so that Ruby
DateTime can easily parse it.
"""
return datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S+00:00")
class CallbackModule(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'notification'
CALLBACK_NAME = 'theforeman.foreman.foreman'
CALLBACK_NEEDS_WHITELIST = True
def __init__(self):
super(CallbackModule, self).__init__()
self.items = defaultdict(list)
self.facts = defaultdict(dict)
self.start_time = get_time()
def set_options(self, task_keys=None, var_options=None, direct=None):
super(CallbackModule, self).set_options(task_keys=task_keys, var_options=var_options, direct=direct)
if self.get_option('disable_callback'):
self._disable_plugin('Callback disabled by environment.')
self.report_type = self.get_option('report_type')
self.foreman_url = self.get_option('url')
self.proxy_url = self.get_option('proxy_url')
ssl_cert = self.get_option('client_cert')
ssl_key = self.get_option('client_key')
self.dir_store = self.get_option('dir_store')
if not HAS_REQUESTS:
self._disable_plugin(u'The `requests` python module is not installed')
self.session = requests.Session()
if self.foreman_url.startswith('https://'):
if not os.path.exists(ssl_cert):
self._disable_plugin(u'FOREMAN_SSL_CERT %s not found.' % ssl_cert)
if not os.path.exists(ssl_key):
self._disable_plugin(u'FOREMAN_SSL_KEY %s not found.' % ssl_key)
self.session.verify = self._ssl_verify(str(self.get_option('verify_certs')))
self.session.cert = (ssl_cert, ssl_key)
def _disable_plugin(self, msg):
self.disabled = True
if msg:
self._display.warning(msg + u' Disabling the Foreman callback plugin.')
else:
self._display.warning(u'Disabling the Foreman callback plugin.')
def _ssl_verify(self, option):
try:
verify = to_bool(option)
except TypeError:
verify = option
if verify is False: # is only set to bool if try block succeeds
requests.packages.urllib3.disable_warnings()
self._display.warning(
u"SSL verification of %s disabled" % self.foreman_url,
)
return verify
def _send_data(self, data_type, report_type, host, data):
if data_type == 'facts':
url = self.foreman_url + '/api/v2/hosts/facts'
elif data_type == 'report' and report_type == 'foreman':
url = self.foreman_url + '/api/v2/config_reports'
elif data_type == 'report' and report_type == 'proxy':
url = self.proxy_url + '/reports/ansible'
else:
self._display.warning(u'Unknown report_type: {rt}'.format(rt=report_type))
if len(self.dir_store) > 0:
filename = u'{host}.json'.format(host=to_text(host))
filename = os.path.join(self.dir_store, filename)
with open(filename, 'w') as f:
json.dump(data, f, indent=2, sort_keys=True)
else:
try:
response = self.session.post(url=url, json=data)
response.raise_for_status()
except requests.exceptions.RequestException as err:
self._display.warning(u'Sending data to Foreman at {url} failed for {host}: {err}'.format(
host=to_text(host), err=to_text(err), url=to_text(self.foreman_url)))
def send_facts(self):
"""
Sends facts to Foreman, to be parsed by foreman_ansible fact
parser. The default fact importer should import these facts
properly.
"""
# proxy parses facts from report directly
if self.report_type == "proxy":
return
for host, facts in self.facts.items():
facts = {
"name": host,
"facts": {
"ansible_facts": facts,
"_type": "ansible",
"_timestamp": get_now(),
},
}
self._send_data('facts', 'foreman', host, facts)
def send_reports_proxy_host_report(self, stats):
"""
Send reports to Foreman Smart Proxy running Host Reports
plugin. The format is native Ansible report without any
changes.
"""
for host in stats.processed.keys():
report = {
"host": host,
"reported_at": get_now(),
"metrics": {
"time": {
"total": int(get_time() - self.start_time)
}
},
"summary": stats.summarize(host),
"results": self.items[host],
"check_mode": self.check_mode,
}
self._send_data('report', 'proxy', host, report)
self.items[host] = []
def send_reports_foreman(self, stats):
"""
Send reports to Foreman to be parsed by its config report
importer. The data is in a format that Foreman can handle
without writing another report importer.
"""
for host in stats.processed.keys():
total = stats.summarize(host)
report = {
"config_report": {
"host": host,
"reported_at": get_now(),
"metrics": {
"time": {
"total": int(get_time() - self.start_time)
}
},
"status": {
"applied": total['changed'],
"failed": total['failures'] + total['unreachable'],
"skipped": total['skipped'],
},
"logs": list(build_log_foreman(self.items[host])),
"reporter": "ansible",
"check_mode": self.check_mode,
}
}
if self.check_mode:
report['config_report']['status']['pending'] = total['changed']
report['config_report']['status']['applied'] = 0
self._send_data('report', 'foreman', host, report)
self.items[host] = []
def send_reports(self, stats):
if self.report_type == "foreman":
self.send_reports_foreman(stats)
elif self.report_type == "proxy":
self.send_reports_proxy_host_report(stats)
else:
self._display.warning(u'Unknown foreman endpoint type: {type}'.format(type=self.report_type))
def drop_nones(self, d):
"""Recursively drop Nones or empty dicts/arrays in dict d and return a new dict"""
dd = {}
for k, v in d.items():
if isinstance(v, dict) and v:
dd[k] = self.drop_nones(v)
elif isinstance(v, list) and len(v) == 1 and v[0] == {}:
pass
elif isinstance(v, (list, set, tuple)) and v:
dd[k] = type(v)(self.drop_nones(vv) if isinstance(vv, dict) else vv
for vv in v)
elif not isinstance(v, (dict, list, set, tuple)) and v is not None:
dd[k] = v
return dd
def append_result(self, result, failed=False):
result_info = result._result
task_info = result._task.serialize()
task_info['args'] = None
value = {}
value['result'] = result_info
value['task'] = task_info
value['failed'] = failed
if self.report_type == "proxy":
value = self.drop_nones(value)
host = result._host.get_name()
self.items[host].append(value)
self.check_mode = result._task.check_mode
if 'ansible_facts' in result_info:
self.facts[host].update(result_info['ansible_facts'])
# Ansible callback API
def v2_runner_on_failed(self, result, ignore_errors=False):
self.append_result(result, True)
def v2_runner_on_unreachable(self, result):
self.append_result(result, True)
def v2_runner_on_async_ok(self, result):
self.append_result(result)
def v2_runner_on_async_failed(self, result):
self.append_result(result, True)
def v2_playbook_on_stats(self, stats):
self.send_facts()
self.send_reports(stats)
def v2_runner_on_ok(self, result):
self.append_result(result)

View File

@@ -0,0 +1,381 @@
# (c) 2019, Evgeni Golov <evgeni@redhat.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import absolute_import, division, print_function
__metaclass__ = type
class ModuleDocFragment(object):
# Foreman documentation fragment
DOCUMENTATION = '''
requirements:
- requests
options:
server_url:
description:
- URL of the Foreman server.
- If the value is not specified in the task, the value of environment variable C(FOREMAN_SERVER_URL) will be used instead.
required: true
type: str
username:
description:
- Username accessing the Foreman server.
- If the value is not specified in the task, the value of environment variable C(FOREMAN_USERNAME) will be used instead.
required: true
type: str
password:
description:
- Password of the user accessing the Foreman server.
- If the value is not specified in the task, the value of environment variable C(FOREMAN_PASSWORD) will be used instead.
required: true
type: str
validate_certs:
description:
- Whether or not to verify the TLS certificates of the Foreman server.
- If the value is not specified in the task, the value of environment variable C(FOREMAN_VALIDATE_CERTS) will be used instead.
default: true
type: bool
'''
NESTED_PARAMETERS = '''
options:
parameters:
description:
- Entity domain specific host parameters
required: false
type: list
elements: dict
suboptions:
name:
description:
- Name of the parameter
required: true
type: str
value:
description:
- Value of the parameter
required: true
type: raw
parameter_type:
description:
- Type of the parameter
default: 'string'
choices:
- 'string'
- 'boolean'
- 'integer'
- 'real'
- 'array'
- 'hash'
- 'yaml'
- 'json'
type: str
'''
OS_FAMILY = '''
options:
os_family:
description:
- The OS family the entity shall be assigned with.
required: false
choices:
- AIX
- Altlinux
- Archlinux
- Coreos
- Debian
- Fcos
- Freebsd
- Gentoo
- Junos
- NXOS
- Rancheros
- Redhat
- Rhcos
- Solaris
- Suse
- VRP
- Windows
- Xenserver
type: str
'''
TAXONOMY = '''
options:
organizations:
description: List of organizations the entity should be assigned to
type: list
elements: str
locations:
description: List of locations the entity should be assigned to
type: list
elements: str
'''
ENTITY_STATE = '''
options:
state:
description:
- State of the entity
default: present
choices:
- present
- absent
type: str
'''
ENTITY_STATE_WITH_DEFAULTS = '''
options:
state:
description:
- State of the entity
- C(present_with_defaults) will ensure the entity exists, but won't update existing ones
default: present
choices:
- present
- present_with_defaults
- absent
type: str
'''
HOST_OPTIONS = '''
options:
compute_resource:
description: Compute resource name
required: false
type: str
compute_profile:
description: Compute profile name
required: false
type: str
domain:
description: Domain name
required: false
type: str
subnet:
description: IPv4 Subnet name
required: false
type: str
subnet6:
description: IPv6 Subnet name
required: false
type: str
root_pass:
description:
- Root password.
- Will result in the entity always being updated, as the current password cannot be retrieved.
type: str
required: false
realm:
description: Realm name
required: false
type: str
architecture:
description: Architecture name
required: False
type: str
medium:
aliases: [ media ]
description:
- Medium name
- Mutually exclusive with I(kickstart_repository).
required: False
type: str
pxe_loader:
description: PXE Bootloader
required: false
choices:
- PXELinux BIOS
- PXELinux UEFI
- Grub UEFI
- Grub2 BIOS
- Grub2 ELF
- Grub2 UEFI
- Grub2 UEFI SecureBoot
- Grub2 UEFI HTTP
- Grub2 UEFI HTTPS
- Grub2 UEFI HTTPS SecureBoot
- iPXE Embedded
- iPXE UEFI HTTP
- iPXE Chain BIOS
- iPXE Chain UEFI
- None
type: str
ptable:
description: Partition table name
required: False
type: str
environment:
description: Puppet environment name
required: false
type: str
puppetclasses:
description: List of puppet classes to include in this host group. Must exist for hostgroup's puppet environment.
required: false
type: list
elements: str
config_groups:
description: Config groups list
required: false
type: list
elements: str
puppet_proxy:
description: Puppet server proxy name
required: false
type: str
puppet_ca_proxy:
description: Puppet CA proxy name
required: false
type: str
openscap_proxy:
description:
- OpenSCAP proxy name.
- Only available when the OpenSCAP plugin is installed.
required: false
type: str
content_source:
description:
- Content source.
- Only available for Katello installations.
required: false
type: str
lifecycle_environment:
description:
- Lifecycle environment.
- Only available for Katello installations.
required: false
type: str
kickstart_repository:
description:
- Kickstart repository name.
- You need to provide this to use the "Synced Content" feature.
- Mutually exclusive with I(medium).
- Only available for Katello installations.
required: false
type: str
content_view:
description:
- Content view.
- Only available for Katello installations.
required: false
type: str
activation_keys:
description:
- Activation Keys used for deployment.
- Comma separated list.
- Only available for Katello installations.
required: false
type: str
'''
ORGANIZATION = '''
options:
organization:
description:
- Organization that the entity is in
required: true
type: str
'''
SCAP_DATASTREAM = '''
options:
scap_file:
description:
- File containing XML DataStream content.
- Required when creating a new DataStream.
required: false
type: path
original_filename:
description:
- Original file name of the XML file.
- If unset, the filename of I(scap_file) will be used.
required: false
type: str
'''
OPERATINGSYSTEMS = '''
options:
operatingsystems:
description:
- List of operating systems the entity should be assigned to.
- Operating systems are looked up by their title which is composed as "<name> <major>.<minor>".
- You can omit the version part as long as you only have one operating system by that name.
required: false
type: list
elements: str
'''
OPERATINGSYSTEM = '''
options:
operatingsystem:
description:
- Operating systems are looked up by their title which is composed as "<name> <major>.<minor>".
- You can omit the version part as long as you only have one operating system by that name.
type: str
required: False
'''
INFOMODULE = '''
options:
name:
description:
- Name of the resource to fetch information for.
- Mutually exclusive with I(search).
required: false
type: str
location:
description:
- Label of the Location to scope the search for.
required: false
type: str
organization:
description:
- Name of the Organization to scope the search for.
required: false
type: str
search:
description:
- Search query to use
- If None, and I(name) is not set, all resources are returned.
- Mutually exclusive with I(name).
type: str
'''
INFOMODULEWITHOUTNAME = '''
options:
location:
description:
- Label of the Location to scope the search for.
required: false
type: str
organization:
description:
- Name of the Organization to scope the search for.
required: false
type: str
search:
description:
- Search query to use
- If None, all resources are returned.
type: str
'''
KATELLOINFOMODULE = '''
options:
organization:
required: true
'''

View File

@@ -0,0 +1,21 @@
DOCUMENTATION:
name: cp_label
author: Matthias Dellweg
version_added: '0.1.0'
short_description: Convert strings to Candlepin labels
description:
- Converts an arbitrary string to a valid Candlepin label
options:
_input:
description: String that should be converted
type: string
required: true
EXAMPLES: |
organization_label: "{{ 'Default Organization' | cp_label }}"
# => 'Default_Organization'
RETURN:
_value:
description: The converted Candlepin label
type: string

View File

@@ -0,0 +1,24 @@
# Copyright (c) 2019 Matthias Dellweg
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
def cp_label(value):
p = re.compile(r'[^-\w]+')
return p.sub('_', value)
# ---- Ansible filters ----
class FilterModule(object):
''' Foreman filter '''
def filters(self):
return {
'cp_label': cp_label,
}

View File

@@ -0,0 +1,671 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2016 Guido Günther <agx@sigxcpu.org>, Daniel Lobato Garcia <dlobatog@redhat.com>
# Copyright (c) 2018 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# pylint: disable=raise-missing-from
# pylint: disable=super-with-arguments
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
name: foreman
short_description: Foreman inventory source
requirements:
- requests >= 1.1
description:
- Get inventory hosts from Foreman.
- Uses a YAML configuration file that ends with ``foreman.(yml|yaml)``.
extends_documentation_fragment:
- inventory_cache
- constructed
options:
plugin:
description: token that ensures this is a source file for the C(foreman) plugin.
required: True
choices: ['theforeman.foreman.foreman']
url:
description:
- URL of the Foreman server.
default: 'http://localhost:3000'
env:
- name: FOREMAN_SERVER
- name: FOREMAN_SERVER_URL
- name: FOREMAN_URL
user:
description:
- Username accessing the Foreman server.
required: True
env:
- name: FOREMAN_USER
- name: FOREMAN_USERNAME
password:
description:
- Password of the user accessing the Foreman server.
required: True
env:
- name: FOREMAN_PASSWORD
validate_certs:
description:
- Whether or not to verify the TLS certificates of the Foreman server.
type: boolean
default: True
env:
- name: FOREMAN_VALIDATE_CERTS
group_prefix:
description: prefix to apply to foreman groups
default: foreman_
vars_prefix:
description: prefix to apply to host variables, does not include facts nor params
default: foreman_
want_facts:
description: Toggle, if True the plugin will retrieve host facts from the server
type: boolean
default: False
want_params:
description: Toggle, if true the inventory will retrieve 'all_parameters' information as host vars
type: boolean
default: False
want_hostcollections:
description: Toggle, if true the plugin will create Ansible groups for host collections
type: boolean
default: False
legacy_hostvars:
description:
- Toggle, if true the plugin will build legacy hostvars present in the foreman script
- Places hostvars in a dictionary with keys `foreman`, `foreman_facts`, and `foreman_params`
type: boolean
default: False
host_filters:
description: This can be used to restrict the list of returned host
type: string
batch_size:
description: Number of hosts per batch that will be retrieved from the Foreman API per individual call
type: int
default: 250
use_reports_api:
description: Use Reporting API.
type: boolean
default: True
foreman:
description:
- Foreman server related configuration, deprecated.
- You can pass I(use_reports_api) in this dict to enable the Reporting API.
- Only for backward compatibility.
report:
description:
- Report API specific configuration, deprecated.
- You can pass the Report API specific params as part of this dict, instead of the main configuration.
- Only for backward compatibility.
type: dict
poll_interval:
description: The polling interval between 2 calls to the report_data endpoint while polling.
type: int
default: 10
max_timeout:
description: Timeout before falling back to old host API when using report_data endpoint while polling.
type: int
default: 600
want_organization:
description: Toggle, if true the inventory will fetch organization the host belongs to and create groupings for the same.
type: boolean
default: True
want_location:
description: Toggle, if true the inventory will fetch location the host belongs to and create groupings for the same.
type: boolean
default: True
want_ipv4:
description: Toggle, if true the inventory will fetch ipv4 address of the host.
type: boolean
default: True
want_ipv6:
description: Toggle, if true the inventory will fetch ipv6 address of the host.
type: boolean
default: True
want_host_group:
description: Toggle, if true the inventory will fetch host_groups and create groupings for the same.
type: boolean
default: True
want_subnet:
description: Toggle, if true the inventory will fetch subnet.
type: boolean
default: True
want_subnet_v6:
description: Toggle, if true the inventory will fetch ipv6 subnet.
type: boolean
default: True
want_smart_proxies:
description: Toggle, if true the inventory will fetch smart proxy that the host is registered to.
type: boolean
default: True
want_content_facet_attributes:
description: Toggle, if true the inventory will fetch content view details that the host is tied to.
type: boolean
default: True
hostnames:
description:
- A list of templates in order of precedence to compose inventory_hostname.
- If the template results in an empty string or None value it is ignored.
type: list
elements: str
default: ['name']
'''
EXAMPLES = '''
# my.foreman.yml
plugin: theforeman.foreman.foreman
url: https://foreman.example.com
user: ansibleinventory
password: changeme
host_filters: 'organization="Web Engineering"'
# shortname.foreman.yml
plugin: theforeman.foreman.foreman
url: https://foreman.example.com
user: ansibleinventory
password: changeme
hostnames:
- name.split('.')[0]
'''
import copy
import json
from ansible_collections.theforeman.foreman.plugins.module_utils._version import LooseVersion
from time import sleep
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils.common._collections_compat import MutableMapping
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, to_safe_group_name, Constructable
# 3rd party imports
try:
import requests
if LooseVersion(requests.__version__) < LooseVersion('1.1.0'):
raise ImportError
from requests.auth import HTTPBasicAuth
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
class InventoryModule(BaseInventoryPlugin, Cacheable, Constructable):
''' Host inventory parser for ansible using foreman as source. '''
NAME = 'theforeman.foreman.foreman'
def __init__(self):
super(InventoryModule, self).__init__()
self.MINIMUM_FOREMAN_VERSION_FOR_REPORTING_API = '1.24.0'
# from config
self.foreman_url = None
self.session = None
self.cache_key = None
self.use_cache = None
if not HAS_REQUESTS:
raise AnsibleError('This script requires python-requests 1.1 as a minimum version')
def verify_file(self, path):
valid = False
if super(InventoryModule, self).verify_file(path):
if path.endswith(('foreman.yaml', 'foreman.yml')):
valid = True
else:
self.display.vvv('Skipping due to inventory source not ending in "foreman.yaml" nor "foreman.yml"')
return valid
def _get_session(self):
if not self.session:
self.session = requests.session()
self.session.auth = HTTPBasicAuth(self.get_option('user'), to_bytes(self.get_option('password')))
self.session.verify = self.get_option('validate_certs')
return self.session
def _get_json(self, url, ignore_errors=None, params=None):
if not self.use_cache or url not in self._cache.get(self.cache_key, {}):
if self.cache_key not in self._cache:
self._cache[self.cache_key] = {url: ''}
results = []
s = self._get_session()
if params is None:
params = {}
params['page'] = 1
params['per_page'] = self.get_option('batch_size')
while True:
# workaround to address the follwing issues where 'verify' is overridden in Requests:
# - https://github.com/psf/requests/issues/3829
# - https://github.com/psf/requests/issues/5209
ret = s.get(url, params=params, verify=self.get_option('validate_certs'))
if ignore_errors and ret.status_code in ignore_errors:
break
ret.raise_for_status()
json = ret.json()
# process results
# FIXME: This assumes 'return type' matches a specific query,
# it will break if we expand the queries and they dont have different types
if 'results' not in json: # pylint: disable=no-else-break
# /hosts/:id dos not have a 'results' key
results = json
break
elif isinstance(json['results'], MutableMapping):
# /facts are returned as dict in 'results'
if not isinstance(results, MutableMapping):
results = {}
# check for end of paging
if len(json['results']) == 0:
break
for host, facts in json['results'].items():
if host not in results:
results[host] = {}
results[host].update(facts)
# get next page
params['page'] += 1
else:
# /hosts 's 'results' is a list of all hosts, returned is paginated
results = results + json['results']
# check for end of paging
if len(results) >= json['subtotal']:
break
if len(json['results']) == 0:
self.display.warning("Did not make any progress during loop. expected %d got %d" % (json['subtotal'], len(results)))
break
# get next page
params['page'] += 1
self._cache[self.cache_key][url] = results
return self._cache[self.cache_key][url]
def _get_hosts(self):
url = "%s/api/v2/hosts" % self.foreman_url
params = {}
if self.get_option('host_filters'):
params['search'] = self.get_option('host_filters')
return self._get_json(url, params=params)
def _get_all_params_by_id(self, hid):
url = "%s/api/v2/hosts/%s" % (self.foreman_url, hid)
ret = self._get_json(url, [404])
if not ret or not isinstance(ret, MutableMapping) or not ret.get('all_parameters', False):
return {}
return ret.get('all_parameters')
def _get_facts_by_id(self, hid):
url = "%s/api/v2/hosts/%s/facts" % (self.foreman_url, hid)
return self._get_json(url)
def _get_host_data_by_id(self, hid):
url = "%s/api/v2/hosts/%s" % (self.foreman_url, hid)
return self._get_json(url)
def _get_facts(self, host):
"""Fetch all host facts of the host"""
ret = self._get_facts_by_id(host['id'])
if len(ret.values()) == 0:
facts = {}
elif len(ret.values()) == 1:
facts = list(ret.values())[0]
else:
raise ValueError("More than one set of facts returned for '%s'" % host)
return facts
def _get_hostvars(self, host, vars_prefix='', omitted_vars=()):
hostvars = {}
for k, v in host.items():
if k not in omitted_vars:
hostvars[vars_prefix + k] = v
return hostvars
def _fetch_params(self):
options = ("no", "yes")
params = dict()
report_options = self.get_option('report') or {}
self.want_location = report_options.get('want_location', self.get_option('want_location'))
self.want_organization = report_options.get('want_organization', self.get_option('want_organization'))
self.want_IPv4 = report_options.get('want_ipv4', self.get_option('want_ipv4'))
self.want_IPv6 = report_options.get('want_ipv6', self.get_option('want_ipv6'))
self.want_host_group = report_options.get('want_host_group', self.get_option('want_host_group'))
self.want_hostcollections = report_options.get('want_hostcollections', self.get_option('want_hostcollections'))
self.want_subnet = report_options.get('want_subnet', self.get_option('want_subnet'))
self.want_subnet_v6 = report_options.get('want_subnet_v6', self.get_option('want_subnet_v6'))
self.want_smart_proxies = report_options.get('want_smart_proxies', self.get_option('want_smart_proxies'))
self.want_content_facet_attributes = report_options.get('want_content_facet_attributes', self.get_option('want_content_facet_attributes'))
self.want_params = self.get_option('want_params')
self.want_facts = self.get_option('want_facts')
self.host_filters = self.get_option('host_filters')
params["Organization"] = options[self.want_organization]
params["Location"] = options[self.want_location]
params["IPv4"] = options[self.want_IPv4]
params["IPv6"] = options[self.want_IPv6]
params["Facts"] = options[self.want_facts]
params["Host Group"] = options[self.want_host_group]
params["Host Collections"] = options[self.want_hostcollections]
params["Subnet"] = options[self.want_subnet]
params["Subnet v6"] = options[self.want_subnet_v6]
params["Smart Proxies"] = options[self.want_smart_proxies]
params["Content Attributes"] = options[self.want_content_facet_attributes]
params["Host Parameters"] = options[self.want_params]
if self.host_filters:
params["Hosts"] = self.host_filters
return params
def _use_inventory_report(self):
use_inventory_report = self.get_option('use_reports_api')
# backward compatibility
try:
use_inventory_report = self.get_option('foreman').get('use_reports_api')
except Exception:
pass
if not use_inventory_report:
return False
status_url = "%s/api/v2/status" % self.foreman_url
result = self._get_json(status_url)
foreman_version = (LooseVersion(result.get('version')) >= LooseVersion(self.MINIMUM_FOREMAN_VERSION_FOR_REPORTING_API))
return foreman_version
def _post_request(self):
url = "%s/ansible/api/v2/ansible_inventories/schedule" % self.foreman_url
params = {'input_values': self._fetch_params()}
if self.use_cache and url in self._cache.get(self.cache_key, {}):
return self._cache[self.cache_key][url]
if self.cache_key not in self._cache:
self._cache[self.cache_key] = {}
session = self._get_session()
self.poll_interval = self.get_option('poll_interval')
self.max_timeout = self.get_option('max_timeout')
# backward compatibility
try:
self.poll_interval = int(self.get_option('report').get('poll_interval'))
self.max_timeout = int(self.get_option('report').get('max_timeout'))
except Exception:
pass
max_polls = self.max_timeout / self.poll_interval
ret = session.post(url, json=params)
if not ret:
raise Exception("Error scheduling inventory report on foreman. Please check foreman logs!")
data_url = "{0}/{1}".format(self.foreman_url, ret.json().get('data_url'))
polls = 0
response = session.get(data_url)
while response:
if response.status_code != 204 or polls > max_polls:
break
sleep(self.poll_interval)
polls += 1
response = session.get(data_url)
if not response:
raise Exception("Error receiving inventory report from foreman. Please check foreman logs!")
elif (response.status_code == 204 and polls > max_polls):
raise Exception("Timeout receiving inventory report from foreman. Check foreman server and max_timeout in foreman.yml")
else:
self._cache[self.cache_key][url] = json.loads(response.json())
return self._cache[self.cache_key][url]
def _populate(self):
if self._use_inventory_report():
self._populate_report_api()
else:
self._populate_host_api()
def _get_hostname(self, properties, hostnames, strict=False):
hostname = None
errors = []
for preference in hostnames:
try:
hostname = self._compose(preference, properties)
except Exception as e: # pylint: disable=broad-except
if strict:
raise AnsibleError("Could not compose %s as hostnames - %s" % (preference, to_native(e)))
else:
errors.append(
(preference, str(e))
)
if hostname:
return to_text(hostname)
raise AnsibleError(
'Could not template any hostname for host, errors for each preference: %s' % (
', '.join(['%s: %s' % (pref, err) for pref, err in errors])
)
)
def _populate_report_api(self):
self.groups = dict()
self.hosts = dict()
try:
# We need a deep copy of the data, as we modify it below and this would also modify the cache
host_data = copy.deepcopy(self._post_request())
except Exception as exc:
self.display.warning("Failed to use Reports API, falling back to Hosts API: {0}".format(exc))
self._populate_host_api()
return
self.group_prefix = self.get_option('group_prefix')
hostnames = self.get_option('hostnames')
strict = self.get_option('strict')
for host in host_data:
if not host:
continue
composed_host_name = self._get_hostname(host, hostnames, strict=strict)
if (composed_host_name in self._cache.keys()):
continue
host_name = self.inventory.add_host(composed_host_name)
group_name = host.get('hostgroup_title', host.get('hostgroup_name'))
if group_name:
group_name = to_safe_group_name('%s%s' % (self.get_option('group_prefix'), group_name.lower().replace(" ", "")))
group_name = self.inventory.add_group(group_name)
self.inventory.add_child(group_name, host_name)
host_params = host.pop('host_parameters', {})
fact_list = host.pop('facts', {})
if self.get_option('legacy_hostvars'):
hostvars = self._get_hostvars(host)
self.inventory.set_variable(host_name, 'foreman', hostvars)
else:
omitted_vars = ('name', 'hostgroup_title', 'hostgroup_name')
hostvars = self._get_hostvars(host, self.get_option('vars_prefix'), omitted_vars)
for k, v in hostvars.items():
try:
self.inventory.set_variable(host_name, k, v)
except ValueError as e:
self.display.warning("Could not set host info hostvar for %s, skipping %s: %s" % (host, k, to_text(e)))
content_facet_attributes = host.get('content_attributes', {}) or {}
if self.get_option('want_facts'):
self.inventory.set_variable(host_name, 'foreman_facts', fact_list)
# Create ansible groups for hostgroup
group = 'host_group'
group_name = host.get(group)
if group_name:
parent_name = None
group_label_parts = []
for part in group_name.split('/'):
group_label_parts.append(part.lower().replace(" ", ""))
gname = to_safe_group_name('%s%s' % (self.get_option('group_prefix'), '/'.join(group_label_parts)))
result_gname = self.inventory.add_group(gname)
if parent_name:
self.inventory.add_child(parent_name, result_gname)
parent_name = result_gname
self.inventory.add_child(result_gname, host_name)
# Create ansible groups for environment, location and organization
for group in ['environment', 'location', 'organization']:
val = host.get('%s' % group)
if val:
safe_key = to_safe_group_name('%s%s_%s' % (
to_text(self.group_prefix),
group,
to_text(val).lower()
))
env_lo_org = self.inventory.add_group(safe_key)
self.inventory.add_child(env_lo_org, host_name)
for group in ['lifecycle_environment', 'content_view']:
val = content_facet_attributes.get('%s_name' % group)
if val:
safe_key = to_safe_group_name('%s%s_%s' % (
to_text(self.group_prefix),
group,
to_text(val).lower()
))
le_cv_group = self.inventory.add_group(safe_key)
self.inventory.add_child(le_cv_group, host_name)
params = host_params
if self.want_hostcollections:
hostcollections = host.get('host_collections')
if hostcollections:
# Create Ansible groups for host collections
for hostcollection in hostcollections:
try:
host_collection_group_name = to_safe_group_name('%shostcollection_%s' % (
to_text(self.group_prefix),
to_text(hostcollection).lower()
))
hostcollection_group = self.inventory.add_group(host_collection_group_name)
self.inventory.add_child(hostcollection_group, host_name)
except ValueError as e:
self.display.warning("Could not create groups for host collections for %s, skipping: %s" % (host_name, to_text(e)))
# set host vars from params
if self.get_option('want_params'):
if self.get_option('legacy_hostvars'):
self.inventory.set_variable(host_name, 'foreman_params', params)
else:
for k, v in params.items():
try:
self.inventory.set_variable(host_name, k, v)
except ValueError as e:
self.display.warning("Could not set hostvar %s to '%s' for the '%s' host, skipping: %s" %
(k, to_native(v), host, to_native(e)))
hostvars = self.inventory.get_host(host_name).get_vars()
self._set_composite_vars(self.get_option('compose'), hostvars, host_name, strict)
self._add_host_to_composed_groups(self.get_option('groups'), hostvars, host_name, strict)
self._add_host_to_keyed_groups(self.get_option('keyed_groups'), hostvars, host_name, strict)
def _populate_host_api(self):
hostnames = self.get_option('hostnames')
strict = self.get_option('strict')
for host in self._get_hosts():
if not host:
continue
composed_host_name = self._get_hostname(host, hostnames, strict=strict)
if (composed_host_name in self._cache.keys()):
continue
host_name = self.inventory.add_host(composed_host_name)
# create directly mapped groups
group_name = host.get('hostgroup_title', host.get('hostgroup_name'))
if group_name:
parent_name = None
group_label_parts = []
for part in group_name.split('/'):
group_label_parts.append(part.lower().replace(" ", ""))
gname = to_safe_group_name('%s%s' % (self.get_option('group_prefix'), '/'.join(group_label_parts)))
result_gname = self.inventory.add_group(gname)
if parent_name:
self.inventory.add_child(parent_name, result_gname)
parent_name = result_gname
self.inventory.add_child(result_gname, host_name)
if self.get_option('legacy_hostvars'):
hostvars = self._get_hostvars(host)
self.inventory.set_variable(host_name, 'foreman', hostvars)
else:
omitted_vars = ('name', 'hostgroup_title', 'hostgroup_name')
hostvars = self._get_hostvars(host, self.get_option('vars_prefix'), omitted_vars)
for k, v in hostvars.items():
try:
self.inventory.set_variable(host_name, k, v)
except ValueError as e:
self.display.warning("Could not set host info hostvar for %s, skipping %s: %s" % (host, k, to_text(e)))
# set host vars from params
if self.get_option('want_params'):
params = self._get_all_params_by_id(host['id'])
filtered_params = {}
for p in params:
if 'name' in p and 'value' in p:
filtered_params[p['name']] = p['value']
if self.get_option('legacy_hostvars'):
self.inventory.set_variable(host_name, 'foreman_params', filtered_params)
else:
for k, v in filtered_params.items():
try:
self.inventory.set_variable(host_name, k, v)
except ValueError as e:
self.display.warning("Could not set hostvar %s to '%s' for the '%s' host, skipping: %s" %
(k, to_native(v), host, to_native(e)))
# set host vars from facts
if self.get_option('want_facts'):
self.inventory.set_variable(host_name, 'foreman_facts', self._get_facts(host))
# create group for host collections
if self.get_option('want_hostcollections'):
host_data = self._get_host_data_by_id(host['id'])
hostcollections = host_data.get('host_collections')
if hostcollections:
# Create Ansible groups for host collections
for hostcollection in hostcollections:
try:
hostcollection_group = to_safe_group_name('%shostcollection_%s' % (self.get_option('group_prefix'),
hostcollection['name'].lower().replace(" ", "")))
hostcollection_group = self.inventory.add_group(hostcollection_group)
self.inventory.add_child(hostcollection_group, host_name)
except ValueError as e:
self.display.warning("Could not create groups for host collections for %s, skipping: %s" % (host_name, to_text(e)))
hostvars = self.inventory.get_host(host_name).get_vars()
self._set_composite_vars(self.get_option('compose'), hostvars, host_name, strict)
self._add_host_to_composed_groups(self.get_option('groups'), hostvars, host_name, strict)
self._add_host_to_keyed_groups(self.get_option('keyed_groups'), hostvars, host_name, strict)
def parse(self, inventory, loader, path, cache=True):
super(InventoryModule, self).parse(inventory, loader, path)
# read config from file, this sets 'options'
self._read_config_data(path)
# get connection host
self.foreman_url = self.get_option('url')
self.cache_key = self.get_cache_key(path)
self.use_cache = cache and self.get_option('cache')
# actually populate inventory
self._populate()

View File

@@ -0,0 +1,907 @@
# pylint: disable=ansible-format-automatic-specification,raise-missing-from
from __future__ import absolute_import, division, print_function
__metaclass__ = type
try:
from typing import Any, Iterable, List, Optional, Tuple # pylint: disable=unused-import
except ImportError:
pass
"""
Apypie Action module
"""
try:
base_string = basestring
except NameError: # Python 3 has no base_string
base_string = str # pylint: disable=invalid-name,redefined-builtin
class Action(object):
"""
Apipie Action
"""
def __init__(self, name, resource, api):
# type: (str, str, Api) -> None
self.name = name
self.resource = resource
self.api = api
@property
def apidoc(self):
# type: () -> dict
"""
The apidoc of this action.
:returns: The apidoc.
"""
resource_methods = self.api.apidoc['docs']['resources'][self.resource]['methods']
return [method for method in resource_methods if method['name'] == self.name][0]
@property
def routes(self):
# type: () -> List[Route]
"""
The routes this action can be invoked by.
:returns: The routes
"""
return [Route(route['api_url'], route['http_method'], route['short_description']) for route in self.apidoc['apis']]
@property
def params(self):
# type: () -> List[Param]
"""
The params accepted by this action.
:returns: The params.
"""
return [Param(**param) for param in self.apidoc['params']]
@property
def examples(self):
# type: () -> List[Example]
"""
The examples of this action.
:returns: The examples.
"""
return [Example.parse(example) for example in self.apidoc['examples']]
def call(self, params=None, headers=None, options=None, data=None, files=None): # pylint: disable=too-many-arguments
# type: (dict, Optional[dict], Optional[dict], Optional[Any], Optional[dict]) -> dict
"""
Call the API to execute the action.
:param params: The params that should be passed to the API.
:param headers: Additional headers to be passed to the API.
:param options: Options
:param data: Binary data to be submitted to the API.
:param files: Files to be submitted to the API.
:returns: The API response.
"""
return self.api.call(self.resource, self.name, params, headers, options, data, files)
def find_route(self, params=None):
# type: (Optional[dict]) -> Route
"""
Find the best matching route for a given set of params.
:param params: Params that should be submitted to the API.
:returns: The best route.
"""
param_keys = set(self.filter_empty_params(params).keys())
sorted_routes = sorted(self.routes, key=lambda route: [-1 * len(route.params_in_path), route.path])
for route in sorted_routes:
if set(route.params_in_path) <= param_keys:
return route
return sorted_routes[-1]
def validate(self, values, data=None, files=None):
# type: (dict, Optional[Any], Optional[dict]) -> None
"""
Validate a given set of parameter values against the required set of parameters.
:param values: The values to validate.
:param data: Additional binary data to validate.
:param files: Additional files to validate.
"""
self._validate(self.params, values, data, files)
@staticmethod
def _add_to_path(path=None, additions=None):
# type: (Optional[str], Optional[List[str]]) -> str
if path is None:
path = ''
if additions is None:
additions = []
for addition in additions:
if path == '':
path = "{}".format(addition)
else:
path = "{}[{}]".format(path, addition)
return path
def _validate(self, params, values, data=None, files=None, path=None): # pylint: disable=too-many-arguments,too-many-locals
# type: (Iterable[Param], dict, Optional[Any], Optional[dict], Optional[str]) -> None
if not isinstance(values, dict):
raise InvalidArgumentTypesError
given_params = set(values.keys())
given_files = set((files or {}).keys())
given_data = set((data or {}).keys())
required_params = {param.name for param in params if param.required}
missing_params = required_params - given_params - given_files - given_data
if missing_params:
missing_params_with_path = [self._add_to_path(path, [param]) for param in missing_params]
message = "The following required parameters are missing: {}".format(', '.join(missing_params_with_path))
raise MissingArgumentsError(message)
for param, value in values.items():
param_descriptions = [p for p in params if p.name == param]
if param_descriptions:
param_description = param_descriptions[0]
if param_description.params and value is not None:
if param_description.expected_type == 'array':
for num, item in enumerate(value):
self._validate(param_description.params, item, path=self._add_to_path(path, [param_description.name, str(num)]))
elif param_description.expected_type == 'hash':
self._validate(param_description.params, value, path=self._add_to_path(path, [param_description.name]))
if (param_description.expected_type == 'numeric' and isinstance(value, base_string)):
try:
value = int(value)
except ValueError:
# this will be caught in the next check
pass
if (not param_description.allow_nil and value is None):
raise ValueError("{} can't be {}".format(param, value))
# pylint: disable=too-many-boolean-expressions
if (value is not None
and ((param_description.expected_type == 'boolean' and not isinstance(value, bool) and not (isinstance(value, int) and value in [0, 1]))
or (param_description.expected_type == 'numeric' and not isinstance(value, int))
or (param_description.expected_type == 'string' and not isinstance(value, (base_string, int))))):
raise ValueError("{} ({}): {}".format(param, value, param_description.validator))
@staticmethod
def filter_empty_params(params=None):
# type: (Optional[dict]) -> dict
"""
Filter out any params that have no value.
:param params: The params to filter.
:returns: The filtered params.
"""
result = {}
if params is not None:
if isinstance(params, dict):
result = {k: v for k, v in params.items() if v is not None}
else:
raise InvalidArgumentTypesError
return result
def prepare_params(self, input_dict):
# type: (dict) -> dict
"""
Transform a dict with data into one that can be accepted as params for calling the action.
This will ignore any keys that are not accepted as params when calling the action.
It also allows generating nested params without forcing the user to care about them.
:param input_dict: a dict with data that should be used to fill in the params
:return: :class:`dict` object
:rtype: dict
Usage::
>>> action.prepare_params({'id': 1})
{'user': {'id': 1}}
"""
params = self._prepare_params(self.params, input_dict)
route_params = self._prepare_route_params(input_dict)
params.update(route_params)
return params
def _prepare_params(self, action_params, input_dict):
# type: (Iterable[Param], dict) -> dict
result = {}
for param in action_params:
if param.expected_type == 'hash' and param.params:
nested_dict = input_dict.get(param.name, input_dict)
nested_result = self._prepare_params(param.params, nested_dict)
if nested_result:
result[param.name] = nested_result
elif param.name in input_dict:
result[param.name] = input_dict[param.name]
return result
def _prepare_route_params(self, input_dict):
# type: (dict) -> dict
result = {}
route = self.find_route(input_dict)
for url_param in route.params_in_path:
if url_param in input_dict:
result[url_param] = input_dict[url_param]
return result
"""
Apypie Api module
"""
import errno
import glob
import json
try:
import requests
except ImportError:
pass
try:
from json.decoder import JSONDecodeError # type: ignore
except ImportError:
JSONDecodeError = ValueError # type: ignore
import os
try:
from urlparse import urljoin # type: ignore
except ImportError:
from urllib.parse import urljoin # type: ignore
def _qs_param(param):
# type: (Any) -> Any
if isinstance(param, bool):
return str(param).lower()
return param
class Api(object):
"""
Apipie API bindings
:param uri: base URL of the server
:param username: username to access the API
:param password: username to access the API
:param api_version: version of the API. Defaults to `1`
:param language: prefered locale for the API description
:param apidoc_cache_base_dir: base directory for building apidoc_cache_dir. Defaults to `~/.cache/apipie_bindings`.
:param apidoc_cache_dir: where to cache the JSON description of the API. Defaults to `apidoc_cache_base_dir/<URI>`.
:param apidoc_cache_name: name of the cache file. If there is cache in the `apidoc_cache_dir`, it is used. Defaults to `default`.
:param verify_ssl: should the SSL certificate be verified. Defaults to `True`.
Usage::
>>> import apypie
>>> api = apypie.Api(uri='https://api.example.com', username='admin', password='changeme')
"""
def __init__(self, **kwargs):
self.uri = kwargs.get('uri')
self.api_version = kwargs.get('api_version', 1)
self.language = kwargs.get('language')
# Find where to put the cache by default according to the XDG spec
# Not using just get('XDG_CACHE_HOME', '~/.cache') because the spec says
# that the defaut should be used if "$XDG_CACHE_HOME is either not set or empty"
xdg_cache_home = os.environ.get('XDG_CACHE_HOME', None)
if not xdg_cache_home:
xdg_cache_home = '~/.cache'
apidoc_cache_base_dir = kwargs.get('apidoc_cache_base_dir', os.path.join(os.path.expanduser(xdg_cache_home), 'apypie'))
apidoc_cache_dir_default = os.path.join(apidoc_cache_base_dir, self.uri.replace(':', '_').replace('/', '_'), 'v{}'.format(self.api_version))
self.apidoc_cache_dir = kwargs.get('apidoc_cache_dir', apidoc_cache_dir_default)
self.apidoc_cache_name = kwargs.get('apidoc_cache_name', self._find_cache_name())
self._session = requests.Session()
self._session.verify = kwargs.get('verify_ssl', True)
self._session.headers['Accept'] = 'application/json;version={}'.format(self.api_version)
self._session.headers['User-Agent'] = 'apypie (https://github.com/Apipie/apypie)'
if self.language:
self._session.headers['Accept-Language'] = self.language
if kwargs.get('username') and kwargs.get('password'):
self._session.auth = (kwargs['username'], kwargs['password'])
self._apidoc = None
@property
def apidoc(self):
# type: () -> dict
"""
The full apidoc.
The apidoc will be fetched from the server, if that didn't happen yet.
:returns: The apidoc.
"""
if self._apidoc is None:
self._apidoc = self._load_apidoc()
return self._apidoc
@property
def apidoc_cache_file(self):
# type: () -> str
"""
Full local path to the cached apidoc.
"""
return os.path.join(self.apidoc_cache_dir, '{0}{1}'.format(self.apidoc_cache_name, self.cache_extension))
def _cache_dir_contents(self):
# type: () -> Iterable[str]
return glob.iglob(os.path.join(self.apidoc_cache_dir, '*{}'.format(self.cache_extension)))
def _find_cache_name(self, default='default'):
cache_file = next(self._cache_dir_contents(), None)
cache_name = default
if cache_file:
cache_name = os.path.basename(cache_file)[:-len(self.cache_extension)]
return cache_name
def validate_cache(self, cache_name):
# type: (str) -> None
"""
Ensure the cached apidoc matches the one presented by the server.
:param cache_name: The name of the apidoc on the server.
"""
if cache_name is not None and cache_name != self.apidoc_cache_name:
self.clean_cache()
self.apidoc_cache_name = os.path.basename(os.path.normpath(cache_name))
def clean_cache(self):
# type: () -> None
"""
Remove any locally cached apidocs.
"""
self._apidoc = None
for filename in self._cache_dir_contents():
os.unlink(filename)
@property
def resources(self):
# type: () -> Iterable
"""
List of available resources.
Usage::
>>> api.resources
['comments', 'users']
"""
return sorted(self.apidoc['docs']['resources'].keys())
def resource(self, name):
# type: (str) -> Resource
"""
Get a resource.
:param name: the name of the resource to load
:return: :class:`Resource <Resource>` object
:rtype: apypie.Resource
Usage::
>>> api.resource('users')
"""
if name in self.resources:
return Resource(self, name)
message = "Resource '{}' does not exist in the API. Existing resources: {}".format(name, ', '.join(sorted(self.resources)))
raise KeyError(message)
def _load_apidoc(self):
# type: () -> dict
try:
with open(self.apidoc_cache_file, 'r') as apidoc_file:
api_doc = json.load(apidoc_file)
except (IOError, JSONDecodeError):
api_doc = self._retrieve_apidoc()
return api_doc
def _retrieve_apidoc(self):
# type: () -> dict
try:
os.makedirs(self.apidoc_cache_dir)
except OSError as err:
if err.errno != errno.EEXIST or not os.path.isdir(self.apidoc_cache_dir):
raise
response = None
if self.language:
response = self._retrieve_apidoc_call('/apidoc/v{0}.{1}.json'.format(self.api_version, self.language), safe=True)
language_family = self.language.split('_')[0]
if not response and language_family != self.language:
response = self._retrieve_apidoc_call('/apidoc/v{0}.{1}.json'.format(self.api_version, language_family), safe=True)
if not response:
try:
response = self._retrieve_apidoc_call('/apidoc/v{}.json'.format(self.api_version))
except Exception as exc:
raise DocLoadingError("""Could not load data from {0}: {1}
- is your server down?
- was rake apipie:cache run when using apipie cache? (typical production settings)""".format(self.uri, exc))
with open(self.apidoc_cache_file, 'w') as apidoc_file:
apidoc_file.write(json.dumps(response))
return response
def _retrieve_apidoc_call(self, path, safe=False):
try:
return self.http_call('get', path)
except requests.exceptions.HTTPError:
if not safe:
raise
def call(self, resource_name, action_name, params=None, headers=None, options=None, data=None, files=None): # pylint: disable=too-many-arguments
"""
Call an action in the API.
It finds most fitting route based on given parameters
with other attributes necessary to do an API call.
:param resource_name: name of the resource
:param action_name: action_name name of the action
:param params: Dict of parameters to be sent in the request
:param headers: Dict of headers to be sent in the request
:param options: Dict of options to influence the how the call is processed
* `skip_validation` (Bool) *false* - skip validation of parameters
:param data: Binary data to be sent in the request
:param files: Binary files to be sent in the request
:return: :class:`dict` object
:rtype: dict
Usage::
>>> api.call('users', 'show', {'id': 1})
"""
if options is None:
options = {}
if params is None:
params = {}
resource = Resource(self, resource_name)
action = resource.action(action_name)
if not options.get('skip_validation', False):
action.validate(params, data, files)
return self._call_action(action, params, headers, data, files)
def _call_action(self, action, params=None, headers=None, data=None, files=None): # pylint: disable=too-many-arguments
if params is None:
params = {}
route = action.find_route(params)
get_params = {key: value for key, value in params.items() if key not in route.params_in_path}
return self.http_call(
route.method,
route.path_with_params(params),
get_params,
headers, data, files)
def http_call(self, http_method, path, params=None, headers=None, data=None, files=None): # pylint: disable=too-many-arguments
"""
Execute an HTTP request.
:param params: Dict of parameters to be sent in the request
:param headers: Dict of headers to be sent in the request
:param data: Binary data to be sent in the request
:param files: Binary files to be sent in the request
:return: :class:`dict` object
:rtype: dict
"""
full_path = urljoin(self.uri, path)
kwargs = {
'verify': self._session.verify,
}
if headers:
kwargs['headers'] = headers
if params:
if http_method in ['get', 'head']:
kwargs['params'] = {k: _qs_param(v) for k, v in params.items()}
else:
kwargs['json'] = params
elif http_method in ['post', 'put', 'patch'] and not data and not files:
kwargs['json'] = {}
if files:
kwargs['files'] = files
if data:
kwargs['data'] = data
request = self._session.request(http_method, full_path, **kwargs)
request.raise_for_status()
self.validate_cache(request.headers.get('apipie-checksum'))
if request.status_code == requests.codes['no_content']:
return None
return request.json()
@property
def cache_extension(self):
"""
File extension for the local cache file.
Will include the language if set.
"""
if self.language:
ext = '.{}.json'.format(self.language)
else:
ext = '.json'
return ext
"""
Apypie Example module
"""
import re
EXAMPLE_PARSER = re.compile(r'(\w+)\s+([^\n]*)\n?(.*)\n(\d+)\n(.*)', re.DOTALL)
class Example(object): # pylint: disable=too-few-public-methods
"""
Apipie Example
"""
def __init__(self, http_method, path, args, status, response): # pylint: disable=too-many-arguments
# type: (str, str, str, str, str) -> None
self.http_method = http_method
self.path = path
self.args = args
self.status = int(status)
self.response = response
@classmethod
def parse(cls, example):
"""
Parse an example from an apidoc string
:returns: The parsed :class:`Example`
"""
parsed = EXAMPLE_PARSER.match(example)
return cls(*parsed.groups())
"""
Apypie Exceptions
"""
class DocLoadingError(Exception):
"""
Exception to be raised when apidoc could not be loaded.
"""
class MissingArgumentsError(Exception):
"""
Exception to be raised when required arguments are missing.
"""
class InvalidArgumentTypesError(Exception):
"""
Exception to be raised when arguments are of the wrong type.
"""
"""
Apypie Inflector module
Based on ActiveSupport Inflector (https://github.com/rails/rails.git)
Inflection rules taken from davidcelis's Inflections (https://github.com/davidcelis/inflections.git)
"""
import re
class Inflections(object):
"""
Inflections - rules how to convert words from singular to plural and vice versa.
"""
def __init__(self):
self.plurals = []
self.singulars = []
self.uncountables = []
self.humans = []
self.acronyms = {}
self.acronym_regex = r'/(?=a)b/'
def acronym(self, word):
# type: (str) -> None
"""
Add a new acronym.
"""
self.acronyms[word.lower()] = word
self.acronym_regex = '|'.join(self.acronyms.values())
def plural(self, rule, replacement):
# type: (str, str) -> None
"""
Add a new plural rule.
"""
if rule in self.uncountables:
self.uncountables.remove(rule)
if replacement in self.uncountables:
self.uncountables.remove(replacement)
self.plurals.insert(0, (rule, replacement))
def singular(self, rule, replacement):
# type: (str, str) -> None
"""
Add a new singular rule.
"""
if rule in self.uncountables:
self.uncountables.remove(rule)
if replacement in self.uncountables:
self.uncountables.remove(replacement)
self.singulars.insert(0, (rule, replacement))
def irregular(self, singular, plural):
# type: (str, str) -> None
"""
Add a new irregular rule
"""
if singular in self.uncountables:
self.uncountables.remove(singular)
if plural in self.uncountables:
self.uncountables.remove(plural)
sfirst = singular[0]
srest = singular[1:]
pfirst = plural[0]
prest = plural[1:]
if sfirst.upper() == pfirst.upper():
self.plural(r'(?i)({}){}$'.format(sfirst, srest), r'\1' + prest)
self.plural(r'(?i)({}){}$'.format(pfirst, prest), r'\1' + prest)
self.singular(r'(?i)({}){}$'.format(sfirst, srest), r'\1' + srest)
self.singular(r'(?i)({}){}$'.format(pfirst, prest), r'\1' + srest)
else:
self.plural(r'{}(?i){}$'.format(sfirst.upper(), srest), pfirst.upper() + prest)
self.plural(r'{}(?i){}$'.format(sfirst.lower(), srest), pfirst.lower() + prest)
self.plural(r'{}(?i){}$'.format(pfirst.upper(), prest), pfirst.upper() + prest)
self.plural(r'{}(?i){}$'.format(pfirst.lower(), prest), pfirst.lower() + prest)
self.singular(r'{}(?i){}$'.format(sfirst.upper(), srest), sfirst.upper() + srest)
self.singular(r'{}(?i){}$'.format(sfirst.lower(), srest), sfirst.lower() + srest)
self.singular(r'{}(?i){}$'.format(pfirst.upper(), prest), sfirst.upper() + srest)
self.singular(r'{}(?i){}$'.format(pfirst.lower(), prest), sfirst.lower() + srest)
def uncountable(self, *words):
"""
Add new uncountables.
"""
self.uncountables.extend(words)
def human(self, rule, replacement):
# type: (str, str) -> None
"""
Add a new humanize rule.
"""
self.humans.insert(0, (rule, replacement))
class Inflector(object):
"""
Inflector - perform inflections
"""
def __init__(self):
# type: () -> None
self.inflections = Inflections()
self.inflections.plural(r'$', 's')
self.inflections.plural(r'(?i)([sxz]|[cs]h)$', r'\1es')
self.inflections.plural(r'(?i)([^aeiouy]o)$', r'\1es')
self.inflections.plural(r'(?i)([^aeiouy])y$', r'\1ies')
self.inflections.singular(r'(?i)s$', r'')
self.inflections.singular(r'(?i)(ss)$', r'\1')
self.inflections.singular(r'([sxz]|[cs]h)es$', r'\1')
self.inflections.singular(r'([^aeiouy]o)es$', r'\1')
self.inflections.singular(r'(?i)([^aeiouy])ies$', r'\1y')
self.inflections.irregular('child', 'children')
self.inflections.irregular('man', 'men')
self.inflections.irregular('medium', 'media')
self.inflections.irregular('move', 'moves')
self.inflections.irregular('person', 'people')
self.inflections.irregular('self', 'selves')
self.inflections.irregular('sex', 'sexes')
self.inflections.uncountable('equipment', 'information', 'money', 'species', 'series', 'fish', 'sheep', 'police')
def pluralize(self, word):
# type: (str) -> str
"""
Pluralize a word.
"""
return self._apply_inflections(word, self.inflections.plurals)
def singularize(self, word):
# type: (str) -> str
"""
Singularize a word.
"""
return self._apply_inflections(word, self.inflections.singulars)
def _apply_inflections(self, word, rules):
# type: (str, Iterable[Tuple[str, str]]) -> str
result = word
if word != '' and result.lower() not in self.inflections.uncountables:
for (rule, replacement) in rules:
result = re.sub(rule, replacement, result)
if result != word:
break
return result
"""
Apypie Param module
"""
import re
HTML_STRIP = re.compile(r'<\/?[^>]+?>')
class Param(object): # pylint: disable=too-many-instance-attributes,too-few-public-methods
"""
Apipie Param
"""
def __init__(self, **kwargs):
self.allow_nil = kwargs.get('allow_nil')
self.description = HTML_STRIP.sub('', kwargs.get('description'))
self.expected_type = kwargs.get('expected_type')
self.full_name = kwargs.get('full_name')
self.name = kwargs.get('name')
self.params = [Param(**param) for param in kwargs.get('params', [])]
self.required = bool(kwargs.get('required'))
self.validator = kwargs.get('validator')
"""
Apypie Resource module
"""
class Resource(object):
"""
Apipie Resource
"""
def __init__(self, api, name):
# type: (Api, str) -> None
self.api = api
self.name = name
@property
def actions(self):
# type: () -> List
"""
Actions available for this resource.
:returns: The actions.
"""
return sorted([method['name'] for method in self.api.apidoc['docs']['resources'][self.name]['methods']])
def action(self, name):
# type: (str) -> Action
"""
Get an :class:`Action` for this resource.
:param name: The name of the action.
"""
if self.has_action(name):
return Action(name, self.name, self.api)
message = "Unknown action '{}'. Supported actions: {}".format(name, ', '.join(sorted(self.actions)))
raise KeyError(message)
def has_action(self, name):
# type: (str) -> bool
"""
Check whether the resource has a given action.
:param name: The name of the action.
"""
return name in self.actions
def call(self, action, params=None, headers=None, options=None, data=None, files=None): # pylint: disable=too-many-arguments
# type: (str, Optional[dict], Optional[dict], Optional[dict], Optional[Any], Optional[dict]) -> dict
"""
Call the API to execute an action for this resource.
:param action: The action to call.
:param params: The params that should be passed to the API.
:param headers: Additional headers to be passed to the API.
:param options: Options
:param data: Binary data to be submitted to the API.
:param files: Files to be submitted to the API.
:returns: The API response.
"""
return self.api.call(self.name, action, params, headers, options, data, files)
"""
Apypie Route module
"""
class Route(object):
"""
Apipie Route
"""
def __init__(self, path, method, description=""):
# type: (str, str, str) -> None
self.path = path
self.method = method.lower()
self.description = description
@property
def params_in_path(self):
# type: () -> List
"""
Params that can be passed in the path (URL) of the route.
:returns: The params.
"""
return [part[1:] for part in self.path.split('/') if part.startswith(':')]
def path_with_params(self, params=None):
# type: (Optional[dict]) -> str
"""
Fill in the params into the path.
:returns: The path with params.
"""
result = self.path
if params is not None:
for param in self.params_in_path:
if param in params:
result = result.replace(':{}'.format(param), str(params[param]))
else:
raise KeyError("missing param '{}' in parameters".format(param))
return result

View File

@@ -0,0 +1,335 @@
# Vendored copy of distutils/version.py from CPython 3.9.5
#
# Implements multiple version numbering conventions for the
# Python Module Distribution Utilities.
#
# PSF License (see PSF-license.txt or https://opensource.org/licenses/Python-2.0)
#
"""Provides classes to represent module version numbers (one class for
each style of version numbering). There are currently two such classes
implemented: StrictVersion and LooseVersion.
Every version number class implements the following interface:
* the 'parse' method takes a string and parses it to some internal
representation; if the string is an invalid version number,
'parse' raises a ValueError exception
* the class constructor takes an optional string argument which,
if supplied, is passed to 'parse'
* __str__ reconstructs the string that was passed to 'parse' (or
an equivalent string -- ie. one that will generate an equivalent
version number instance)
* __repr__ generates Python code to recreate the version number instance
* _cmp compares the current instance with either another instance
of the same class or a string (which will be parsed to an instance
of the same class, thus must follow the same rules)
"""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
try:
RE_FLAGS = re.VERBOSE | re.ASCII
except AttributeError:
RE_FLAGS = re.VERBOSE
class Version:
"""Abstract base class for version numbering classes. Just provides
constructor (__init__) and reproducer (__repr__), because those
seem to be the same for all version numbering classes; and route
rich comparisons to _cmp.
"""
def __init__(self, vstring=None):
if vstring:
self.parse(vstring)
def __repr__(self):
return "%s ('%s')" % (self.__class__.__name__, str(self))
def __eq__(self, other):
c = self._cmp(other)
if c is NotImplemented:
return c
return c == 0
def __lt__(self, other):
c = self._cmp(other)
if c is NotImplemented:
return c
return c < 0
def __le__(self, other):
c = self._cmp(other)
if c is NotImplemented:
return c
return c <= 0
def __gt__(self, other):
c = self._cmp(other)
if c is NotImplemented:
return c
return c > 0
def __ge__(self, other):
c = self._cmp(other)
if c is NotImplemented:
return c
return c >= 0
# Interface for version-number classes -- must be implemented
# by the following classes (the concrete ones -- Version should
# be treated as an abstract class).
# __init__ (string) - create and take same action as 'parse'
# (string parameter is optional)
# parse (string) - convert a string representation to whatever
# internal representation is appropriate for
# this style of version numbering
# __str__ (self) - convert back to a string; should be very similar
# (if not identical to) the string supplied to parse
# __repr__ (self) - generate Python code to recreate
# the instance
# _cmp (self, other) - compare two version numbers ('other' may
# be an unparsed version string, or another
# instance of your version class)
class StrictVersion(Version):
"""Version numbering for anal retentives and software idealists.
Implements the standard interface for version number classes as
described above. A version number consists of two or three
dot-separated numeric components, with an optional "pre-release" tag
on the end. The pre-release tag consists of the letter 'a' or 'b'
followed by a number. If the numeric components of two version
numbers are equal, then one with a pre-release tag will always
be deemed earlier (lesser) than one without.
The following are valid version numbers (shown in the order that
would be obtained by sorting according to the supplied cmp function):
0.4 0.4.0 (these two are equivalent)
0.4.1
0.5a1
0.5b3
0.5
0.9.6
1.0
1.0.4a3
1.0.4b1
1.0.4
The following are examples of invalid version numbers:
1
2.7.2.2
1.3.a4
1.3pl1
1.3c4
The rationale for this version numbering system will be explained
in the distutils documentation.
"""
version_re = re.compile(r'^(\d+) \. (\d+) (\. (\d+))? ([ab](\d+))?$',
RE_FLAGS)
def parse(self, vstring):
match = self.version_re.match(vstring)
if not match:
raise ValueError("invalid version number '%s'" % vstring)
(major, minor, patch, prerelease, prerelease_num) = \
match.group(1, 2, 4, 5, 6)
if patch:
self.version = tuple(map(int, [major, minor, patch]))
else:
self.version = tuple(map(int, [major, minor])) + (0,)
if prerelease:
self.prerelease = (prerelease[0], int(prerelease_num))
else:
self.prerelease = None
def __str__(self):
if self.version[2] == 0:
vstring = '.'.join(map(str, self.version[0:2]))
else:
vstring = '.'.join(map(str, self.version))
if self.prerelease:
vstring = vstring + self.prerelease[0] + str(self.prerelease[1])
return vstring
def _cmp(self, other):
if isinstance(other, str):
other = StrictVersion(other)
elif not isinstance(other, StrictVersion):
return NotImplemented
if self.version != other.version:
# numeric versions don't match
# prerelease stuff doesn't matter
if self.version < other.version:
return -1
else:
return 1
# have to compare prerelease
# case 1: neither has prerelease; they're equal
# case 2: self has prerelease, other doesn't; other is greater
# case 3: self doesn't have prerelease, other does: self is greater
# case 4: both have prerelease: must compare them!
if (not self.prerelease and not other.prerelease):
return 0
elif (self.prerelease and not other.prerelease):
return -1
elif (not self.prerelease and other.prerelease):
return 1
elif (self.prerelease and other.prerelease):
if self.prerelease == other.prerelease:
return 0
elif self.prerelease < other.prerelease:
return -1
else:
return 1
else:
raise AssertionError("never get here")
# end class StrictVersion
# The rules according to Greg Stein:
# 1) a version number has 1 or more numbers separated by a period or by
# sequences of letters. If only periods, then these are compared
# left-to-right to determine an ordering.
# 2) sequences of letters are part of the tuple for comparison and are
# compared lexicographically
# 3) recognize the numeric components may have leading zeroes
#
# The LooseVersion class below implements these rules: a version number
# string is split up into a tuple of integer and string components, and
# comparison is a simple tuple comparison. This means that version
# numbers behave in a predictable and obvious way, but a way that might
# not necessarily be how people *want* version numbers to behave. There
# wouldn't be a problem if people could stick to purely numeric version
# numbers: just split on period and compare the numbers as tuples.
# However, people insist on putting letters into their version numbers;
# the most common purpose seems to be:
# - indicating a "pre-release" version
# ('alpha', 'beta', 'a', 'b', 'pre', 'p')
# - indicating a post-release patch ('p', 'pl', 'patch')
# but of course this can't cover all version number schemes, and there's
# no way to know what a programmer means without asking him.
#
# The problem is what to do with letters (and other non-numeric
# characters) in a version number. The current implementation does the
# obvious and predictable thing: keep them as strings and compare
# lexically within a tuple comparison. This has the desired effect if
# an appended letter sequence implies something "post-release":
# eg. "0.99" < "0.99pl14" < "1.0", and "5.001" < "5.001m" < "5.002".
#
# However, if letters in a version number imply a pre-release version,
# the "obvious" thing isn't correct. Eg. you would expect that
# "1.5.1" < "1.5.2a2" < "1.5.2", but under the tuple/lexical comparison
# implemented here, this just isn't so.
#
# Two possible solutions come to mind. The first is to tie the
# comparison algorithm to a particular set of semantic rules, as has
# been done in the StrictVersion class above. This works great as long
# as everyone can go along with bondage and discipline. Hopefully a
# (large) subset of Python module programmers will agree that the
# particular flavour of bondage and discipline provided by StrictVersion
# provides enough benefit to be worth using, and will submit their
# version numbering scheme to its domination. The free-thinking
# anarchists in the lot will never give in, though, and something needs
# to be done to accommodate them.
#
# Perhaps a "moderately strict" version class could be implemented that
# lets almost anything slide (syntactically), and makes some heuristic
# assumptions about non-digits in version number strings. This could
# sink into special-case-hell, though; if I was as talented and
# idiosyncratic as Larry Wall, I'd go ahead and implement a class that
# somehow knows that "1.2.1" < "1.2.2a2" < "1.2.2" < "1.2.2pl3", and is
# just as happy dealing with things like "2g6" and "1.13++". I don't
# think I'm smart enough to do it right though.
#
# In any case, I've coded the test suite for this module (see
# ../test/test_version.py) specifically to fail on things like comparing
# "1.2a2" and "1.2". That's not because the *code* is doing anything
# wrong, it's because the simple, obvious design doesn't match my
# complicated, hairy expectations for real-world version numbers. It
# would be a snap to fix the test suite to say, "Yep, LooseVersion does
# the Right Thing" (ie. the code matches the conception). But I'd rather
# have a conception that matches common notions about version numbers.
class LooseVersion(Version):
"""Version numbering for anarchists and software realists.
Implements the standard interface for version number classes as
described above. A version number consists of a series of numbers,
separated by either periods or strings of letters. When comparing
version numbers, the numeric components will be compared
numerically, and the alphabetic components lexically. The following
are all valid version numbers, in no particular order:
1.5.1
1.5.2b2
161
3.10a
8.02
3.4j
1996.07.12
3.2.pl0
3.1.1.6
2g6
11g
0.960923
2.2beta29
1.13++
5.5.kw
2.0b1pl0
In fact, there is no such thing as an invalid version number under
this scheme; the rules for comparison are simple and predictable,
but may not always give the results you want (for some definition
of "want").
"""
component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE)
def __init__(self, vstring=None):
if vstring:
self.parse(vstring)
def parse(self, vstring):
# I've given up on thinking I can reconstruct the version string
# from the parsed tuple -- so I just store the string here for
# use by __str__
self.vstring = vstring
components = [x for x in self.component_re.split(vstring) if x and x != '.']
for i, obj in enumerate(components):
try:
components[i] = int(obj)
except ValueError:
pass
self.version = components
def __str__(self):
return self.vstring
def __repr__(self):
return "LooseVersion ('%s')" % str(self)
def _cmp(self, other):
if isinstance(other, str):
other = LooseVersion(other)
elif not isinstance(other, LooseVersion):
return NotImplemented
if self.version == other.version:
return 0
if self.version < other.version:
return -1
if self.version > other.version:
return 1
# end class LooseVersion

Some files were not shown because too many files have changed in this diff Show More