collection 교체

This commit is contained in:
정훈 변
2024-02-23 16:37:40 +09:00
parent b494779b5b
commit 3fd554eee9
38862 changed files with 220204 additions and 6600073 deletions

View File

@@ -1,7 +1,8 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2020 Orion Poplawski <orion@nwra.com>
# Copyright (c) 2020 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
@@ -12,13 +13,15 @@ DOCUMENTATION = '''
version_added: 1.0.0
description:
- Get inventory hosts from the cobbler service.
- "Uses a configuration file as an inventory source, it must end in C(.cobbler.yml) or C(.cobbler.yaml) and has a C(plugin: cobbler) entry."
- "Uses a configuration file as an inventory source, it must end in C(.cobbler.yml) or C(.cobbler.yaml) and have a C(plugin: cobbler) entry."
- Adds the primary IP addresses to C(cobbler_ipv4_address) and C(cobbler_ipv6_address) host variables if defined in Cobbler. The primary IP address is
defined as the management interface if defined, or the interface who's DNS name matches the hostname of the system, or else the first interface found.
extends_documentation_fragment:
- inventory_cache
options:
plugin:
description: The name of this plugin, it should always be set to C(community.general.cobbler) for this plugin to recognize it as it's own.
required: yes
description: The name of this plugin, it should always be set to V(community.general.cobbler) for this plugin to recognize it as it's own.
required: true
choices: [ 'cobbler', 'community.general.cobbler' ]
url:
description: URL to cobbler.
@@ -27,49 +30,77 @@ DOCUMENTATION = '''
- name: COBBLER_SERVER
user:
description: Cobbler authentication user.
required: no
required: false
env:
- name: COBBLER_USER
password:
description: Cobbler authentication password
required: no
description: Cobbler authentication password.
required: false
env:
- name: COBBLER_PASSWORD
cache_fallback:
description: Fallback to cached results if connection to cobbler fails
description: Fallback to cached results if connection to cobbler fails.
type: boolean
default: no
exclude_profiles:
description:
- Profiles to exclude from inventory.
- Ignored if I(include_profiles) is specified.
default: false
exclude_mgmt_classes:
description: Management classes to exclude from inventory.
type: list
default: []
elements: str
version_added: 7.4.0
exclude_profiles:
description:
- Profiles to exclude from inventory.
- Ignored if O(include_profiles) is specified.
type: list
default: []
elements: str
include_mgmt_classes:
description: Management classes to include from inventory.
type: list
default: []
elements: str
version_added: 7.4.0
include_profiles:
description:
- Profiles to include from inventory.
- If specified, all other profiles will be excluded.
- I(exclude_profiles) is ignored if I(include_profiles) is specified.
- O(exclude_profiles) is ignored if O(include_profiles) is specified.
type: list
default: []
elements: str
version_added: 4.4.0
inventory_hostname:
description:
- What to use for the ansible inventory hostname.
- By default the networking hostname is used if defined, otherwise the DNS name of the management or first non-static interface.
- If set to V(system), the cobbler system name is used.
type: str
choices: [ 'hostname', 'system' ]
default: hostname
version_added: 7.1.0
group_by:
description: Keys to group hosts by
description: Keys to group hosts by.
type: list
elements: string
default: [ 'mgmt_classes', 'owners', 'status' ]
group:
description: Group to place all hosts into
description: Group to place all hosts into.
default: cobbler
group_prefix:
description: Prefix to apply to cobbler groups
description: Prefix to apply to cobbler groups.
default: cobbler_
want_facts:
description: Toggle, if C(true) the plugin will retrieve host facts from the server
description: Toggle, if V(true) the plugin will retrieve host facts from the server.
type: boolean
default: yes
default: true
want_ip_addresses:
description:
- Toggle, if V(true) the plugin will add a C(cobbler_ipv4_addresses) and C(cobbleer_ipv6_addresses) dictionary to the defined O(group) mapping
interface DNS names to IP addresses.
type: boolean
default: true
version_added: 7.1.0
'''
EXAMPLES = '''
@@ -84,8 +115,8 @@ import socket
from ansible.errors import AnsibleError
from ansible.module_utils.common.text.converters import to_text
from ansible.module_utils.six import iteritems
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, to_safe_group_name
from ansible.module_utils.six import text_type
# xmlrpc
try:
@@ -127,7 +158,7 @@ class InventoryModule(BaseInventoryPlugin, Cacheable):
self.connection = xmlrpc_client.Server(self.cobbler_url, allow_none=True)
self.token = None
if self.get_option('user') is not None:
self.token = self.connection.login(self.get_option('user'), self.get_option('password'))
self.token = self.connection.login(text_type(self.get_option('user')), text_type(self.get_option('password')))
return self.connection
def _init_cache(self):
@@ -197,9 +228,12 @@ class InventoryModule(BaseInventoryPlugin, Cacheable):
self.cache_key = self.get_cache_key(path)
self.use_cache = cache and self.get_option('cache')
self.exclude_mgmt_classes = self.get_option('exclude_mgmt_classes')
self.include_mgmt_classes = self.get_option('include_mgmt_classes')
self.exclude_profiles = self.get_option('exclude_profiles')
self.include_profiles = self.get_option('include_profiles')
self.group_by = self.get_option('group_by')
self.inventory_hostname = self.get_option('inventory_hostname')
for profile in self._get_profiles():
if profile['parent']:
@@ -213,7 +247,7 @@ class InventoryModule(BaseInventoryPlugin, Cacheable):
self.inventory.add_child(parent_group_name, group_name)
else:
self.display.vvvv('Processing profile %s without parent\n' % profile['name'])
# Create a heirarchy of profile names
# Create a hierarchy of profile names
profile_elements = profile['name'].split('-')
i = 0
while i < len(profile_elements) - 1:
@@ -235,18 +269,30 @@ class InventoryModule(BaseInventoryPlugin, Cacheable):
self.inventory.add_group(self.group)
self.display.vvvv('Added site group %s\n' % self.group)
ip_addresses = {}
ipv6_addresses = {}
for host in self._get_systems():
# Get the FQDN for the host and add it to the right groups
hostname = host['hostname'] # None
if self.inventory_hostname == 'system':
hostname = host['name'] # None
else:
hostname = host['hostname'] # None
interfaces = host['interfaces']
if self._exclude_profile(host['profile']):
self.display.vvvv('Excluding host %s in profile %s\n' % (host['name'], host['profile']))
continue
if set(host['mgmt_classes']) & set(self.include_mgmt_classes):
self.display.vvvv('Including host %s in mgmt_classes %s\n' % (host['name'], host['mgmt_classes']))
else:
if self._exclude_profile(host['profile']):
self.display.vvvv('Excluding host %s in profile %s\n' % (host['name'], host['profile']))
continue
if set(host['mgmt_classes']) & set(self.exclude_mgmt_classes):
self.display.vvvv('Excluding host %s in mgmt_classes %s\n' % (host['name'], host['mgmt_classes']))
continue
# hostname is often empty for non-static IP hosts
if hostname == '':
for (iname, ivalue) in iteritems(interfaces):
for iname, ivalue in interfaces.items():
if ivalue['management'] or not ivalue['static']:
this_dns_name = ivalue.get('dns_name', None)
if this_dns_name is not None and this_dns_name != "":
@@ -261,8 +307,11 @@ class InventoryModule(BaseInventoryPlugin, Cacheable):
self.display.vvvv('Added host %s hostname %s\n' % (host['name'], hostname))
# Add host to profile group
group_name = self._add_safe_group_name(host['profile'], child=hostname)
self.display.vvvv('Added host %s to profile group %s\n' % (hostname, group_name))
if host['profile'] != '':
group_name = self._add_safe_group_name(host['profile'], child=hostname)
self.display.vvvv('Added host %s to profile group %s\n' % (hostname, group_name))
else:
self.display.warning('Host %s has an empty profile\n' % (hostname))
# Add host to groups specified by group_by fields
for group_by in self.group_by:
@@ -279,8 +328,51 @@ class InventoryModule(BaseInventoryPlugin, Cacheable):
self.inventory.add_child(self.group, hostname)
# Add host variables
ip_address = None
ip_address_first = None
ipv6_address = None
ipv6_address_first = None
for iname, ivalue in interfaces.items():
# Set to first interface or management interface if defined or hostname matches dns_name
if ivalue['ip_address'] != "":
if ip_address_first is None:
ip_address_first = ivalue['ip_address']
if ivalue['management']:
ip_address = ivalue['ip_address']
elif ivalue['dns_name'] == hostname and ip_address is None:
ip_address = ivalue['ip_address']
if ivalue['ipv6_address'] != "":
if ipv6_address_first is None:
ipv6_address_first = ivalue['ipv6_address']
if ivalue['management']:
ipv6_address = ivalue['ipv6_address']
elif ivalue['dns_name'] == hostname and ipv6_address is None:
ipv6_address = ivalue['ipv6_address']
# Collect all interface name mappings for adding to group vars
if self.get_option('want_ip_addresses'):
if ivalue['dns_name'] != "":
if ivalue['ip_address'] != "":
ip_addresses[ivalue['dns_name']] = ivalue['ip_address']
if ivalue['ipv6_address'] != "":
ip_addresses[ivalue['dns_name']] = ivalue['ipv6_address']
# Add ip_address to host if defined, use first if no management or matched dns_name
if ip_address is None and ip_address_first is not None:
ip_address = ip_address_first
if ip_address is not None:
self.inventory.set_variable(hostname, 'cobbler_ipv4_address', ip_address)
if ipv6_address is None and ipv6_address_first is not None:
ipv6_address = ipv6_address_first
if ipv6_address is not None:
self.inventory.set_variable(hostname, 'cobbler_ipv6_address', ipv6_address)
if self.get_option('want_facts'):
try:
self.inventory.set_variable(hostname, 'cobbler', host)
except ValueError as e:
self.display.warning("Could not set host info for %s: %s" % (hostname, to_text(e)))
if self.get_option('want_ip_addresses'):
self.inventory.set_variable(self.group, 'cobbler_ipv4_addresses', ip_addresses)
self.inventory.set_variable(self.group, 'cobbler_ipv6_addresses', ipv6_addresses)

