Compare commits

...
31 Commits
Author SHA1 Message Date
Michal Nasiadka 166db53fa4 Add missing changelog entries to 2.7.0
The identity_user options and loadbalancer availability zone changes
were merged just before the 2.7.0 release metadata was prepared, so
their changelog fragments were not aggregated. Fold them into the
2.7.0 release notes, since both changes ship in that release.

Change-Id: Ibde8b7a16b16934ac500299207b428d3bd8dce31
Signed-off-by: Michal Nasiadka <mnasiadka@gmail.com>
2026-11-15 10:01:48 -06:00
Doug Szumski aa949c09a6 Prepare release metadata for openstack.cloud 2.7.0
Release a new version with minor changes and bugfixes only.

Change-Id: Ia6f2c9634cd8935ba9edb7b471a2d3219ff76623
Assisted-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 13:59:46 +00:00
ZuulandGerrit Code Review 6cd74f4749 Merge "feat: add option to specify the availability zone for a newly created loadbalancer" 2026-10-28 16:54:23 +00:00
ZuulandGerrit Code Review 2d02e7ac75 Merge "identity_user: support Keystone user resource options" 2026-10-28 16:54:21 +00:00
ZuulandGerrit Code Review ac8cce11c7 Merge "image: do a web-download import when uri is given" 2026-10-26 16:25:54 +00:00
ZuulandGerrit Code Review 896027d67e Merge "Add target_provision_state option to baremetal_node" 2026-10-26 16:25:52 +00:00
Moritz Tanner 34a99f549b image: do a web-download import when uri is given
The module documents and accepts import_method and uri, but nothing ever
acts on them for a URL-based import. Its only import_image() call is
hardcoded to glance-direct, so asking Glance to fetch an image itself is
not possible.

Worse, the two options are listed in attr_params, so they are handed to
conn.create_image() as unrecognised keyword arguments and end up stored
on the image as arbitrary properties. With no filename the create call
then reaches the direct upload endpoint with no data, which Glance
rejects:

  HttpException: 415: Client Error for url:
  .../v2/images/<id>/file, Unsupported Media Type
  Image disk_format qcow2 does not match stream data raw

Import a queued image from its uri instead, defaulting the method to
web-download, and drop the three behavioural options from attr_params so
they stop becoming image properties. When creating the image, do not let
create_image() wait for it to become active, since it stays queued until
the import is started.

Remove glance-download from the import_method choices. The module never
used it. The glance-download method takes a remote region and a remote
image ID, and the module has no options for these yet.

Closes-Bug: #2167999
Change-Id: I11fa064567c36012cd51c78e4bca2c46152990d3
Signed-off-by: Moritz Tanner <moritz.tanner@linbit.com>
2026-10-22 15:12:20 +02:00
Jed Preist ee6e1e9741 Add target_provision_state option to baremetal_node
Add an option to configure the expected provision state for newly
created baremetal nodes.

Change-Id: Iafb9206b86ea366d45c6919247847f5f8d221952
Signed-off-by: Jed Preist <jed@stackhpc.com>
2026-10-22 13:35:23 +01:00
ZuulandGerrit Code Review 4caa12c979 Merge "Fix: Include target_project_id in RBAC creation" 2026-10-22 12:00:01 +00:00
ZuulandGerrit Code Review 6482009c49 Merge "Use **-operator to unpack dict in volume_type_access" 2026-10-22 11:59:59 +00:00
ZuulandGerrit Code Review 11a9430073 Merge "Handle the cloud parameter as a dict in application_credential module" 2026-10-22 11:50:11 +00:00
Jed Preist ad7205503e Fix dns zone update issues in CI
Stop CI failing due to DNS zone update timing out. Designate currently
has a bug where an update that only changes the description of a DNS
zone gets stuck in pending. Update the TTL as well to work around this.
https://bugs.launchpad.net/designate/+bug/2171489

Change-Id: I47ec220f0db00dde996962077a15b2a8b2f072ee
Signed-off-by: Jed Preist <jed@stackhpc.com>
2026-10-20 10:00:11 +01:00
Matt Crees 291d64adaa Fix: Include target_project_id in RBAC creation
This fixes an issue where we cannot create multiple Neutron RBAC
policies using the same source project and network.

Closes-Bug: #2129677
Change-Id: Ib3c63131f9ae09abd03fc7d619e3566267690216
Signed-off-by: Matt Crees <mattc@stackhpc.com>
2026-09-23 09:35:26 +01:00
Maximilian Stinsky cfb7a39221 identity_user: support Keystone user resource options
Add an `options` parameter to the identity_user module, mapping 1:1 to
Keystone's user resource `options` field exposed by openstacksdk
(`User.options`). This allows setting options such as
`ignore_password_expiry` and `ignore_change_password_upon_first_use`.

On update, desired options are merged with the user's existing options
so that options not managed by the module are preserved, and the
operation is idempotent when the desired values already match.

Change-Id: I16cff99e86f0676a5c16121e8eca2b7a13ea9d6e
Signed-off-by: Maximilian Stinsky <maximilian.stinsky-damke@wiit.cloud>
2026-09-22 10:24:31 +02:00
Jan Horstmann e433ee401b Use **-operator to unpack dict in volume_type_access
Closes-Bug: #2167592

Change-Id: I8b5fa92bb30e1b4e0a9860274e071547d65b7bc8
Signed-off-by: Jan Horstmann <horstmann@osism.tech>
2026-09-17 14:47:51 +02:00
Pierre Riteau da4a211b2d CI: Test with ansible-core 2.21
Change-Id: Iabb17e193ebe1ba3e471cb46e3f323d43cb8ef9a
Signed-off-by: Pierre Riteau <pierre@stackhpc.com>
2026-09-17 07:45:54 +02:00
ZuulandGerrit Code Review 6fccec65bc Merge "fix using undefined variable" 2026-09-15 10:51:52 +00:00
wuensche 9a437e49bc fix using undefined variable
Closes-Bug: #2162084
Change-Id: I3276aa8613165a98bd5fafa1c7830039f95ad4bb
Signed-off-by: Daniel Wuensche <wuensche@b1-systems.de>
2026-09-14 11:57:57 +02:00
Patrick Pfurtscheller 74caf969b3 feat: add option to specify the availability zone for a newly created loadbalancer
Change-Id: Iade373f6ab999684c932a5228d879a573f3250ad
Signed-off-by: Patrick Pfurtscheller <patrick@pfurtscheller.org>
2026-09-11 08:24:46 +02:00
ZuulandGerrit Code Review 19a8bc6e05 Merge "Search for the router network in specified project" 2026-09-09 16:01:25 +00:00
ZuulandGerrit Code Review 8c95d5aba8 Merge "Add support for recordset lookup by type to prevent conflicts" 2026-09-09 10:25:13 +00:00
Denys Mishchenko 876823b88e Search for the router network in specified project
If we have multiple networks with the same name in different projects,
we will get an error in a global search. So first we should search in
specified project and only if the network is missing there, do a global
search. This should allow creation of multiple projects with the routers
using the same network names.

Change-Id: I40f41a6ee3e18d7cb2fc7fdd375539066444f3fb
Signed-off-by: Denys Mishchenko <denys.mishchenko@cleura.com>
2026-09-09 12:04:40 +02:00
ZuulandGerrit Code Review 6924032c86 Merge "Fix subnet module when subnet already exists" 2026-09-08 13:15:20 +00:00
ZuulandGerrit Code Review 463dda6549 Merge "feat: add support for live_migrate action" 2026-09-03 19:22:48 +00:00
Thomas Sell ebacdde5a4 Fix subnet module when subnet already exists
Regression introduced in commit eef8368e6f

Closes-Bug: #2164658
Related-Change: I4647fd96aaa15460d82765365f98a18ddf2693db
Change-Id: I128663705e9a21bdc09904af299c58fe527d4478
Signed-off-by: Thomas Sell <thomas.sell@bih-charite.de>
2026-08-20 17:30:01 +02:00
Sondre Batalden 746e521d47 Add support for recordset lookup by type to prevent conflicts
Change-Id: I81cd7b89d4a91f48d1556fb58967209336b5c1db
2026-08-12 11:58:42 +02:00
Hollie HutchinsonandDoug Szumski ee88cc15b8 Remove MAC address requirement for node registration
Allow the creation of baremetal nodes without specifying any NICs.
In this case switch the target provision state from available to
enroll.

We're proposing this patch to support enrolling nodes as a first
step before running an out-of-band Redfish inspection to get the
NICs.

No change is made to existing workflows.

Change-Id: I9b1636d778e7477191bfbe6094bd6bc70a4d384e
Signed-off-by: Hollie Hutchinson <hollie@stackhpc.com>
Signed-off-by: Doug Szumski <doug@stackhpc.com>
2026-07-23 16:36:27 +01:00
Patrick Pfurtscheller 9d53bf6403 feat: add support for live_migrate action
Change-Id: I3c32e2c8b33d6c7c6bd9fe4ea039bce16bd1b3b3
Signed-off-by: Patrick Pfurtscheller <patrick@pfurtscheller.org>
2026-06-22 11:28:28 +02:00
ZuulandGerrit Code Review 209cf2d605 Merge "Revive collection unit tests" 2026-06-15 16:05:50 +00:00
Dmitriy Rabotyagov dc2bb8232e Revive collection unit tests
Seemingly, ansible-test unit tests were not run in CI for a while and
are broken in multiple places.