View File

@@ -1,7 +1,8 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2018, Stefan Heitmueller <stefan.heitmueller@gmx.com>
# Copyright (c) 2018 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
@@ -13,7 +14,6 @@ DOCUMENTATION = '''
- Stefan Heitmüller (@morph027) <stefan.heitmueller@gmx.com>
short_description: Ansible dynamic inventory plugin for GitLab runners.
requirements:
- python >= 2.7
- python-gitlab > 1.8.0
extends_documentation_fragment:
- constructed
@@ -54,7 +54,7 @@ DOCUMENTATION = '''
verbose_output:
description: Toggle to (not) include all available nodes metadata
type: bool
default: yes
default: true
'''
EXAMPLES = '''
@@ -65,7 +65,7 @@ host: https://gitlab.com
# Example using constructed features to create groups and set ansible_host
plugin: community.general.gitlab_runners
host: https://gitlab.com
strict: False
strict: false
keyed_groups:
# add e.g. amd64 hosts to an arch_amd64 group
- prefix: arch

View File

@@ -1,7 +1,8 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Cliff Hults <cliff.hlts@gmail.com>
# Copyright (c) 2021 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
@@ -57,7 +58,7 @@ DOCUMENTATION = '''
description:
- Allows the override of the inventory name based on different attributes.
- This allows for changing the way limits are used.
- The current default, C(address), is sometimes not unique or present. We recommend to use C(name) instead.
- The current default, V(address), is sometimes not unique or present. We recommend to use V(name) instead.
type: string
default: address
choices: ['name', 'display_name', 'address']
@@ -71,7 +72,7 @@ url: http://localhost:5665
user: ansible
password: secure
host_filter: \"linux-servers\" in host.groups
validate_certs: false
validate_certs: false # only do this when connecting to localhost!
inventory_attr: name
groups:
# simple name matching

View File

@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
@@ -11,7 +12,6 @@ DOCUMENTATION = r'''
- Luke Murphy (@decentral1se)
short_description: Ansible dynamic inventory plugin for Linode.
requirements:
- python >= 2.7
- linode_api4 >= 2.0.0
description:
- Reads inventories from the Linode API v4.
@@ -120,12 +120,8 @@ compose:
ansible_host: "ipv4 | community.general.json_query('[?public==`false`].address') | first"
'''
import os
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.module_utils.six import string_types
from ansible.errors import AnsibleError
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable
from ansible.template import Templar
try:
@@ -144,22 +140,14 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
def _build_client(self, loader):
"""Build the Linode client."""
t = Templar(loader=loader)
access_token = self.get_option('access_token')
if t.is_template(access_token):
access_token = t.template(variable=access_token, disable_lookups=False)
if access_token is None:
try:
access_token = os.environ['LINODE_ACCESS_TOKEN']
except KeyError:
pass
if self.templar.is_template(access_token):
access_token = self.templar.template(variable=access_token, disable_lookups=False)
if access_token is None:
raise AnsibleError((
'Could not retrieve Linode access token '
'from plugin configuration or environment'
'from plugin configuration sources'
))
self.client = LinodeClient(access_token)

View File

@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
# Copyright: (c) 2021, Frank Dornheim <dornheim@posteo.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Copyright (c) 2021, Frank Dornheim <dornheim@posteo.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
@@ -40,23 +41,42 @@ DOCUMENTATION = r'''
aliases: [ cert_file ]
default: $HOME/.config/lxc/client.crt
type: path
server_cert:
description:
- The server certificate file path.
type: path
version_added: 8.0.0
server_check_hostname:
description:
- This option controls if the server's hostname is checked as part of the HTTPS connection verification.
This can be useful to disable, if for example, the server certificate provided (see O(server_cert) option)
does not cover a name matching the one used to communicate with the server. Such mismatch is common as LXD
generates self-signed server certificates by default.
type: bool
default: true
version_added: 8.0.0
trust_password:
description:
- The client trusted password.
- You need to set this password on the lxd server before
running this module using the following command
C(lxc config set core.trust_password <some random password>)
See U(https://www.stgraber.org/2016/04/18/lxd-api-direct-interaction/).
- If I(trust_password) is set, this module send a request for authentication before sending any requests.
See U(https://documentation.ubuntu.com/lxd/en/latest/authentication/#adding-client-certificates-using-a-trust-password).
- If O(trust_password) is set, this module send a request for authentication before sending any requests.
type: str
state:
description: Filter the instance according to the current status.
type: str
default: none
choices: [ 'STOPPED', 'STARTING', 'RUNNING', 'none' ]
project:
description: Filter the instance according to the given project.
type: str
default: default
version_added: 6.2.0
type_filter:
description:
- Filter the instances by type C(virtual-machine), C(container) or C(both).
- Filter the instances by type V(virtual-machine), V(container) or V(both).
- The first version of the inventory only supported containers.
type: str
default: container
@@ -64,18 +84,18 @@ DOCUMENTATION = r'''
version_added: 4.2.0
prefered_instance_network_interface:
description:
- If an instance has multiple network interfaces, select which one is the prefered as pattern.
- If an instance has multiple network interfaces, select which one is the preferred as pattern.
- Combined with the first number that can be found e.g. 'eth' + 0.
- The option has been renamed from I(prefered_container_network_interface) to I(prefered_instance_network_interface) in community.general 3.8.0.
The old name still works as an alias.
- The option has been renamed from O(prefered_container_network_interface) to O(prefered_instance_network_interface)
in community.general 3.8.0. The old name still works as an alias.
type: str
default: eth
aliases:
- prefered_container_network_interface
prefered_instance_network_family:
description:
- If an instance has multiple network interfaces, which one is the prefered by family.
- Specify C(inet) for IPv4 and C(inet6) for IPv6.
- If an instance has multiple network interfaces, which one is the preferred by family.
- Specify V(inet) for IPv4 and V(inet6) for IPv6.
type: str
default: inet
choices: [ 'inet', 'inet6' ]
@@ -139,19 +159,21 @@ groupby:
vlan666:
type: vlanid
attribute: 666
projectInternals:
type: project
attribute: internals
'''
import binascii
import json
import re
import time
import os
import socket
from ansible.plugins.inventory import BaseInventoryPlugin
from ansible.module_utils.common.text.converters import to_native, to_text
from ansible.module_utils.common.dict_transformations import dict_merge
from ansible.module_utils.six import raise_from
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.module_utils.six.moves.urllib.parse import urlencode
from ansible_collections.community.general.plugins.module_utils.lxd import LXDClient, LXDClientException
try:
@@ -278,7 +300,7 @@ class InventoryModule(BaseInventoryPlugin):
urls = (url for url in url_list if self.validate_url(url))
for url in urls:
try:
socket_connection = LXDClient(url, self.client_key, self.client_cert, self.debug)
socket_connection = LXDClient(url, self.client_key, self.client_cert, self.debug, self.server_cert, self.server_check_hostname)
return socket_connection
except LXDClientException as err:
error_storage[url] = err
@@ -329,7 +351,15 @@ class InventoryModule(BaseInventoryPlugin):
# "status_code": 200,
# "type": "sync"
# }
instances = self.socket.do('GET', '/1.0/instances')
url = '/1.0/instances'
if self.project:
url = url + '?{0}'.format(urlencode(dict(project=self.project)))
instances = self.socket.do('GET', url)
if self.project:
return [m.split('/')[3].split('?')[0] for m in instances['metadata']]
return [m.split('/')[3] for m in instances['metadata']]
def _get_config(self, branch, name):
@@ -343,22 +373,24 @@ class InventoryModule(BaseInventoryPlugin):
Kwargs:
None
Source:
https://github.com/lxc/lxd/blob/master/doc/rest-api.md
https://documentation.ubuntu.com/lxd/en/latest/rest-api/
Raises:
None
Returns:
dict(config): Config of the instance"""
config = {}
if isinstance(branch, (tuple, list)):
config[name] = {branch[1]: self.socket.do('GET', '/1.0/{0}/{1}/{2}'.format(to_native(branch[0]), to_native(name), to_native(branch[1])))}
config[name] = {branch[1]: self.socket.do(
'GET', '/1.0/{0}/{1}/{2}?{3}'.format(to_native(branch[0]), to_native(name), to_native(branch[1]), urlencode(dict(project=self.project))))}
else:
config[name] = {branch: self.socket.do('GET', '/1.0/{0}/{1}'.format(to_native(branch), to_native(name)))}
config[name] = {branch: self.socket.do(
'GET', '/1.0/{0}/{1}?{2}'.format(to_native(branch), to_native(name), urlencode(dict(project=self.project))))}
return config
def get_instance_data(self, names):
"""Create Inventory of the instance
Iterate through the different branches of the instances and collect Informations.
Iterate through the different branches of the instances and collect Information.
Args:
list(names): List of instance names
@@ -380,7 +412,7 @@ class InventoryModule(BaseInventoryPlugin):
def get_network_data(self, names):
"""Create Inventory of the instance
Iterate through the different branches of the instances and collect Informations.
Iterate through the different branches of the instances and collect Information.
Args:
list(names): List of instance names
@@ -433,12 +465,12 @@ class InventoryModule(BaseInventoryPlugin):
return network_configuration
def get_prefered_instance_network_interface(self, instance_name):
"""Helper to get the prefered interface of thr instance
"""Helper to get the preferred interface of thr instance
Helper to get the prefered interface provide by neme pattern from 'prefered_instance_network_interface'.
Helper to get the preferred interface provide by neme pattern from 'prefered_instance_network_interface'.
Args:
str(containe_name): name of instance
str(instance_name): name of instance
Kwargs:
None
Raises:
@@ -463,7 +495,7 @@ class InventoryModule(BaseInventoryPlugin):
Helper to get the VLAN_ID from the instance
Args:
str(containe_name): name of instance
str(instance_name): name of instance
Kwargs:
None
Raises:
@@ -522,7 +554,7 @@ class InventoryModule(BaseInventoryPlugin):
"""Helper to save data
Helper to save the data in self.data
Detect if data is allready in branch and use dict_merge() to prevent that branch is overwritten.
Detect if data is already in branch and use dict_merge() to prevent that branch is overwritten.
Args:
str(instance_name): name of instance
@@ -545,7 +577,7 @@ class InventoryModule(BaseInventoryPlugin):
else:
path[instance_name][key] = value
except KeyError as err:
raise AnsibleParserError("Unable to store Informations: {0}".format(to_native(err)))
raise AnsibleParserError("Unable to store Information: {0}".format(to_native(err)))
def extract_information_from_instance_configs(self):
"""Process configuration information
@@ -582,6 +614,8 @@ class InventoryModule(BaseInventoryPlugin):
self._set_data_entry(instance_name, 'network_interfaces', self.extract_network_information_from_instance_config(instance_name))
self._set_data_entry(instance_name, 'preferred_interface', self.get_prefered_instance_network_interface(instance_name))
self._set_data_entry(instance_name, 'vlan_ids', self.get_instance_vlans(instance_name))
self._set_data_entry(instance_name, 'project', self._get_data_entry(
'instances/{0}/instances/metadata/project'.format(instance_name)))
def build_inventory_network(self, instance_name):
"""Add the network interfaces of the instance to the inventory
@@ -663,7 +697,7 @@ class InventoryModule(BaseInventoryPlugin):
continue
# add instance
self.inventory.add_host(instance_name)
# add network informations
# add network information
self.build_inventory_network(instance_name)
# add os
v = self._get_data_entry('inventory/{0}/os'.format(instance_name))
@@ -685,6 +719,8 @@ class InventoryModule(BaseInventoryPlugin):
# add VLAN_ID information
if self._get_data_entry('inventory/{0}/vlan_ids'.format(instance_name)):
self.inventory.set_variable(instance_name, 'ansible_lxd_vlan_ids', self._get_data_entry('inventory/{0}/vlan_ids'.format(instance_name)))
# add project
self.inventory.set_variable(instance_name, 'ansible_lxd_project', self._get_data_entry('inventory/{0}/project'.format(instance_name)))
def build_inventory_groups_location(self, group_name):
"""create group by attribute: location
@@ -760,6 +796,28 @@ class InventoryModule(BaseInventoryPlugin):
# Ignore invalid IP addresses returned by lxd
pass
def build_inventory_groups_project(self, group_name):
"""create group by attribute: project
Args:
str(group_name): Group name
Kwargs:
None
Raises:
None
Returns:
None"""
# maybe we just want to expand one group
if group_name not in self.inventory.groups:
self.inventory.add_group(group_name)
gen_instances = [
instance_name for instance_name in self.inventory.hosts
if 'ansible_lxd_project' in self.inventory.get_host(instance_name).get_vars()]
for instance_name in gen_instances:
if self.groupby[group_name].get('attribute').lower() == self.inventory.get_host(instance_name).get_vars().get('ansible_lxd_project'):
self.inventory.add_child(group_name, instance_name)
def build_inventory_groups_os(self, group_name):
"""create group by attribute: os
@@ -898,6 +956,7 @@ class InventoryModule(BaseInventoryPlugin):
* 'profile'
* 'vlanid'
* 'type'
* 'project'
Args:
str(group_name): Group name
@@ -925,6 +984,8 @@ class InventoryModule(BaseInventoryPlugin):
self.build_inventory_groups_vlanid(group_name)
elif self.groupby[group_name].get('type') == 'type':
self.build_inventory_groups_type(group_name)
elif self.groupby[group_name].get('type') == 'project':
self.build_inventory_groups_project(group_name)
else:
raise AnsibleParserError('Unknown group type: {0}'.format(to_native(group_name)))
@@ -1031,6 +1092,9 @@ class InventoryModule(BaseInventoryPlugin):
try:
self.client_key = self.get_option('client_key')
self.client_cert = self.get_option('client_cert')
self.server_cert = self.get_option('server_cert')
self.server_check_hostname = self.get_option('server_check_hostname')
self.project = self.get_option('project')
self.debug = self.DEBUG
self.data = {} # store for inventory-data
self.groupby = self.get_option('groupby')

View File

@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
@@ -19,32 +20,76 @@ DOCUMENTATION = '''
options:
plugin:
description: token that ensures this is a source file for the 'nmap' plugin.
required: True
required: true
choices: ['nmap', 'community.general.nmap']
sudo:
description: Set to C(true) to execute a C(sudo nmap) plugin scan.
description: Set to V(true) to execute a C(sudo nmap) plugin scan.
version_added: 4.8.0
default: false
type: boolean
address:
description: Network IP or range of IPs to scan, you can use a simple range (10.2.2.15-25) or CIDR notation.
required: True
required: true
env:
- name: ANSIBLE_NMAP_ADDRESS
version_added: 6.6.0
exclude:
description: list of addresses to exclude
description:
- List of addresses to exclude.
- For example V(10.2.2.15-25) or V(10.2.2.15,10.2.2.16).
type: list
elements: string
env:
- name: ANSIBLE_NMAP_EXCLUDE
version_added: 6.6.0
port:
description:
- Only scan specific port or port range (C(-p)).
- For example, you could pass V(22) for a single port, V(1-65535) for a range of ports,
or V(U:53,137,T:21-25,139,8080,S:9) to check port 53 with UDP, ports 21-25 with TCP, port 9 with SCTP, and ports 137, 139, and 8080 with all.
type: string
version_added: 6.5.0
ports:
description: Enable/disable scanning for open ports
description: Enable/disable scanning ports.
type: boolean
default: True
default: true
ipv4:
description: use IPv4 type addresses
type: boolean
default: True
default: true
ipv6:
description: use IPv6 type addresses
type: boolean
default: True
default: true
udp_scan:
description:
- Scan via UDP.
- Depending on your system you might need O(sudo=true) for this to work.
type: boolean
default: false
version_added: 6.1.0
icmp_timestamp:
description:
- Scan via ICMP Timestamp (C(-PP)).
- Depending on your system you might need O(sudo=true) for this to work.
type: boolean
default: false
version_added: 6.1.0
open:
description: Only scan for open (or possibly open) ports.
type: boolean
default: false
version_added: 6.5.0
dns_resolve:
description: Whether to always (V(true)) or never (V(false)) do DNS resolution.
type: boolean
default: false
version_added: 6.1.0
use_arp_ping:
description: Whether to always (V(true)) use the quick ARP ping or (V(false)) a slower but more reliable method.
type: boolean
default: true
version_added: 7.4.0
notes:
- At least one of ipv4 or ipv6 is required to be True, both can be True, but they cannot both be False.
- 'TODO: add OS fingerprinting'
@@ -52,15 +97,23 @@ DOCUMENTATION = '''
EXAMPLES = '''
# inventory.config file in YAML format
plugin: community.general.nmap
strict: False
strict: false
address: 192.168.0.0/24
# a sudo nmap scan to fully use nmap scan power.
plugin: community.general.nmap
sudo: true
strict: False
strict: false
address: 192.168.0.0/24
# an nmap scan specifying ports and classifying results to an inventory group
plugin: community.general.nmap
address: 192.168.0.0/24
exclude: 192.168.0.1, web.example.com
port: 22, 443
groups:
web_servers: "ports | selectattr('port', 'equalto', '443')"
'''
import os
@@ -148,24 +201,43 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
# setup command
cmd = [self._nmap]
if self._options['sudo']:
if self.get_option('sudo'):
cmd.insert(0, 'sudo')
if not self._options['ports']:
if self.get_option('port'):
cmd.append('-p')
cmd.append(self.get_option('port'))
if not self.get_option('ports'):
cmd.append('-sP')
if self._options['ipv4'] and not self._options['ipv6']:
if self.get_option('ipv4') and not self.get_option('ipv6'):
cmd.append('-4')
elif self._options['ipv6'] and not self._options['ipv4']:
elif self.get_option('ipv6') and not self.get_option('ipv4'):
cmd.append('-6')
elif not self._options['ipv6'] and not self._options['ipv4']:
elif not self.get_option('ipv6') and not self.get_option('ipv4'):
raise AnsibleParserError('One of ipv4 or ipv6 must be enabled for this plugin')
if self._options['exclude']:
if self.get_option('exclude'):
cmd.append('--exclude')
cmd.append(','.join(self._options['exclude']))
cmd.append(','.join(self.get_option('exclude')))
cmd.append(self._options['address'])
if self.get_option('dns_resolve'):
cmd.append('-n')
if self.get_option('udp_scan'):
cmd.append('-sU')
if self.get_option('icmp_timestamp'):
cmd.append('-PP')
if self.get_option('open'):
cmd.append('--open')
if not self.get_option('use_arp_ping'):
cmd.append('--disable-arp-ping')
cmd.append(self.get_option('address'))
try:
# execute
p = Popen(cmd, stdout=PIPE, stderr=PIPE)

View File

@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
@@ -15,10 +16,10 @@ DOCUMENTATION = r'''
options:
plugin:
description: token that ensures this is a source file for the 'online' plugin.
required: True
required: true
choices: ['online', 'community.general.online']
oauth_token:
required: True
required: true
description: Online OAuth token.
env:
# in order of precedence
@@ -64,7 +65,7 @@ from sys import version as python_version
from ansible.errors import AnsibleError
from ansible.module_utils.urls import open_url
from ansible.plugins.inventory import BaseInventoryPlugin
from ansible.module_utils.common.text.converters import to_native, to_text
from ansible.module_utils.common.text.converters import to_text
from ansible.module_utils.ansible_release import __version__ as ansible_version
from ansible.module_utils.six.moves.urllib.parse import urljoin

View File

@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2020, FELDSAM s.r.o. - FeldHost™ <support@feldhost.cz>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
@@ -16,9 +17,9 @@ DOCUMENTATION = r'''
- constructed
description:
- Get inventory hosts from OpenNebula cloud.
- Uses an YAML configuration file ending with either I(opennebula.yml) or I(opennebula.yaml)
- Uses an YAML configuration file ending with either C(opennebula.yml) or C(opennebula.yaml)
to set parameter values.
- Uses I(api_authfile), C(~/.one/one_auth), or C(ONE_AUTH) pointing to a OpenNebula credentials file.
- Uses O(api_authfile), C(~/.one/one_auth), or E(ONE_AUTH) pointing to a OpenNebula credentials file.
options:
plugin:
description: Token that ensures this is a source file for the 'opennebula' plugin.
@@ -30,37 +31,37 @@ DOCUMENTATION = r'''
- URL of the OpenNebula RPC server.
- It is recommended to use HTTPS so that the username/password are not
transferred over the network unencrypted.
- If not set then the value of the C(ONE_URL) environment variable is used.
- If not set then the value of the E(ONE_URL) environment variable is used.
env:
- name: ONE_URL
required: True
required: true
type: string
api_username:
description:
- Name of the user to login into the OpenNebula RPC server. If not set
then the value of the C(ONE_USERNAME) environment variable is used.
then the value of the E(ONE_USERNAME) environment variable is used.
env:
- name: ONE_USERNAME
type: string
api_password:
description:
- Password or a token of the user to login into OpenNebula RPC server.
- If not set, the value of the C(ONE_PASSWORD) environment variable is used.
- If not set, the value of the E(ONE_PASSWORD) environment variable is used.
env:
- name: ONE_PASSWORD
required: False
required: false
type: string
api_authfile:
description:
- If both I(api_username) or I(api_password) are not set, then it will try
- If both O(api_username) or O(api_password) are not set, then it will try
authenticate with ONE auth file. Default path is C(~/.one/one_auth).
- Set environment variable C(ONE_AUTH) to override this path.
- Set environment variable E(ONE_AUTH) to override this path.
env:
- name: ONE_AUTH
required: False
required: false
type: string
hostname:
description: Field to match the hostname. Note C(v4_first_ip) corresponds to the first IPv4 found on VM.
description: Field to match the hostname. Note V(v4_first_ip) corresponds to the first IPv4 found on VM.
type: string
default: v4_first_ip
choices:
@@ -73,7 +74,7 @@ DOCUMENTATION = r'''
group_by_labels:
description: Create host groups by vm labels
type: bool
default: True
default: true
'''
EXAMPLES = r'''

View File

@@ -1,7 +1,8 @@
# -*- 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)
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
@@ -24,15 +25,15 @@ DOCUMENTATION = '''
- inventory_cache
options:
plugin:
description: The name of this plugin, it should always be set to C(community.general.proxmox) for this plugin to recognize it as it's own.
required: yes
description: The name of this plugin, it should always be set to V(community.general.proxmox) for this plugin to recognize it as it's own.
required: true
choices: ['community.general.proxmox']
type: str
url:
description:
- URL to Proxmox cluster.
- If the value is not specified in the inventory configuration, the value of environment variable C(PROXMOX_URL) will be used instead.
- Since community.general 4.7.0 you can also use templating to specify the value of the I(url).
- If the value is not specified in the inventory configuration, the value of environment variable E(PROXMOX_URL) will be used instead.
- Since community.general 4.7.0 you can also use templating to specify the value of the O(url).
default: 'http://localhost:8006'
type: str
env:
@@ -41,9 +42,9 @@ DOCUMENTATION = '''
user:
description:
- Proxmox authentication user.
- If the value is not specified in the inventory configuration, the value of environment variable C(PROXMOX_USER) will be used instead.
- Since community.general 4.7.0 you can also use templating to specify the value of the I(user).
required: yes
- If the value is not specified in the inventory configuration, the value of environment variable E(PROXMOX_USER) will be used instead.
- Since community.general 4.7.0 you can also use templating to specify the value of the O(user).
required: true
type: str
env:
- name: PROXMOX_USER
@@ -51,9 +52,9 @@ DOCUMENTATION = '''
password:
description:
- Proxmox authentication password.
- If the value is not specified in the inventory configuration, the value of environment variable C(PROXMOX_PASSWORD) will be used instead.
- Since community.general 4.7.0 you can also use templating to specify the value of the I(password).
- If you do not specify a password, you must set I(token_id) and I(token_secret) instead.
- If the value is not specified in the inventory configuration, the value of environment variable E(PROXMOX_PASSWORD) will be used instead.
- Since community.general 4.7.0 you can also use templating to specify the value of the O(password).
- If you do not specify a password, you must set O(token_id) and O(token_secret) instead.
type: str
env:
- name: PROXMOX_PASSWORD
@@ -61,8 +62,8 @@ DOCUMENTATION = '''
token_id:
description:
- Proxmox authentication token ID.
- If the value is not specified in the inventory configuration, the value of environment variable C(PROXMOX_TOKEN_ID) will be used instead.
- To use token authentication, you must also specify I(token_secret). If you do not specify I(token_id) and I(token_secret),
- If the value is not specified in the inventory configuration, the value of environment variable E(PROXMOX_TOKEN_ID) will be used instead.
- To use token authentication, you must also specify O(token_secret). If you do not specify O(token_id) and O(token_secret),
you must set a password instead.
- Make sure to grant explicit pve permissions to the token or disable 'privilege separation' to use the users' privileges instead.
version_added: 4.8.0
@@ -72,8 +73,8 @@ DOCUMENTATION = '''
token_secret:
description:
- Proxmox authentication token secret.
- If the value is not specified in the inventory configuration, the value of environment variable C(PROXMOX_TOKEN_SECRET) will be used instead.
- To use token authentication, you must also specify I(token_id). If you do not specify I(token_id) and I(token_secret),
- If the value is not specified in the inventory configuration, the value of environment variable E(PROXMOX_TOKEN_SECRET) will be used instead.
- To use token authentication, you must also specify O(token_id). If you do not specify O(token_id) and O(token_secret),
you must set a password instead.
version_added: 4.8.0
type: str
@@ -82,7 +83,7 @@ DOCUMENTATION = '''
validate_certs:
description: Verify SSL certificate if using HTTPS.
type: boolean
default: yes
default: true
group_prefix:
description: Prefix to apply to Proxmox groups.
default: proxmox_
@@ -92,18 +93,34 @@ DOCUMENTATION = '''
default: proxmox_
type: str
want_facts:
description: Gather LXC/QEMU configuration facts.
default: no
description:
- Gather LXC/QEMU configuration facts.
- When O(want_facts) is set to V(true) more details about QEMU VM status are possible, besides the running and stopped states.
Currently if the VM is running and it is suspended, the status will be running and the machine will be in C(running) group,
but its actual state will be paused. See O(qemu_extended_statuses) for how to retrieve the real status.
default: false
type: bool
qemu_extended_statuses:
description:
- Requires O(want_facts) to be set to V(true) to function. This will allow you to differentiate between C(paused) and C(prelaunch)
statuses of the QEMU VMs.
- This introduces multiple groups [prefixed with O(group_prefix)] C(prelaunch) and C(paused).
default: false
type: bool
version_added: 5.1.0
want_proxmox_nodes_ansible_host:
version_added: 3.0.0
description:
- Whether to set C(ansbile_host) for proxmox nodes.
- When set to C(true) (default), will use the first available interface. This can be different from what you expect.
- This currently defaults to C(true), but the default is deprecated since community.general 4.8.0.
The default will change to C(false) in community.general 6.0.0. To avoid a deprecation warning, please
set this parameter explicitly.
- Whether to set C(ansible_host) for proxmox nodes.
- When set to V(true) (default), will use the first available interface. This can be different from what you expect.
- The default of this option changed from V(true) to V(false) in community.general 6.0.0.
type: bool
default: false
exclude_nodes:
description: Exclude proxmox nodes and the nodes-group from the inventory output.
type: bool
default: false
version_added: 8.1.0
filters:
version_added: 4.6.0
description: A list of Jinja templates that allow filtering hosts.
@@ -154,7 +171,6 @@ plugin: community.general.proxmox
url: http://pve.domain.com:8006
user: ansible@pve
password: secure
validate_certs: false
want_facts: true
keyed_groups:
# proxmox_tags_parsed is an example of a fact only returned when 'want_facts=true'
@@ -175,10 +191,10 @@ want_proxmox_nodes_ansible_host: true
# Note: my_inv_var demonstrates how to add a string variable to every host used by the inventory.
# my.proxmox.yml
plugin: community.general.proxmox
url: http://pve.domain.com:8006
url: http://192.168.1.2:8006
user: ansible@pve
password: secure
validate_certs: false
validate_certs: false # only do this when you trust the network!
want_facts: true
want_proxmox_nodes_ansible_host: false
compose:
@@ -210,7 +226,6 @@ from ansible.module_utils.common.text.converters import to_native
from ansible.module_utils.six import string_types
from ansible.module_utils.six.moves.urllib.parse import urlencode
from ansible.utils.display import Display
from ansible.template import Templar
from ansible_collections.community.general.plugins.module_utils.version import LooseVersion
@@ -266,6 +281,11 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
credentials = urlencode({'username': self.proxmox_user, 'password': self.proxmox_password, })
a = self._get_session()
if a.verify is False:
from requests.packages.urllib3 import disable_warnings
disable_warnings()
ret = a.post('%s/api2/json/access/ticket' % self.proxmox_url, data=credentials)
json = ret.json()
@@ -397,15 +417,23 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
stripped_value = value.strip()
if stripped_value:
parsed_key = key + "_parsed"
properties[parsed_key] = [tag.strip() for tag in stripped_value.split(",")]
properties[parsed_key] = [tag.strip() for tag in stripped_value.replace(',', ';').split(";")]
# The first field in the agent string tells you whether the agent is enabled
# the rest of the comma separated string is extra config for the agent
if config == 'agent' and int(value.split(',')[0]):
agent_iface_value = self._get_agent_network_interfaces(node, vmid, vmtype)
if agent_iface_value:
agent_iface_key = self.to_safe('%s%s' % (key, "_interfaces"))
properties[agent_iface_key] = agent_iface_value
# the rest of the comma separated string is extra config for the agent.
# In some (newer versions of proxmox) instances it can be 'enabled=1'.
if config == 'agent':
agent_enabled = 0
try:
agent_enabled = int(value.split(',')[0])
except ValueError:
if value.split(',')[0] == "enabled=1":
agent_enabled = 1
if agent_enabled:
agent_iface_value = self._get_agent_network_interfaces(node, vmid, vmtype)
if agent_iface_value:
agent_iface_key = self.to_safe('%s%s' % (key, "_interfaces"))
properties[agent_iface_key] = agent_iface_value
if config == 'lxc':
out_val = {}
@@ -431,6 +459,8 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
def _get_vm_status(self, properties, node, vmid, vmtype, name):
ret = self._get_json("%s/api2/json/nodes/%s/%s/%s/status/current" % (self.proxmox_url, node, vmtype, vmid))
properties[self._fact('status')] = ret['status']
if vmtype == 'qemu':
properties[self._fact('qmpstatus')] = ret['qmpstatus']
def _get_vm_snapshots(self, properties, node, vmid, vmtype, name):
ret = self._get_json("%s/api2/json/nodes/%s/%s/%s/snapshot" % (self.proxmox_url, node, vmtype, vmid))
@@ -489,7 +519,8 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
name, vmid = item['name'], item['vmid']
# get status, config and snapshots if want_facts == True
if self.get_option('want_facts'):
want_facts = self.get_option('want_facts')
if want_facts:
self._get_vm_status(properties, node, vmid, ittype, name)
self._get_vm_config(properties, node, vmid, ittype, name)
self._get_vm_snapshots(properties, node, vmid, ittype, name)
@@ -503,10 +534,13 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
node_type_group = self._group('%s_%s' % (node, ittype))
self.inventory.add_child(self._group('all_' + ittype), name)
self.inventory.add_child(node_type_group, name)
if item['status'] == 'stopped':
self.inventory.add_child(self._group('all_stopped'), name)
elif item['status'] == 'running':
self.inventory.add_child(self._group('all_running'), name)
item_status = item['status']
if item_status == 'running':
if want_facts and ittype == 'qemu' and self.get_option('qemu_extended_statuses'):
# get more details about the status of the qemu VM
item_status = properties.get(self._fact('qmpstatus'), item_status)
self.inventory.add_child(self._group('all_%s' % (item_status, )), name)
return name
@@ -528,22 +562,18 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
def _populate(self):
# create common groups
self.inventory.add_group(self._group('all_lxc'))
self.inventory.add_group(self._group('all_qemu'))
self.inventory.add_group(self._group('all_running'))
self.inventory.add_group(self._group('all_stopped'))
default_groups = ['lxc', 'qemu', 'running', 'stopped']
if self.get_option('qemu_extended_statuses'):
default_groups.extend(['prelaunch', 'paused'])
for group in default_groups:
self.inventory.add_group(self._group('all_%s' % (group)))
nodes_group = self._group('nodes')
self.inventory.add_group(nodes_group)
if not self.exclude_nodes:
self.inventory.add_group(nodes_group)
want_proxmox_nodes_ansible_host = self.get_option("want_proxmox_nodes_ansible_host")
if want_proxmox_nodes_ansible_host is None:
display.deprecated(
'The want_proxmox_nodes_ansible_host option of the community.general.proxmox inventory plugin'
' currently defaults to `true`, but this default has been deprecated and will change to `false`'
' in community.general 6.0.0. To keep the current behavior and remove this deprecation warning,'
' explicitly set `want_proxmox_nodes_ansible_host` to `true` in your inventory configuration',
version='6.0.0', collection_name='community.general')
want_proxmox_nodes_ansible_host = True
# gather vm's on nodes
self._get_auth()
@@ -551,19 +581,24 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
for node in self._get_nodes():
if not node.get('node'):
continue
self.inventory.add_host(node['node'])
if node['type'] == 'node':
if not self.exclude_nodes:
self.inventory.add_host(node['node'])
if node['type'] == 'node' and not self.exclude_nodes:
self.inventory.add_child(nodes_group, node['node'])
if node['status'] == 'offline':
continue
# get node IP address
if want_proxmox_nodes_ansible_host:
if want_proxmox_nodes_ansible_host and not self.exclude_nodes:
ip = self._get_node_ip(node['node'])
self.inventory.set_variable(node['node'], 'ansible_host', ip)
# Setting composite variables
if not self.exclude_nodes:
variables = self.inventory.get_host(node['node']).get_vars()
self._set_composite_vars(self.get_option('compose'), variables, node['node'], strict=self.strict)
# add LXC/Qemu groups for the node
for ittype in ('lxc', 'qemu'):
node_type_group = self._group('%s_%s' % (node['node'], ittype))
@@ -590,37 +625,23 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
# read config from file, this sets 'options'
self._read_config_data(path)
t = Templar(loader=loader)
# read and template auth options
for o in ('url', 'user', 'password', 'token_id', 'token_secret'):
v = self.get_option(o)
if self.templar.is_template(v):
v = self.templar.template(v, disable_lookups=False)
setattr(self, 'proxmox_%s' % o, v)
# read options
proxmox_url = self.get_option('url')
if t.is_template(proxmox_url):
proxmox_url = t.template(variable=proxmox_url, disable_lookups=False)
self.proxmox_url = proxmox_url.rstrip('/')
# some more cleanup and validation
self.proxmox_url = self.proxmox_url.rstrip('/')
proxmox_user = self.get_option('user')
if t.is_template(proxmox_user):
proxmox_user = t.template(variable=proxmox_user, disable_lookups=False)
self.proxmox_user = proxmox_user
proxmox_password = self.get_option('password')
if t.is_template(proxmox_password):
proxmox_password = t.template(variable=proxmox_password, disable_lookups=False)
self.proxmox_password = proxmox_password
proxmox_token_id = self.get_option('token_id')
if t.is_template(proxmox_token_id):
proxmox_token_id = t.template(variable=proxmox_token_id, disable_lookups=False)
self.proxmox_token_id = proxmox_token_id
proxmox_token_secret = self.get_option('token_secret')
if t.is_template(proxmox_token_secret):
proxmox_token_secret = t.template(variable=proxmox_token_secret, disable_lookups=False)
self.proxmox_token_secret = proxmox_token_secret
if proxmox_password is None and (proxmox_token_id is None or proxmox_token_secret is None):
if self.proxmox_password is None and (self.proxmox_token_id is None or self.proxmox_token_secret is None):
raise AnsibleError('You must specify either a password or both token_id and token_secret.')
if self.get_option('qemu_extended_statuses') and not self.get_option('want_facts'):
raise AnsibleError('You must set want_facts to True if you want to use qemu_extended_statuses.')
# read rest of options
self.exclude_nodes = self.get_option('exclude_nodes')
self.cache_key = self.get_cache_key(path)
self.use_cache = cache and self.get_option('cache')
self.host_filters = self.get_option('filters')

View File

@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
# Copyright: (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
@@ -18,7 +19,7 @@ DOCUMENTATION = r'''
options:
plugin:
description: Token that ensures this is a source file for the 'scaleway' plugin.
required: True
required: true
choices: ['scaleway', 'community.general.scaleway']
regions:
description: Filter results on a specific Scaleway region.
@@ -36,7 +37,7 @@ DOCUMENTATION = r'''
scw_profile:
description:
- The config profile to use in config file.
- By default uses the one specified as C(active_profile) in the config file, or falls back to C(default) if that is not defined.
- By default uses the one specified as C(active_profile) in the config file, or falls back to V(default) if that is not defined.
type: string
version_added: 4.4.0
oauth_token:

View File

@@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Shay Rybak <shay.rybak@stackpath.com>
# Copyright (c) 2020 Ansible Project
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

View File

@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
@@ -19,12 +20,12 @@ DOCUMENTATION = '''
options:
plugin:
description: token that ensures this is a source file for the 'virtualbox' plugin
required: True
required: true
choices: ['virtualbox', 'community.general.virtualbox']
running_only:
description: toggles showing all vms vs only those currently running
type: boolean
default: False
default: false
settings_password_file:
description: provide a file containing the settings password (equivalent to --settingspwfile)
network_info_path:
@@ -185,10 +186,13 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
else:
# found vars, accumulate in hostvars for clean inventory set
pref_k = 'vbox_' + k.strip().replace(' ', '_')
if k.startswith(' '):
if prevkey not in hostvars[current_host]:
leading_spaces = len(k) - len(k.lstrip(' '))
if 0 < leading_spaces <= 2:
if prevkey not in hostvars[current_host] or not isinstance(hostvars[current_host][prevkey], dict):
hostvars[current_host][prevkey] = {}
hostvars[current_host][prevkey][pref_k] = v
elif leading_spaces > 2:
continue
else:
if v != '':
hostvars[current_host][pref_k] = v

View File

@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
@@ -22,30 +23,30 @@ DOCUMENTATION = '''
- inventory_cache
options:
plugin:
description: The name of this plugin, it should always be set to C(community.general.xen_orchestra) for this plugin to recognize it as its own.
required: yes
description: The name of this plugin, it should always be set to V(community.general.xen_orchestra) for this plugin to recognize it as its own.
required: true
choices: ['community.general.xen_orchestra']
type: str
api_host:
description:
- API host to XOA API.
- If the value is not specified in the inventory configuration, the value of environment variable C(ANSIBLE_XO_HOST) will be used instead.
- If the value is not specified in the inventory configuration, the value of environment variable E(ANSIBLE_XO_HOST) will be used instead.
type: str
env:
- name: ANSIBLE_XO_HOST
user:
description:
- Xen Orchestra user.
- If the value is not specified in the inventory configuration, the value of environment variable C(ANSIBLE_XO_USER) will be used instead.
required: yes
- If the value is not specified in the inventory configuration, the value of environment variable E(ANSIBLE_XO_USER) will be used instead.
required: true
type: str
env:
- name: ANSIBLE_XO_USER
password:
description:
- Xen Orchestra password.
- If the value is not specified in the inventory configuration, the value of environment variable C(ANSIBLE_XO_PASSWORD) will be used instead.
required: yes
- If the value is not specified in the inventory configuration, the value of environment variable E(ANSIBLE_XO_PASSWORD) will be used instead.
required: true
type: str
env:
- name: ANSIBLE_XO_PASSWORD
@@ -77,6 +78,7 @@ compose:
import json
import ssl
from time import sleep
from ansible.errors import AnsibleError
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable
@@ -137,21 +139,42 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
self.conn = create_connection(
'{0}://{1}/api/'.format(proto, xoa_api_host), sslopt=sslopt)
CALL_TIMEOUT = 100
"""Number of 1/10ths of a second to wait before method call times out."""
def call(self, method, params):
"""Calls a method on the XO server with the provided parameters."""
id = self.pointer
self.conn.send(json.dumps({
'id': id,
'jsonrpc': '2.0',
'method': method,
'params': params
}))
waited = 0
while waited < self.CALL_TIMEOUT:
response = json.loads(self.conn.recv())
if 'id' in response and response['id'] == id:
return response
else:
sleep(0.1)
waited += 1
raise AnsibleError(
'Method call {method} timed out after {timeout} seconds.'.format(method=method, timeout=self.CALL_TIMEOUT / 10))
def login(self, user, password):
payload = {'id': self.pointer, 'jsonrpc': '2.0', 'method': 'session.signIn', 'params': {
'username': user, 'password': password}}
self.conn.send(json.dumps(payload))
result = json.loads(self.conn.recv())
result = self.call('session.signIn', {
'username': user, 'password': password
})
if 'error' in result:
raise AnsibleError(
'Could not connect: {0}'.format(result['error']))
def get_object(self, name):
payload = {'id': self.pointer, 'jsonrpc': '2.0',
'method': 'xo.getAllObjects', 'params': {'filter': {'type': name}}}
self.conn.send(json.dumps(payload))
answer = json.loads(self.conn.recv())
answer = self.call('xo.getAllObjects', {'filter': {'type': name}})
if 'error' in answer:
raise AnsibleError(