This patch aims to re-incarnate unit testing of modules
and execute them as part of the sanity tests.
We use sanity right now, as they perform testing against different
ansible versions and unit tests take multiple seconds to complete.
So spawning a separate nodes would be an overkill.

Unit tests have also detected a regression in server module, as existing
nets generation can create a generator, where `isinstance(net, dict)`
will return negative result, as it is gonna
be a generator, not a dict.
So this part has been refactored to avoid poitential regressions.

Change-Id: Ibefc087239b5c8d5e843c977c2c5a2250ae0bfbd
Signed-off-by: Dmitriy Rabotyagov <dmitriy.rabotyagov@cleura.com>
2026-06-10 17:09:00 +00:00
Vincent Lequertier 08686d1d9c Handle the cloud parameter as a dict in application_credential module
Closes-Bug: 2117712
Change-Id: I258f4f6f35ed00b1ac0d719f17e5704c1bfe22f8
2025-07-23 15:03:38 +02:00
26 changed files with 713 additions and 66 deletions
+31
View File
@@ -245,6 +245,19 @@
vars: vars:
tox_envlist: ansible_2_20 tox_envlist: ansible_2_20
- job:
name: ansible-collections-openstack-functional-devstack-ansible-2.21
parent: ansible-collections-openstack-functional-devstack-base
branches: master
description: |
Run openstack collections functional tests against a master devstack
using master of openstacksdk and stable 2.21 branch of ansible
required-projects:
- name: github.com/ansible/ansible
override-checkout: stable-2.21
vars:
tox_envlist: ansible_2_21
- job: - job:
name: ansible-collections-openstack-functional-devstack-ansible-devel name: ansible-collections-openstack-functional-devstack-ansible-devel
parent: ansible-collections-openstack-functional-devstack-base parent: ansible-collections-openstack-functional-devstack-base
@@ -324,6 +337,19 @@
python_version: "3.12" python_version: "3.12"
bindep_profile: test py312 bindep_profile: test py312
- job:
name: openstack-tox-linters-ansible-2.21
parent: openstack-tox-linters-ansible
description: |
Run openstack collections linter tests using the 2.21 branch of ansible
required-projects:
- name: github.com/ansible/ansible
override-checkout: stable-2.21
vars:
tox_envlist: linters_2_21
python_version: "3.12"
bindep_profile: test py312
# Cross-checks with other projects # Cross-checks with other projects
- job: - job:
name: bifrost-collections-src name: bifrost-collections-src
@@ -379,11 +405,13 @@
- openstack-tox-linters-ansible-2.18 - openstack-tox-linters-ansible-2.18
- openstack-tox-linters-ansible-2.19 - openstack-tox-linters-ansible-2.19
- openstack-tox-linters-ansible-2.20 - openstack-tox-linters-ansible-2.20
- openstack-tox-linters-ansible-2.21
- ansible-collections-openstack-functional-devstack - ansible-collections-openstack-functional-devstack
- ansible-collections-openstack-functional-devstack-releases - ansible-collections-openstack-functional-devstack-releases
- ansible-collections-openstack-functional-devstack-ansible-2.18 - ansible-collections-openstack-functional-devstack-ansible-2.18
- ansible-collections-openstack-functional-devstack-ansible-2.19 - ansible-collections-openstack-functional-devstack-ansible-2.19
- ansible-collections-openstack-functional-devstack-ansible-2.20 - ansible-collections-openstack-functional-devstack-ansible-2.20
- ansible-collections-openstack-functional-devstack-ansible-2.21
- ansible-collections-openstack-functional-devstack-ansible-devel - ansible-collections-openstack-functional-devstack-ansible-devel
- ansible-collections-openstack-functional-devstack-magnum - ansible-collections-openstack-functional-devstack-magnum
- ansible-collections-openstack-functional-devstack-manila - ansible-collections-openstack-functional-devstack-manila
@@ -402,6 +430,7 @@
- openstack-tox-linters-ansible-2.18 - openstack-tox-linters-ansible-2.18
- openstack-tox-linters-ansible-2.19 - openstack-tox-linters-ansible-2.19
- openstack-tox-linters-ansible-2.20 - openstack-tox-linters-ansible-2.20
- openstack-tox-linters-ansible-2.21
- ansible-collections-openstack-functional-devstack-releases - ansible-collections-openstack-functional-devstack-releases
- ansible-collections-openstack-functional-devstack-magnum - ansible-collections-openstack-functional-devstack-magnum
- ansible-collections-openstack-functional-devstack-manila - ansible-collections-openstack-functional-devstack-manila
@@ -413,11 +442,13 @@
- openstack-tox-linters-ansible-2.18 - openstack-tox-linters-ansible-2.18
- openstack-tox-linters-ansible-2.19 - openstack-tox-linters-ansible-2.19
- openstack-tox-linters-ansible-2.20 - openstack-tox-linters-ansible-2.20
- openstack-tox-linters-ansible-2.21
- ansible-collections-openstack-functional-devstack - ansible-collections-openstack-functional-devstack
- ansible-collections-openstack-functional-devstack-releases - ansible-collections-openstack-functional-devstack-releases
- ansible-collections-openstack-functional-devstack-ansible-2.18 - ansible-collections-openstack-functional-devstack-ansible-2.18
- ansible-collections-openstack-functional-devstack-ansible-2.19 - ansible-collections-openstack-functional-devstack-ansible-2.19
- ansible-collections-openstack-functional-devstack-ansible-2.20 - ansible-collections-openstack-functional-devstack-ansible-2.20
- ansible-collections-openstack-functional-devstack-ansible-2.21
- ansible-collections-openstack-functional-devstack-ansible-devel - ansible-collections-openstack-functional-devstack-ansible-devel
- bifrost-collections-src - bifrost-collections-src
- bifrost-keystone-collections-src - bifrost-keystone-collections-src
+31 -1
View File
@@ -4,6 +4,37 @@ Ansible OpenStack Collection Release Notes
.. contents:: Topics .. contents:: Topics
v2.7.0
======
Release Summary
---------------
Bugfixes and minor changes.
Minor Changes
-------------
- baremetal_node - Add ``target_provision_state`` option.
- baremetal_node - Allow registering nodes without NICs.
- identity_user - Added an ``options`` parameter to set Keystone user resource options, e.g. ``ignore_password_expiry`` and ``ignore_change_password_upon_first_use``. On update, the provided options are merged with the user's existing options so options not managed by this module are preserved.
- loadbalancer - Add option to specify the availability zone a loadbalancer should be created in.
- server_action - Add ``live_migrate`` action.
Bugfixes
--------
- application_credential - Handle ``cloud`` passed as a dict.
- image - Do a web-download import when ``uri`` is given, instead of ignoring ``uri`` and ``import_method`` and attempting a direct upload with no data.
- image - Remove the unimplemented ``glance-download`` choice for ``import_method``.
- image - Stop storing ``uri``, ``import_method`` and ``use_import`` on the image as properties.
- lb_pool - Fix use of an undefined variable.
- neutron_rbac_policy - Include ``target_project_id`` on creation.
- recordset - Look an existing recordset up by zone, name and type instead of by zone and name only. Recordsets sharing a name with recordsets of another type, e.g. an ``A`` recordset at the apex of a zone which shares its name with the ``SOA`` and ``NS`` recordsets created along with the zone, could not be created, updated or deleted because the lookup matched more than one recordset and failed with ``More than one Recordset exists with the name``.
- router - Search for the network in the router's project first.
- subnet - Fix regression when the subnet already exists.
- volume_type_access - Fix failure when ``project_domain`` is set.
v2.6.0 v2.6.0
====== ======
@@ -12,7 +43,6 @@ Release Summary
New modules for Bare Metal port groups and Neutron network segments, plus image/project enhancements and bugfixes. New modules for Bare Metal port groups and Neutron network segments, plus image/project enhancements and bugfixes.
Minor Changes Minor Changes
------------- -------------
+42
View File
@@ -665,3 +665,45 @@ releases:
name: volume_retype name: volume_retype
namespace: '' namespace: ''
release_date: '2026-06-10' release_date: '2026-06-10'
2.7.0:
changes:
bugfixes:
- application_credential - Handle ``cloud`` passed as a dict.
- image - Do a web-download import when ``uri`` is given, instead of ignoring
``uri`` and ``import_method`` and attempting a direct upload with no data.
- image - Remove the unimplemented ``glance-download`` choice for ``import_method``.
- image - Stop storing ``uri``, ``import_method`` and ``use_import`` on the
image as properties.
- lb_pool - Fix use of an undefined variable.
- neutron_rbac_policy - Include ``target_project_id`` on creation.
- recordset - Look an existing recordset up by zone, name and type instead of
by zone and name only. Recordsets sharing a name with recordsets of another
type, e.g. an ``A`` recordset at the apex of a zone which shares its name
with the ``SOA`` and ``NS`` recordsets created along with the zone, could
not be created, updated or deleted because the lookup matched more than one
recordset and failed with ``More than one Recordset exists with the name``.
- router - Search for the network in the router's project first.
- subnet - Fix regression when the subnet already exists.
- volume_type_access - Fix failure when ``project_domain`` is set.
minor_changes:
- baremetal_node - Add ``target_provision_state`` option.
- baremetal_node - Allow registering nodes without NICs.
- identity_user - Added an ``options`` parameter to set Keystone user resource
options, e.g. ``ignore_password_expiry`` and ``ignore_change_password_upon_first_use``.
On update, the provided options are merged with the user's existing options
so options not managed by this module are preserved.
- loadbalancer - Add option to specify the availability zone a loadbalancer
should be created in.
- server_action - Add ``live_migrate`` action.
release_summary: Bugfixes and minor changes.
fragments:
- add_az_parameter_to_loadbalancer.yaml
- baremetal_provision_state.yaml
- bug_2167592.yaml
- identity_user_options.yaml
- image_web_download.yaml
- rbac_target_project_id.yaml
- recordset_find_by_type.yaml
- router_network.yaml
- undefined_variable.yaml
release_date: '2026-10-26'
+4
View File
@@ -16,17 +16,21 @@
# allow new fields to be introduced but prevent fields from being removed # allow new fields to be introduced but prevent fields from being removed
- expected_fields|difference(dns_zone.zone.keys())|length == 0 - expected_fields|difference(dns_zone.zone.keys())|length == 0
# NOTE(jed-preist): Update ttl as well, to work around
# https://bugs.launchpad.net/designate/+bug/2171489
- name: Update dns zone - name: Update dns zone
openstack.cloud.dns_zone: openstack.cloud.dns_zone:
cloud: "{{ cloud }}" cloud: "{{ cloud }}"
name: ansible.test.zone. name: ansible.test.zone.
description: "Another description" description: "Another description"
ttl: 1800
register: dns_zone register: dns_zone
- name: Assert return values of dns_zone module - name: Assert return values of dns_zone module
assert: assert:
that: that:
- dns_zone.zone.description == "Another description" - dns_zone.zone.description == "Another description"
- dns_zone.zone.ttl == 1800
- name: Fetch all dns zones - name: Fetch all dns zones
openstack.cloud.dns_zone_info: openstack.cloud.dns_zone_info:
+3
View File
@@ -63,3 +63,6 @@ expected_fields:
- vm_mode - vm_mode
- vmware_adaptertype - vmware_adaptertype
- vmware_ostype - vmware_ostype
# Fetched by the Image service itself in the web-download test.
image_web_download_uri: https://download.cirros-cloud.net/0.6.2/cirros-0.6.2-x86_64-disk.img
+47
View File
@@ -368,6 +368,53 @@
name: "{{ tmp_file.path }}" name: "{{ tmp_file.path }}"
state: absent state: absent
- name: Import an image with web-download
openstack.cloud.image:
cloud: "{{ cloud }}"
state: present
name: ansible_image_web_download
container_format: bare
disk_format: qcow2
import_method: web-download
uri: "{{ image_web_download_uri }}"
register: web_download_image
- name: Assert the image was fetched by the Image service
assert:
that:
- web_download_image is changed
- web_download_image.image.status == 'active'
- web_download_image.image.size > 0
- name: Assert import options were not stored as image properties
assert:
that:
- "'uri' not in web_download_image.image.properties"
- "'import_method' not in web_download_image.image.properties"
- "'use_import' not in web_download_image.image.properties"
- name: Import the same image again
openstack.cloud.image:
cloud: "{{ cloud }}"
state: present
name: ansible_image_web_download
container_format: bare
disk_format: qcow2
import_method: web-download
uri: "{{ image_web_download_uri }}"
register: web_download_image
- name: Assert the second import did not change anything
assert:
that:
- web_download_image is not changed
- name: Delete the web-download image
openstack.cloud.image:
cloud: "{{ cloud }}"
state: absent
name: ansible_image_web_download
always: always:
- name: Remove temporary image file - name: Remove temporary image file
ansible.builtin.file: ansible.builtin.file:
+1 -1
View File
@@ -32,4 +32,4 @@ build_ignore:
- .vscode - .vscode
- ansible_collections_openstack.egg-info - ansible_collections_openstack.egg-info
- changelogs - changelogs
version: 2.6.0 version: 2.7.0
+5 -1
View File
@@ -298,7 +298,11 @@ class IdentityApplicationCredentialModule(OpenStackModule):
return creds return creds
def _get_cloud_config(self, creds): def _get_cloud_config(self, creds):
cloud_region = openstack.config.OpenStackConfig().get_one(self.cloud) if isinstance(self.cloud, str):
cloud_region = openstack.config.OpenStackConfig().get_one(self.cloud)
# If the cloud parameter is not a string, try to send it to kwargs
else:
cloud_region = openstack.config.OpenStackConfig().get_one(**self.cloud)
conf = cloud_region.config conf = cloud_region.config
cloud_config = copy.deepcopy(conf) cloud_config = copy.deepcopy(conf)
+31 -2
View File
@@ -75,7 +75,8 @@ options:
description: description:
- 'A list of network interface cards, eg, C( - mac: aa:bb:cc:aa:bb:cc)' - 'A list of network interface cards, eg, C( - mac: aa:bb:cc:aa:bb:cc)'
- This node attribute cannot be updated. - This node attribute cannot be updated.
required: true required: false
default: []
type: list type: list
elements: dict elements: dict
suboptions: suboptions:
@@ -153,6 +154,18 @@ options:
- Interface used for attaching and detaching volumes on this node, e.g. - Interface used for attaching and detaching volumes on this node, e.g.
C(cinder). C(cinder).
type: str type: str
target_provision_state:
description:
- Indicates desired provision state of the node.
- This option is ignored if the node already exists.
- If set to available, the node will go through cleaning. This may fail
if the nics option has no interfaces specified.
- try-available behaves the same as available if the nics option is
set, and falls back to enroll if it is not.
choices: ['enroll', 'manageable', 'available', 'try-available']
default: try-available
type: str
version_added: 2.7.0
timeout: timeout:
description: description:
- Number of seconds to wait for the newly created node to reach the - Number of seconds to wait for the newly created node to reach the
@@ -508,7 +521,7 @@ class BaremetalNodeModule(OpenStackModule):
management_interface=dict(), management_interface=dict(),
name=dict(), name=dict(),
network_interface=dict(), network_interface=dict(),
nics=dict(type='list', required=True, elements='dict'), nics=dict(type='list', default=[], elements='dict'),
power_interface=dict(), power_interface=dict(),
properties=dict( properties=dict(
type='dict', type='dict',
@@ -531,6 +544,10 @@ class BaremetalNodeModule(OpenStackModule):
), ),
state=dict(default='present', choices=['present', 'absent']), state=dict(default='present', choices=['present', 'absent']),
storage_interface=dict(), storage_interface=dict(),
target_provision_state=dict(
default='try-available',
choices=['enroll', 'manageable', 'available', 'try-available']
),
timeout=dict(default=1800, type='int'), # increased default value timeout=dict(default=1800, type='int'), # increased default value
vendor_interface=dict(), vendor_interface=dict(),
) )
@@ -651,10 +668,22 @@ class BaremetalNodeModule(OpenStackModule):
if properties: if properties:
kwargs['properties'] = properties kwargs['properties'] = properties
provision_state = self.params['target_provision_state']
if provision_state == 'available':
if len(self.params['nics']) == 0:
self.warn('Attempting to make node available with no NICs'
' set. Node may fail cleaning.')
elif provision_state == 'try-available':
if len(self.params['nics']) == 0:
provision_state = 'enroll'
else:
provision_state = 'available'
node = self.conn.register_machine( node = self.conn.register_machine(
nics=self.params['nics'], nics=self.params['nics'],
wait=self.params['wait'], wait=self.params['wait'],
timeout=self.params['timeout'], timeout=self.params['timeout'],
provision_state=provision_state,
**kwargs) **kwargs)
self.exit_json(changed=True, node=node.to_dict(computed=False)) self.exit_json(changed=True, node=node.to_dict(computed=False))
+34 -1
View File
@@ -40,6 +40,13 @@ options:
- I(name) cannot be updated without deleting and re-creating the user. - I(name) cannot be updated without deleting and re-creating the user.
required: true required: true
type: str type: str
options:
description:
- A dictionary of Keystone user options to set on the user, e.g.
C(ignore_password_expiry) or C(ignore_change_password_upon_first_use).
- On update, the provided options are merged with the user's existing
options, so options not specified here are preserved.
type: dict
password: password:
description: description:
- Password for the user. - Password for the user.
@@ -99,6 +106,17 @@ EXAMPLES = r'''
email: demo@example.com email: demo@example.com
domain: default domain: default
default_project: demo default_project: demo
- name: Create a user with password policy options
openstack.cloud.identity_user:
cloud: mycloud
state: present
name: demouser
password: secret
domain: default
options:
ignore_password_expiry: true
ignore_change_password_upon_first_use: true
''' '''
RETURN = r''' RETURN = r'''
@@ -138,6 +156,10 @@ user:
description: Unique user name, within the owning domain description: Unique user name, within the owning domain
type: str type: str
sample: "demouser" sample: "demouser"
options:
description: The resource options for the user (e.g.
ignore_password_expiry).
type: dict
password: password:
description: Credential used during authentication description: Credential used during authentication
type: str type: str
@@ -159,6 +181,7 @@ class IdentityUserModule(OpenStackModule):
email=dict(), email=dict(),
is_enabled=dict(default=True, type='bool', aliases=['enabled']), is_enabled=dict(default=True, type='bool', aliases=['enabled']),
name=dict(required=True), name=dict(required=True),
options=dict(type='dict'),
password=dict(no_log=True), password=dict(no_log=True),
state=dict(default='present', choices=['absent', 'present']), state=dict(default='present', choices=['absent', 'present']),
update_password=dict(default='on_create', update_password=dict(default='on_create',
@@ -177,6 +200,16 @@ class IdentityUserModule(OpenStackModule):
elif update_password == 'on_create' and 'password' in attributes: elif update_password == 'on_create' and 'password' in attributes:
attributes.pop('password') attributes.pop('password')
if 'options' in attributes:
# Merge desired options with the user's existing options so
# that options not managed by this module are preserved, and
# so the update is idempotent when the desired options already
# match the current values.
current = self.get_function(resource['id'])
merged = dict(current['options'] or {})
merged.update(attributes['options'])
attributes['options'] = merged
return super()._build_update(resource, attributes, return super()._build_update(resource, attributes,
updateable_attributes, updateable_attributes,
non_updateable_attributes, **kwargs) non_updateable_attributes, **kwargs)
@@ -202,7 +235,7 @@ class IdentityUserModule(OpenStackModule):
kwargs['attributes'] = \ kwargs['attributes'] = \
dict((k, self.params[k]) dict((k, self.params[k])
for k in ['description', 'email', 'is_enabled', 'name', for k in ['description', 'email', 'is_enabled', 'name',
'password'] 'options', 'password']
if self.params[k] is not None) if self.params[k] is not None)
domain_name_or_id = self.params['domain'] domain_name_or_id = self.params['domain']
+47 -17
View File
@@ -125,21 +125,29 @@ options:
use_import: use_import:
description: description:
- Use the 'glance-direct' method of the interoperable image import mechanism. - Use the 'glance-direct' method of the interoperable image import mechanism.
- Applies only to uploads from I(filename). I(import_method) does not
affect it.
- Should only be used when needed, such as when the user needs the cloud to - Should only be used when needed, such as when the user needs the cloud to
transform image format. transform image format.
type: bool type: bool
import_method: import_method:
description: description:
- Method to use for importing the image. Not all deployments support all methods. - Interoperable image import method that the Image service uses to
- Supports web-download or glance-download. download the image data.
- copy-image is not supported with create actions. - The only supported method is web-download. The Image service downloads
- glance-direct is removed from the import method so use_import can be used in that case. the image data from I(uri).
- If I(uri) is set and I(import_method) is not, the module uses
web-download.
- For glance-direct uploads from I(filename), use I(use_import).
type: str type: str
choices: [web-download, glance-download] choices: [web-download]
uri: uri:
description: description:
- Required only if using the web-download import method. - URL the Image service downloads the image data from.
- This url is where the data is made available to the Image service. - Requires I(import_method=web-download), which is the default when
I(uri) is given, and a Glance with that import method enabled.
- Mutually exclusive with I(filename) and I(volume). The image data
never passes through the Ansible controller.
type: str type: str
extends_documentation_fragment: extends_documentation_fragment:
@@ -147,6 +155,15 @@ extends_documentation_fragment:
''' '''
EXAMPLES = r''' EXAMPLES = r'''
- name: Have the Image service download an image itself
openstack.cloud.image:
cloud: devstack
name: cirros
container_format: bare
disk_format: qcow2
import_method: web-download
uri: https://download.cirros-cloud.net/0.6.2/cirros-0.6.2-x86_64-disk.img
- name: Upload an image from a local file named cirros-0.3.0-x86_64-disk.img - name: Upload an image from a local file named cirros-0.3.0-x86_64-disk.img
openstack.cloud.image: openstack.cloud.image:
cloud: devstack-admin cloud: devstack-admin
@@ -413,7 +430,7 @@ class ImageModule(OpenStackModule):
visibility=dict(choices=['public', 'private', 'shared', 'community']), visibility=dict(choices=['public', 'private', 'shared', 'community']),
volume=dict(), volume=dict(),
use_import=dict(type='bool'), use_import=dict(type='bool'),
import_method=dict(choices=['web-download', 'glance-download']), import_method=dict(choices=['web-download']),
uri=dict() uri=dict()
) )
@@ -422,13 +439,15 @@ class ImageModule(OpenStackModule):
('filename', 'volume', 'uri'), ('filename', 'volume', 'uri'),
('visibility', 'is_public'), ('visibility', 'is_public'),
], ],
required_if=[
('import_method', 'web-download', ['uri']),
],
) )
# resource attributes obtainable directly from params # resource attributes obtainable directly from params
attr_params = ('id', 'name', 'filename', 'disk_format', attr_params = ('id', 'name', 'filename', 'disk_format',
'container_format', 'wait', 'timeout', 'is_public', 'container_format', 'wait', 'timeout', 'is_public',
'is_protected', 'min_disk', 'min_ram', 'volume', 'tags', 'is_protected', 'min_disk', 'min_ram', 'volume', 'tags')
'use_import', 'import_method', 'uri')
def _resolve_visibility(self): def _resolve_visibility(self):
"""resolve a visibility value to be compatible with older versions""" """resolve a visibility value to be compatible with older versions"""
@@ -497,14 +516,13 @@ class ImageModule(OpenStackModule):
wait=self.params['timeout'], wait=self.params['timeout'],
attribute='status') attribute='status')
def _import_uploaded_image(self, image): def _import_image(self, image, method, **kwargs):
if not hasattr(self.conn.image, 'import_image'): if not hasattr(self.conn.image, 'import_image'):
self.fail_json( self.fail_json(
msg="The installed openstacksdk library does not support " msg="The installed openstacksdk library does not support "
"image import operations required for images in the " "image import operations.")
"'uploading' state.")
self.conn.image.import_image(image, method='glance-direct') self.conn.image.import_image(image, method=method, **kwargs)
return self._wait_for_image_active(self.conn.get_image(image.id)) return self._wait_for_image_active(self.conn.get_image(image.id))
def run(self): def run(self):
@@ -536,15 +554,23 @@ class ImageModule(OpenStackModule):
changed = False changed = False
if self.params['state'] == 'present': if self.params['state'] == 'present':
import_method = self.params['import_method']
if self.params['uri'] and not import_method:
import_method = 'web-download'
attrs = self._build_params(owner) attrs = self._build_params(owner)
if not image: if not image:
# self.conn.image.create_image() cannot be used because it does # self.conn.image.create_image() cannot be used because it does
# not provide self.conn.create_image()'s volume parameter [0]. # not provide self.conn.create_image()'s volume parameter [0].
# [0] https://opendev.org/openstack/openstacksdk/src/commit/ # [0] https://opendev.org/openstack/openstacksdk/src/commit/
# a41d04ea197439c2f134ce3554995693933a46ac/openstack/cloud/_image.py#L306 # a41d04ea197439c2f134ce3554995693933a46ac/openstack/cloud/_image.py#L306
if import_method:
# Without data, the image stays queued until the import
# below starts. Waiting for it here times out.
attrs['wait'] = False
image = self.conn.create_image(**attrs) image = self.conn.create_image(**attrs)
changed = True changed = True
if not self.params['wait']: if not self.params['wait'] and not import_method:
self.exit_json(changed=changed, self.exit_json(changed=changed,
image=self._return_value(image.id)) image=self._return_value(image.id))
@@ -552,7 +578,11 @@ class ImageModule(OpenStackModule):
self.conn.image.reactivate_image(image) self.conn.image.reactivate_image(image)
changed = True changed = True
elif image['status'] == 'queued': elif image['status'] == 'queued':
if ( if import_method == 'web-download':
image = self._import_image(
image, import_method, uri=self.params['uri'])
changed = True
elif (
self.params['filename'] self.params['filename']
and hasattr(self.conn.image, 'stage_image')): and hasattr(self.conn.image, 'stage_image')):
self.conn.image.stage_image( self.conn.image.stage_image(
@@ -570,7 +600,7 @@ class ImageModule(OpenStackModule):
image = self.conn.get_image(image.id) image = self.conn.get_image(image.id)
if image['status'] == 'uploading' and self.params['use_import']: if image['status'] == 'uploading' and self.params['use_import']:
image = self._import_uploaded_image(image) image = self._import_image(image, 'glance-direct')
changed = True changed = True
elif image['status'] == 'importing': elif image['status'] == 'importing':
image = self._wait_for_image_active(image) image = self._wait_for_image_active(image)
+1 -1
View File
@@ -235,7 +235,7 @@ class LoadBalancerPoolModule(OpenStackModule):
loadbalancer_name_or_id, ignore_missing=False) loadbalancer_name_or_id, ignore_missing=False)
# Field load_balancer_id is not returned from self.conn.\ # Field load_balancer_id is not returned from self.conn.\
# load_balancer.find_load_balancer() so use load_balancers instead. # load_balancer.find_load_balancer() so use load_balancers instead.
if listener['load_balancers'] != [dict(id=loadbalancer.id)]: if pool['loadbalancers'] != [dict(id=loadbalancer.id)]:
non_updateable_keys.append('loadbalancer_id') non_updateable_keys.append('loadbalancer_id')
if non_updateable_keys: if non_updateable_keys:
+7 -2
View File
@@ -64,6 +64,10 @@ options:
choices: [present, absent] choices: [present, absent]
default: present default: present
type: str type: str
availability_zone:
description:
- The availability zone, in which the load balancer will be deployed.
type: str
vip_address: vip_address:
description: description:
- IP address of the load balancer virtual IP. - IP address of the load balancer virtual IP.
@@ -279,6 +283,7 @@ class LoadBalancerModule(OpenStackModule):
floating_ip_network=dict(aliases=['public_network']), floating_ip_network=dict(aliases=['public_network']),
name=dict(required=True), name=dict(required=True),
state=dict(default='present', choices=['absent', 'present']), state=dict(default='present', choices=['absent', 'present']),
availability_zone=dict(),
vip_address=dict(), vip_address=dict(),
vip_network=dict(), vip_network=dict(),
vip_port=dict(), vip_port=dict(),
@@ -337,7 +342,7 @@ class LoadBalancerModule(OpenStackModule):
def _build_update(self, load_balancer): def _build_update(self, load_balancer):
update = {} update = {}
non_updateable_keys = [k for k in ['name', 'vip_address'] non_updateable_keys = [k for k in ['name', 'vip_address', 'availability_zone']
if self.params[k] is not None if self.params[k] is not None
and self.params[k] != load_balancer[k]] and self.params[k] != load_balancer[k]]
@@ -456,7 +461,7 @@ class LoadBalancerModule(OpenStackModule):
def _create(self): def _create(self):
kwargs = dict((k, self.params[k]) kwargs = dict((k, self.params[k])
for k in ['description', 'name', 'vip_address'] for k in ['description', 'name', 'vip_address', 'availability_zone']
if self.params[k] is not None) if self.params[k] is not None)
flavor_name_or_id = self.params['flavor'] flavor_name_or_id = self.params['flavor']
+3 -2
View File
@@ -252,7 +252,7 @@ class NeutronRBACPolicy(OpenStackModule):
matches = self._find_matches() matches = self._find_matches()
if len(matches) > 1: if len(matches) > 1:
self.fail_json(msg='Found more a single matching RBAC policy' self.fail_json(msg='Found more than a single matching RBAC policy'
' which match the given parameters.') ' which match the given parameters.')
elif len(matches) == 1: elif len(matches) == 1:
return matches[0] return matches[0]
@@ -269,7 +269,8 @@ class NeutronRBACPolicy(OpenStackModule):
.format(', '.join(missing_keys))) .format(', '.join(missing_keys)))
kwargs = dict((k, self.params[k]) kwargs = dict((k, self.params[k])
for k in ['action', 'object_type', 'project_id']) for k in ['action', 'object_type', 'project_id',
'target_project_id'])
policies = self.conn.network.rbac_policies(**kwargs) policies = self.conn.network.rbac_policies(**kwargs)
+35 -2
View File
@@ -21,6 +21,9 @@ options:
name: name:
description: description:
- Name of the recordset. It must be ended with name of dns zone. - Name of the recordset. It must be ended with name of dns zone.
- A recordset is identified by I(zone), I(name) and I(recordset_type)
because DNS allows several recordsets to share a name as long as
their types differ.
required: true required: true
type: str type: str
records: records:
@@ -33,6 +36,11 @@ options:
description: description:
- Recordset type - Recordset type
- Required when I(state=present). - Required when I(state=present).
- Used to identify the recordset, together with I(zone) and I(name).
When I(state=absent) and this option is omitted, the recordset is
looked up by name only, which fails when its name carries more than
one type, e.g. at the apex of a zone where SOA and NS recordsets
share the name of the zone.
choices: ['a', 'aaaa', 'mx', 'cname', 'txt', 'ns', 'srv', 'ptr', 'caa'] choices: ['a', 'aaaa', 'mx', 'cname', 'txt', 'ns', 'srv', 'ptr', 'caa']
type: str type: str
state: state:
@@ -76,12 +84,25 @@ EXAMPLES = '''
records: ['10.1.1.1'] records: ['10.1.1.1']
ttl: 7200 ttl: 7200
# Delete recordset named "www.example.net." # Create a recordset at the apex of zone "example.net.", where the SOA and NS
# recordsets created with the zone share its name
- openstack.cloud.recordset:
cloud: mycloud
state: present
zone: example.net.
name: example.net.
recordset_type: "a"
records: ['10.1.1.1']
ttl: 3600
# Delete the "a" recordset named "www.example.net.", leaving recordsets of
# other types with that name untouched
- openstack.cloud.recordset: - openstack.cloud.recordset:
cloud: mycloud cloud: mycloud
state: absent state: absent
zone: example.net. zone: example.net.
name: www.example.net. name: www.example.net.
recordset_type: "a"
''' '''
RETURN = ''' RETURN = '''
@@ -204,6 +225,18 @@ class DnsRecordsetModule(OpenStackModule):
return True return True
return False return False
def _find_recordset(self, zone, name):
# A recordset is identified by zone, name and type: DNS allows several
# recordsets to share a name as long as their types differ, e.g. at the
# apex of a zone where the SOA and NS recordsets share the name of the
# zone. Looking a recordset up by name only would match all of them and
# fail with a DuplicateResource error.
query = {}
recordset_type = self.params['recordset_type']
if recordset_type is not None:
query['type'] = recordset_type.upper()
return self.conn.dns.find_recordset(zone, name, **query)
def _build_params(self): def _build_params(self):
recordset_type = self.params['recordset_type'] recordset_type = self.params['recordset_type']
records = self.params['records'] records = self.params['records']
@@ -224,7 +257,7 @@ class DnsRecordsetModule(OpenStackModule):
ttl = self.params.get('ttl') ttl = self.params.get('ttl')
zone = self.conn.dns.find_zone(name_or_id=zone, ignore_missing=False) zone = self.conn.dns.find_zone(name_or_id=zone, ignore_missing=False)
recordset = self.conn.dns.find_recordset(zone, name) recordset = self._find_recordset(zone, name)
if self.ansible.check_mode: if self.ansible.check_mode:
self.exit_json(changed=self._system_state_change(state, recordset)) self.exit_json(changed=self._system_state_change(state, recordset))
+8 -1
View File
@@ -497,8 +497,15 @@ class RouterModule(OpenStackModule):
if 'net' not in iface: if 'net' not in iface:
self.fail( self.fail(
"Network name missing from interface definition") "Network name missing from interface definition")
# First try to find a network in the specified project.
net = self.conn.network.find_network(iface['net'], net = self.conn.network.find_network(iface['net'],
ignore_missing=False) ignore_missing=False,
**filters)
# Fall back to a global search for the network.
if not net:
net = self.conn.network.find_network(
iface['net'],
ignore_missing=False)
if 'portip' not in iface: if 'portip' not in iface:
# portip not set, add any ip from subnet # portip not set, add any ip from subnet
+7 -4
View File
@@ -1228,10 +1228,13 @@ class ServerModule(OpenStackModule):
if not isinstance(stringified_nets, list): if not isinstance(stringified_nets, list):
self.fail_json(msg="The 'nics' parameter must be a list.") self.fail_json(msg="The 'nics' parameter must be a list.")
nets = [(dict((nested_net.split('='),)) nets = []
for nested_net in net.split(',')) for net in stringified_nets:
if isinstance(net, str) else net if isinstance(net, str):
for net in stringified_nets] for nested_net in net.split(','):
nets.append(dict((nested_net.split('='),)))
else:
nets.append(net)
for net in nets: for net in nets:
if not isinstance(net, dict): if not isinstance(net, dict):
+41 -4
View File
@@ -17,9 +17,10 @@ options:
- Action to perform. - Action to perform.
- By default, only server owners and administrators are allowed to - By default, only server owners and administrators are allowed to
perform actions C(pause), C(unpause), C(suspend), C(resume), C(lock), perform actions C(pause), C(unpause), C(suspend), C(resume), C(lock),
C(unlock) and C(shelve_offload). C(unlock), C(shelve_offload) and C(live_migrate).
choices: [lock, pause, reboot_hard, reboot_soft, rebuild, resume, shelve, choices: [lock, pause, reboot_hard, reboot_soft, rebuild, resume, shelve,
shelve_offload, start, stop, suspend, unlock, unpause, unshelve] shelve_offload, start, stop, suspend, unlock, unpause, unshelve,
live_migrate]
type: str type: str
required: true required: true
admin_password: admin_password:
@@ -42,6 +43,13 @@ options:
required: true required: true
type: str type: str
aliases: ['server'] aliases: ['server']
host:
description:
- Target hypervisor host for C(live_migrate) action. If not specified, the server will be
live migrated to a suitable host automatically selected by Nova scheduler.
type: str
required: false
version_added: 2.7.0
extends_documentation_fragment: extends_documentation_fragment:
- openstack.cloud.openstack - openstack.cloud.openstack
''' '''
@@ -53,6 +61,20 @@ EXAMPLES = r'''
action: pause action: pause
server: vm1 server: vm1
timeout: 200 timeout: 200
- name: Live migrate compute instance to an auto-selected hypervisor
openstack.cloud.server_action:
cloud: devstack-admin
action: live_migrate
server: vm1
timeout: 200
- name: Live migrate compute instance to a specified hypervisor
openstack.cloud.server_action:
cloud: devstack-admin
action: live_migrate
server: vm1
host: compute1
''' '''
from ansible_collections.openstack.cloud.plugins.module_utils.openstack import OpenStackModule from ansible_collections.openstack.cloud.plugins.module_utils.openstack import OpenStackModule
@@ -64,9 +86,10 @@ class ServerActionModule(OpenStackModule):
choices=['stop', 'start', 'pause', 'unpause', choices=['stop', 'start', 'pause', 'unpause',
'lock', 'unlock', 'suspend', 'reboot_soft', 'lock', 'unlock', 'suspend', 'reboot_soft',
'reboot_hard', 'resume', 'rebuild', 'shelve', 'reboot_hard', 'resume', 'rebuild', 'shelve',
'shelve_offload', 'unshelve']), 'shelve_offload', 'unshelve', 'live_migrate']),
admin_password=dict(no_log=True), admin_password=dict(no_log=True),
all_projects=dict(type='bool', default=False), all_projects=dict(type='bool', default=False),
host=dict(type='str', default=None),
image=dict(), image=dict(),
name=dict(required=True, aliases=['server']), name=dict(required=True, aliases=['server']),
) )
@@ -116,7 +139,9 @@ class ServerActionModule(OpenStackModule):
'rebuild': ['ACTIVE'], 'rebuild': ['ACTIVE'],
'shelve': ['SHELVED_OFFLOADED', 'SHELVED'], 'shelve': ['SHELVED_OFFLOADED', 'SHELVED'],
'shelve_offload': ['SHELVED_OFFLOADED'], 'shelve_offload': ['SHELVED_OFFLOADED'],
'unshelve': ['ACTIVE']} 'unshelve': ['ACTIVE'],
'live_migrate': ['ACTIVE'],
}
def run(self): def run(self):
# TODO: Replace with self.conn.compute.find_server( # TODO: Replace with self.conn.compute.find_server(
@@ -141,10 +166,17 @@ class ServerActionModule(OpenStackModule):
or (action == 'reboot_soft') or (action == 'reboot_soft')
or (action == 'lock' and not server['is_locked']) or (action == 'lock' and not server['is_locked'])
or (action == 'unlock' and server['is_locked']) or (action == 'unlock' and server['is_locked'])
or (action == 'live_migrate' and not server.status.lower() == 'migrating')
or server.status.lower() not in [a.lower() or server.status.lower() not in [a.lower()
for a for a
in self._action_map[action]]) in self._action_map[action]])
# If live_migrate targets the same host the VM is already on, skip it
if action == 'live_migrate' and self.params['host'] is not None:
current_host = server.get('OS-EXT-SRV-ATTR:host') or server.get('hypervisor_hostname')
if current_host and current_host == self.params['host']:
self.exit_json(changed=False, msg='VM is already on target host {0}, skipping migration.'.format(self.params['host']))
if not will_change: if not will_change:
self.exit_json(changed=False) self.exit_json(changed=False)
elif self.ansible.check_mode: elif self.ansible.check_mode:
@@ -189,6 +221,11 @@ class ServerActionModule(OpenStackModule):
func_name(server, 'SOFT') func_name(server, 'SOFT')
elif action == 'reboot_hard': elif action == 'reboot_hard':
func_name(server, 'HARD') func_name(server, 'HARD')
elif action == 'live_migrate':
kwargs = {}
if self.params['host'] is not None:
kwargs['host'] = self.params['host']
func_name(server, **kwargs)
else: else:
func_name(server) func_name(server)
+3 -3
View File
@@ -361,14 +361,14 @@ class SubnetModule(OpenStackModule):
self.fail_json( self.fail_json(
msg='Cannot update {0} in existing subnet'.format(attr)) msg='Cannot update {0} in existing subnet'.format(attr))
def _system_state_change(self, subnet, network, project, subnet_pool): def _system_state_change(self, subnet, network, segment, project, subnet_pool):
state = self.params['state'] state = self.params['state']
if state == 'absent': if state == 'absent':
return subnet is not None return subnet is not None
# else state is present # else state is present
if not subnet: if not subnet:
return True return True
params = self._build_params(network, project, subnet_pool) params = self._build_params(network, segment, project, subnet_pool)
updates = self._build_updates(subnet, params) updates = self._build_updates(subnet, params)
self._validate_update(subnet, updates) self._validate_update(subnet, updates)
return bool(updates) return bool(updates)
@@ -478,7 +478,7 @@ class SubnetModule(OpenStackModule):
if self.ansible.check_mode: if self.ansible.check_mode:
self.exit_json(changed=self._system_state_change( self.exit_json(changed=self._system_state_change(
subnet, network, project, subnet_pool)) subnet, network, segment, project, subnet_pool))
changed = False changed = False
if state == 'present': if state == 'present':
+1 -1
View File
@@ -114,7 +114,7 @@ class VolumeTypeAccess(OpenStackModule):
if project_name_or_id: if project_name_or_id:
project_id = self.conn.identity.find_project( project_id = self.conn.identity.find_project(
project_name_or_id, ignore_missing=False, *kwargs).id project_name_or_id, ignore_missing=False, **kwargs).id
else: else:
project_id = None project_id = None
+12
View File
@@ -0,0 +1,12 @@
ansible-core>=2.21.0,<2.22.0
flake8
galaxy-importer
openstacksdk
pycodestyle
pylint
rstcheck
ruamel.yaml
tox
voluptuous
yamllint
setuptools
@@ -0,0 +1,170 @@
import unittest
from unittest import mock
from ansible_collections.openstack.cloud.plugins.modules import identity_user
from ansible_collections.openstack.cloud.tests.unit.modules.utils import (
AnsibleExitJson,
ModuleTestCase,
set_module_args,
)
class FakeUser(dict):
'''A dict-like stand-in for an openstacksdk identity.v3.user.User.'''
def to_dict(self, computed=False):
return dict(self)
class FakeSDK(object):
class exceptions:
class OpenStackCloudException(Exception):
pass
class TestIdentityUser(ModuleTestCase):
def _run_module(self, module_args, identity):
set_module_args(module_args)
conn = mock.Mock()
conn.identity = identity
with mock.patch.object(
identity_user.IdentityUserModule,
'openstack_cloud_from_module',
return_value=(FakeSDK(), conn),
):
identity_user.main()
def _new_identity(self, existing_user=None):
identity = mock.Mock()
if existing_user is None:
identity.find_user.return_value = None
else:
identity.find_user.return_value = existing_user
identity.get_user.return_value = existing_user
return identity
# -- create -----------------------------------------------------------
def test_create_user_with_options(self):
identity = self._new_identity(existing_user=None)
identity.create_user.return_value = FakeUser(
id='1', name='demouser', is_enabled=True,
options={'ignore_password_expiry': True,
'ignore_change_password_upon_first_use': True},
)
with self.assertRaises(AnsibleExitJson) as ex:
self._run_module({
'name': 'demouser',
'options': {
'ignore_password_expiry': True,
'ignore_change_password_upon_first_use': True,
},
}, identity)
result = ex.exception.args[0]
self.assertTrue(result['changed'])
identity.create_user.assert_called_once()
_, kwargs = identity.create_user.call_args
self.assertEqual(
{'ignore_password_expiry': True,
'ignore_change_password_upon_first_use': True},
kwargs['options'])
identity.update_user.assert_not_called()
def test_create_user_without_options(self):
identity = self._new_identity(existing_user=None)
identity.create_user.return_value = FakeUser(
id='1', name='demouser', is_enabled=True, options={})
with self.assertRaises(AnsibleExitJson) as ex:
self._run_module({'name': 'demouser'}, identity)
result = ex.exception.args[0]
self.assertTrue(result['changed'])
identity.create_user.assert_called_once()
_, kwargs = identity.create_user.call_args
self.assertNotIn('options', kwargs)
# -- update -----------------------------------------------------------
def _existing_user(self, **options):
return FakeUser(
id='1', name='demouser', is_enabled=True, options=options)
def test_update_user_options_idempotent(self):
user = self._existing_user(
ignore_password_expiry=True,
ignore_change_password_upon_first_use=True,
)
identity = self._new_identity(existing_user=user)
with self.assertRaises(AnsibleExitJson) as ex:
self._run_module({
'name': 'demouser',
'options': {
'ignore_password_expiry': True,
'ignore_change_password_upon_first_use': True,
},
}, identity)
result = ex.exception.args[0]
self.assertFalse(result['changed'])
identity.update_user.assert_not_called()
def test_update_user_options_change(self):
user = self._existing_user(ignore_password_expiry=False)
identity = self._new_identity(existing_user=user)
identity.update_user.return_value = FakeUser(
id='1', name='demouser', is_enabled=True,
options={'ignore_password_expiry': True})
with self.assertRaises(AnsibleExitJson) as ex:
self._run_module({
'name': 'demouser',
'options': {'ignore_password_expiry': True},
}, identity)
result = ex.exception.args[0]
self.assertTrue(result['changed'])
identity.update_user.assert_called_once_with(
'1', options={'ignore_password_expiry': True})
def test_update_user_options_merge_preserves_existing(self):
user = self._existing_user(
lock_password=True,
ignore_password_expiry=False,
)
identity = self._new_identity(existing_user=user)
identity.update_user.return_value = FakeUser(
id='1', name='demouser', is_enabled=True,
options={'lock_password': True, 'ignore_password_expiry': True})
with self.assertRaises(AnsibleExitJson) as ex:
self._run_module({
'name': 'demouser',
'options': {'ignore_password_expiry': True},
}, identity)
result = ex.exception.args[0]
self.assertTrue(result['changed'])
identity.update_user.assert_called_once_with(
'1',
options={'lock_password': True, 'ignore_password_expiry': True})
def test_update_user_without_options_preserves_existing(self):
# When no options are specified, existing options must not be touched.
user = self._existing_user(ignore_password_expiry=True)
identity = self._new_identity(existing_user=user)
with self.assertRaises(AnsibleExitJson) as ex:
self._run_module({'name': 'demouser'}, identity)
result = ex.exception.args[0]
self.assertFalse(result['changed'])
identity.update_user.assert_not_called()
if __name__ == '__main__':
unittest.main()
@@ -16,13 +16,48 @@ class AnsibleExit(Exception):
pass pass
class FakeSDK(object):
class exceptions(object):
class OpenStackCloudException(Exception):
pass
class ResourceNotFound(OpenStackCloudException):
pass
class HelperServerModule(os_server.ServerModule):
def __init__(self, params, conn, sdk):
self.params = {}
for k, v in self.argument_spec.items():
if 'default' in v:
self.params[k] = v['default']
else:
self.params[k] = None
self.params.update(params)
if ('floating_ips' in params or 'floating_ip_pools' in params) and 'auto_ip' not in params:
self.params['auto_ip'] = False
self.params = collections.defaultdict(str, self.params)
self.conn = conn
self.sdk = sdk
self.module_name = 'server'
self.check_mode = False
self.results = {'changed': False}
self.ansible = mock.MagicMock()
self.ansible.check_mode = False
self.ansible.exit_json.side_effect = AnsibleExit
self.ansible.fail_json.side_effect = AnsibleFail
self.exit_json = self.ansible.exit_json
self.fail_json = self.ansible.fail_json
def params_from_doc(func): def params_from_doc(func):
'''This function extracts the docstring from the specified function, '''This function extracts the docstring from the specified function,
parses it as a YAML document, and returns parameters for the openstack.cloud.server parses it as a YAML document, and returns parameters for the openstack.cloud.server
module.''' module.'''
doc = inspect.getdoc(func) doc = inspect.getdoc(func)
cfg = yaml.load(doc) cfg = yaml.safe_load(doc)
for task in cfg: for task in cfg:
for module, params in task.items(): for module, params in task.items():
@@ -95,15 +130,32 @@ class TestNetworkArgs(object):
def setup_method(self, method): def setup_method(self, method):
self.cloud = FakeCloud() self.cloud = FakeCloud()
self.module = mock.MagicMock() self.cloud.network = mock.MagicMock()
self.module.params = params_from_doc(method)
def find_network(name, ignore_missing=False):
net = self.cloud.get_network(name)
if net:
return mock.MagicMock(id=net['id'])
raise Exception("Network not found")
def find_port(name, ignore_missing=False):
port = self.cloud.get_port(name)
if port:
return mock.MagicMock(id=port['id'])
raise Exception("Port not found")
self.cloud.network.find_network.side_effect = find_network
self.cloud.network.find_port.side_effect = find_port
self.params = params_from_doc(method)
self.module = HelperServerModule(self.params, self.cloud, FakeSDK())
def test_nics_string_net_id(self): def test_nics_string_net_id(self):
''' '''
- openstack.cloud.server: - openstack.cloud.server:
nics: net-id=1234 nics: net-id=1234
''' '''
args = os_server._network_args(self.module, self.cloud) args = self.module._parse_nics()
assert args[0]['net-id'] == '1234' assert args[0]['net-id'] == '1234'
def test_nics_string_net_id_list(self): def test_nics_string_net_id_list(self):
@@ -111,7 +163,7 @@ class TestNetworkArgs(object):
- openstack.cloud.server: - openstack.cloud.server:
nics: net-id=1234,net-id=4321 nics: net-id=1234,net-id=4321
''' '''
args = os_server._network_args(self.module, self.cloud) args = self.module._parse_nics()
assert args[0]['net-id'] == '1234' assert args[0]['net-id'] == '1234'
assert args[1]['net-id'] == '4321' assert args[1]['net-id'] == '4321'
@@ -120,7 +172,7 @@ class TestNetworkArgs(object):
- openstack.cloud.server: - openstack.cloud.server:
nics: port-id=1234 nics: port-id=1234
''' '''
args = os_server._network_args(self.module, self.cloud) args = self.module._parse_nics()
assert args[0]['port-id'] == '1234' assert args[0]['port-id'] == '1234'
def test_nics_string_net_name(self): def test_nics_string_net_name(self):
@@ -128,7 +180,7 @@ class TestNetworkArgs(object):
- openstack.cloud.server: - openstack.cloud.server:
nics: net-name=network1 nics: net-name=network1
''' '''
args = os_server._network_args(self.module, self.cloud) args = self.module._parse_nics()
assert args[0]['net-id'] == '5678' assert args[0]['net-id'] == '5678'
def test_nics_string_port_name(self): def test_nics_string_port_name(self):
@@ -136,7 +188,7 @@ class TestNetworkArgs(object):
- openstack.cloud.server: - openstack.cloud.server:
nics: port-name=port1 nics: port-name=port1
''' '''
args = os_server._network_args(self.module, self.cloud) args = self.module._parse_nics()
assert args[0]['port-id'] == '1234' assert args[0]['port-id'] == '1234'
def test_nics_structured_net_id(self): def test_nics_structured_net_id(self):
@@ -145,7 +197,7 @@ class TestNetworkArgs(object):
nics: nics:
- net-id: '1234' - net-id: '1234'
''' '''
args = os_server._network_args(self.module, self.cloud) args = self.module._parse_nics()
assert args[0]['net-id'] == '1234' assert args[0]['net-id'] == '1234'
def test_nics_structured_mixed(self): def test_nics_structured_mixed(self):
@@ -156,7 +208,7 @@ class TestNetworkArgs(object):
- port-name: port1 - port-name: port1
- 'net-name=network1,port-id=4321' - 'net-name=network1,port-id=4321'
''' '''
args = os_server._network_args(self.module, self.cloud) args = self.module._parse_nics()
assert args[0]['net-id'] == '1234' assert args[0]['net-id'] == '1234'
assert args[1]['port-id'] == '1234' assert args[1]['port-id'] == '1234'
assert args[2]['net-id'] == '5678' assert args[2]['net-id'] == '5678'
@@ -166,10 +218,31 @@ class TestNetworkArgs(object):
class TestCreateServer(object): class TestCreateServer(object):
def setup_method(self, method): def setup_method(self, method):
self.cloud = FakeCloud() self.cloud = FakeCloud()
self.module = mock.MagicMock() self.cloud.compute = mock.MagicMock()
self.module.params = params_from_doc(method) self.cloud.compute.find_server.return_value = None
self.module.fail_json.side_effect = AnsibleFail() self.cloud.compute.get_server.return_value = mock.MagicMock()
self.module.exit_json.side_effect = AnsibleExit() self.cloud.compute.get_server.return_value.to_dict.return_value = {'id': '1234'}
def find_flavor(name_or_id, ignore_missing=True):
flavor = self.cloud.get_flavor(name_or_id)
if flavor:
return mock.MagicMock(id=flavor['id'])
if not ignore_missing:
raise FakeSDK.exceptions.ResourceNotFound("Could not find flavor {0}".format(name_or_id))
return None
self.cloud.compute.find_flavor.side_effect = find_flavor
self.cloud.network = mock.MagicMock()
def find_network(name, ignore_missing=False):
net = self.cloud.get_network(name)
if net:
return mock.MagicMock(id=net['id'])
raise Exception("Network not found")
self.cloud.network.find_network.side_effect = find_network
self.params = params_from_doc(method)
self.module = HelperServerModule(self.params, self.cloud, FakeSDK())
self.meta = mock.MagicMock() self.meta = mock.MagicMock()
self.meta.gett_hostvars_from_server.return_value = { self.meta.gett_hostvars_from_server.return_value = {
@@ -188,7 +261,7 @@ class TestCreateServer(object):
- key: value - key: value
''' '''
with pytest.raises(AnsibleExit): with pytest.raises(AnsibleExit):
os_server._create_server(self.module, self.cloud) self.module()
assert self.cloud.create_server.call_count == 1 assert self.cloud.create_server.call_count == 1
assert self.cloud.create_server.call_args[1]['image'] == self.cloud.get_image_id('cirros') assert self.cloud.create_server.call_args[1]['image'] == self.cloud.get_image_id('cirros')
@@ -204,7 +277,7 @@ class TestCreateServer(object):
- net-name: network1 - net-name: network1
''' '''
with pytest.raises(AnsibleFail): with pytest.raises(AnsibleFail):
os_server._create_server(self.module, self.cloud) self.module()
assert 'missing_flavor' in self.module.fail_json.call_args[1]['msg'] assert 'missing_flavor' in self.module.fail_json.call_args[1]['msg']
@@ -216,8 +289,12 @@ class TestCreateServer(object):
nics: nics:
- net-name: missing_network - net-name: missing_network
''' '''
def find_network_fail(name, ignore_missing=False):
raise FakeSDK.exceptions.ResourceNotFound("missing_network")
self.cloud.network.find_network.side_effect = find_network_fail
with pytest.raises(AnsibleFail): with pytest.raises(AnsibleFail):
os_server._create_server(self.module, self.cloud) self.module()
assert 'missing_network' in self.module.fail_json.call_args[1]['msg'] assert 'missing_network' in self.module.fail_json.call_args[1]['msg']
@@ -231,7 +308,7 @@ class TestCreateServer(object):
- net-name: network1 - net-name: network1
''' '''
with pytest.raises(AnsibleFail): with pytest.raises(AnsibleFail):
os_server._create_server(self.module, self.cloud) self.module()
assert 'auto_ip' in self.module.fail_json.call_args[1]['msg'] assert 'auto_ip' in self.module.fail_json.call_args[1]['msg']
@@ -245,7 +322,7 @@ class TestCreateServer(object):
- net-name: network1 - net-name: network1
''' '''
with pytest.raises(AnsibleFail): with pytest.raises(AnsibleFail):
os_server._create_server(self.module, self.cloud) self.module()
assert 'floating_ips' in self.module.fail_json.call_args[1]['msg'] assert 'floating_ips' in self.module.fail_json.call_args[1]['msg']
@@ -259,6 +336,6 @@ class TestCreateServer(object):
- net-name: network1 - net-name: network1
''' '''
with pytest.raises(AnsibleFail): with pytest.raises(AnsibleFail):
os_server._create_server(self.module, self.cloud) self.module()
assert 'floating_ip_pools' in self.module.fail_json.call_args[1]['msg'] assert 'floating_ip_pools' in self.module.fail_json.call_args[1]['msg']
+44 -1
View File
@@ -53,16 +53,59 @@ hostvars = {
} }
try:
from ansible._internal._templating._engine import TrustedAsTemplate
has_trusted = True
except ImportError:
has_trusted = False
def tag_trusted(val):
if not has_trusted:
return val
if isinstance(val, dict):
return {k: tag_trusted(v) for k, v in val.items()}
elif isinstance(val, list):
return [tag_trusted(v) for v in val]
elif isinstance(val, str):
return TrustedAsTemplate().tag(val)
return val
@pytest.fixture(scope="module") @pytest.fixture(scope="module")
def inventory(): def inventory():
inventory = InventoryModule() inventory = InventoryModule()
inventory._config_data = config_data inventory._config_data = tag_trusted(config_data)
inventory.inventory = InventoryData() inventory.inventory = InventoryData()
inventory.templar = Templar(loader=None) inventory.templar = Templar(loader=None)
for host in hostvars: for host in hostvars:
inventory.inventory.add_host(host) inventory.inventory.add_host(host)
def _set_variables(hostvars, groups):
for host in hostvars:
try:
inventory._set_composite_vars(
inventory._config_data.get('compose'), hostvars[host], host, strict=True)
except Exception as e:
print("set_composite_vars error: %s" % e)
raise
for key in hostvars[host]:
inventory.inventory.set_variable(host, key, hostvars[host][key])
try:
inventory._add_host_to_composed_groups(
inventory._config_data.get('groups'), hostvars[host], host, strict=True)
except Exception as e:
print("add_host_to_composed_groups error: %s" % e)
raise
try:
inventory._add_host_to_keyed_groups(
inventory._config_data.get('keyed_groups'), hostvars[host], host, strict=True)
except Exception as e:
print("add_host_to_keyed_groups error: %s" % e)
raise
inventory._set_variables = _set_variables
return inventory return inventory
+4
View File
@@ -44,3 +44,7 @@ ansible-test sanity -v \
--python ${PY_VER} \ --python ${PY_VER} \
$SKIP_TESTS \ $SKIP_TESTS \
plugins/ docs/ meta/ plugins/ docs/ meta/
ansible-test units -v \
--venv \
--python ${PY_VER}
+4 -2
View File
@@ -41,7 +41,7 @@ commands =
ansible-galaxy collection build --force {toxinidir} --output-path {toxinidir}/build_artifact ansible-galaxy collection build --force {toxinidir} --output-path {toxinidir}/build_artifact
bash {toxinidir}/tools/check-import.sh {toxinidir} bash {toxinidir}/tools/check-import.sh {toxinidir}
[testenv:linters_{2_18,2_19,2_20,latest}] [testenv:linters_{2_18,2_19,2_20,2_21,latest}]
allowlist_externals = bash allowlist_externals = bash
commands = commands =
{[testenv:build]commands} {[testenv:build]commands}
@@ -55,6 +55,7 @@ deps =
linters_2_18: -r{toxinidir}/tests/requirements-ansible-2.18.txt linters_2_18: -r{toxinidir}/tests/requirements-ansible-2.18.txt
linters_2_19: -r{toxinidir}/tests/requirements-ansible-2.19.txt linters_2_19: -r{toxinidir}/tests/requirements-ansible-2.19.txt
linters_2_20: -r{toxinidir}/tests/requirements-ansible-2.20.txt linters_2_20: -r{toxinidir}/tests/requirements-ansible-2.20.txt
linters_2_21: -r{toxinidir}/tests/requirements-ansible-2.21.txt
passenv = * passenv = *
[flake8] [flake8]
@@ -68,7 +69,7 @@ ignore = W503,H4,E501,E402,H301
show-source = True show-source = True
exclude=.venv,.git,.tox,dist,doc,*lib/python*,*egg,build,ansible_collections exclude=.venv,.git,.tox,dist,doc,*lib/python*,*egg,build,ansible_collections
[testenv:ansible_{2_18,2_19,2_20,latest}] [testenv:ansible_{2_18,2_19,2_20,2_21,latest}]
allowlist_externals = bash allowlist_externals = bash
commands = commands =
bash {toxinidir}/ci/run-ansible-tests-collection.sh -e {envdir} {posargs} bash {toxinidir}/ci/run-ansible-tests-collection.sh -e {envdir} {posargs}
@@ -78,6 +79,7 @@ deps =
ansible_2_18: -r{toxinidir}/tests/requirements-ansible-2.18.txt ansible_2_18: -r{toxinidir}/tests/requirements-ansible-2.18.txt
ansible_2_19: -r{toxinidir}/tests/requirements-ansible-2.19.txt ansible_2_19: -r{toxinidir}/tests/requirements-ansible-2.19.txt
ansible_2_20: -r{toxinidir}/tests/requirements-ansible-2.20.txt ansible_2_20: -r{toxinidir}/tests/requirements-ansible-2.20.txt
ansible_2_21: -r{toxinidir}/tests/requirements-ansible-2.21.txt
# Need to pass some env vars for the Ansible playbooks # Need to pass some env vars for the Ansible playbooks
passenv = passenv =
HOME HOME