mirror of
https://github.com/ansible/awx.git
synced 2026-01-11 01:57:35 -03:30
Merge pull request #6733 from john-westcott-iv/tower_schedule
Initial version of tower_schedule Reviewed-by: https://github.com/apps/softwarefactory-project-zuul
This commit is contained in:
commit
496c0c5921
6
Makefile
6
Makefile
@ -380,7 +380,11 @@ test_collection:
|
||||
@if [ "$(VENV_BASE)" ]; then \
|
||||
. $(VENV_BASE)/awx/bin/activate; \
|
||||
fi; \
|
||||
PYTHONPATH=$PYTHONPATH:/usr/lib/python3.6/site-packages py.test $(COLLECTION_TEST_DIRS)
|
||||
PYTHONPATH=$(PYTHONPATH):$(VENV_BASE)/awx/lib/python3.6/site-packages:/usr/lib/python3.6/site-packages py.test $(COLLECTION_TEST_DIRS)
|
||||
# The python path needs to be modified so that the tests can find Ansible within the container
|
||||
# First we will use anything expility set as PYTHONPATH
|
||||
# Second we will load any libraries out of the virtualenv (if it's unspecified that should be ok because python should not load out of an empty directory)
|
||||
# Finally we will add the system path so that the tests can find the ansible libraries
|
||||
|
||||
flake8_collection:
|
||||
flake8 awx_collection/ # Different settings, in main exclude list
|
||||
|
||||
249
awx_collection/plugins/lookup/tower_schedule_rrule.py
Normal file
249
awx_collection/plugins/lookup/tower_schedule_rrule.py
Normal file
@ -0,0 +1,249 @@
|
||||
# (c) 2020 Ansible Project
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
|
||||
DOCUMENTATION = """
|
||||
lookup: tower_schedule_rrule
|
||||
author: John Westcott IV (@john-westcott-iv)
|
||||
version_added: "3.7"
|
||||
short_description: Generate an rrule string which can be used for Tower Schedules
|
||||
requirements:
|
||||
- pytz
|
||||
- python.dateutil >= 2.7.0
|
||||
description:
|
||||
- Returns a string based on criteria which represent an rule
|
||||
options:
|
||||
_terms:
|
||||
description:
|
||||
- The frequency of the schedule
|
||||
- none - Run this schedule once
|
||||
- minute - Run this schedule ever x minutes
|
||||
- hour - Run this schedule every x hours
|
||||
- day - Run this schedule ever x days
|
||||
- week - Run this schedule weekly
|
||||
- month - Run this schedule monthly
|
||||
required: True
|
||||
choices: ['none', 'minute', 'hour', 'day', 'week', 'month']
|
||||
start_date:
|
||||
description:
|
||||
- The date to start the rule
|
||||
- Used for all frequencies
|
||||
- Format should be YYYY-MM-DD [HH:MM:SS]
|
||||
type: str
|
||||
timezone:
|
||||
description:
|
||||
- The timezone to use for this rule
|
||||
- Used for all frequencies
|
||||
- Format should be as US/Eastern
|
||||
- Defaults to America/New_York
|
||||
type: str
|
||||
every:
|
||||
description:
|
||||
- The repition in months, weeks, days hours or minutes
|
||||
- Used for all types except none
|
||||
type: int
|
||||
end_on:
|
||||
description:
|
||||
- How to end this schedule
|
||||
- If this is not defined this schedule will never end
|
||||
- If this is a positive integer this schedule will end after this number of occurances
|
||||
- If this is a date in the format YYYY-MM-DD [HH:MM:SS] this schedule end after this date
|
||||
- Used for all types except none
|
||||
type: str
|
||||
on_days:
|
||||
description:
|
||||
- The days to run this schedule on
|
||||
- A comma seperated list which can contain values sunday, monday, tuesday, wednesday, thursday, friday
|
||||
- Used for week type schedules
|
||||
month_day_number:
|
||||
description:
|
||||
- The day of the month this schedule will run on (0-31)
|
||||
- Used for month type schedules
|
||||
- Can not be used with on_the parameter
|
||||
type: int
|
||||
on_the:
|
||||
description:
|
||||
- A description on when this schedule will run
|
||||
- Two strings seperated by space
|
||||
- First string is one of first, second, third, fourth, last
|
||||
- Second string is one of sunday, monday, tuesday, wednesday, thursday, friday
|
||||
- Used for month type schedules
|
||||
- Can not be used with month_day_number parameters
|
||||
"""
|
||||
|
||||
EXAMPLES = """
|
||||
- name: Create a string for a schedule
|
||||
debug:
|
||||
msg: "{{ query('awx.awx.tower_schedule_rrule', 'none', start_date='1979-09-13 03:45:07') }}"
|
||||
"""
|
||||
|
||||
RETURN = """
|
||||
_raw:
|
||||
description:
|
||||
- String in the rrule format
|
||||
type: string
|
||||
"""
|
||||
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.errors import AnsibleError
|
||||
from datetime import datetime
|
||||
import re
|
||||
from distutils.version import LooseVersion
|
||||
|
||||
missing_modules = []
|
||||
try:
|
||||
import pytz
|
||||
except ImportError:
|
||||
missing_modules.append('pytz')
|
||||
|
||||
try:
|
||||
from dateutil import rrule
|
||||
except ImportError:
|
||||
missing_modules.append('python.dateutil')
|
||||
|
||||
# Validate the version of python.dateutil
|
||||
try:
|
||||
import dateutil
|
||||
if LooseVersion(dateutil.__version__) < LooseVersion("2.7.0"):
|
||||
raise Exception
|
||||
except Exception:
|
||||
missing_modules.append('python.dateutil>=2.7.0')
|
||||
|
||||
if len(missing_modules) > 0:
|
||||
raise AnsibleError('You are missing the modules {0}'.format(', '.join(missing_modules)))
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
frequencies = {
|
||||
'none': rrule.DAILY,
|
||||
'minute': rrule.MINUTELY,
|
||||
'hour': rrule.HOURLY,
|
||||
'day': rrule.DAILY,
|
||||
'week': rrule.WEEKLY,
|
||||
'month': rrule.MONTHLY,
|
||||
}
|
||||
|
||||
weekdays = {
|
||||
'monday': rrule.MO,
|
||||
'tuesday': rrule.TU,
|
||||
'wednesday': rrule.WE,
|
||||
'thursday': rrule.TH,
|
||||
'friday': rrule.FR,
|
||||
'saturday': rrule.SA,
|
||||
'sunday': rrule.SU,
|
||||
}
|
||||
|
||||
set_positions = {
|
||||
'first': 1,
|
||||
'second': 2,
|
||||
'third': 3,
|
||||
'fourth': 4,
|
||||
'last': -1,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def parse_date_time(date_string):
|
||||
try:
|
||||
return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
|
||||
except ValueError:
|
||||
return datetime.strptime(date_string, '%Y-%m-%d')
|
||||
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
if len(terms) != 1:
|
||||
raise AnsibleError('You may only pass one schedule type in at a time')
|
||||
|
||||
frequency = terms[0].lower()
|
||||
|
||||
return self.get_rrule(frequency, kwargs)
|
||||
|
||||
@staticmethod
|
||||
def get_rrule(frequency, kwargs):
|
||||
|
||||
if frequency not in LookupModule.frequencies:
|
||||
raise AnsibleError('Frequency of {0} is invalid'.format(frequency))
|
||||
|
||||
rrule_kwargs = {
|
||||
'freq': LookupModule.frequencies[frequency],
|
||||
'interval': kwargs.get('every', 1),
|
||||
}
|
||||
|
||||
# All frequencies can use a start date
|
||||
if 'start_date' in kwargs:
|
||||
try:
|
||||
rrule_kwargs['dtstart'] = LookupModule.parse_date_time(kwargs['start_date'])
|
||||
except Exception:
|
||||
raise AnsibleError('Parameter start_date must be in the format YYYY-MM-DD [HH:MM:SS]')
|
||||
|
||||
# If we are a none frequency we don't need anything else
|
||||
if frequency == 'none':
|
||||
rrule_kwargs['count'] = 1
|
||||
else:
|
||||
# All non-none frequencies can have an end_on option
|
||||
if 'end_on' in kwargs:
|
||||
end_on = kwargs['end_on']
|
||||
if re.match(r'^\d+$', end_on):
|
||||
rrule_kwargs['count'] = end_on
|
||||
else:
|
||||
try:
|
||||
rrule_kwargs['until'] = LookupModule.parse_date_time(end_on)
|
||||
except Exception:
|
||||
raise AnsibleError('Parameter end_on must either be an integer or in the format YYYY-MM-DD [HH:MM:SS]')
|
||||
|
||||
# A week based frequency can also take the on_days parameter
|
||||
if frequency == 'week' and 'on_days' in kwargs:
|
||||
days = []
|
||||
for day in kwargs['on_days'].split(','):
|
||||
day = day.strip()
|
||||
if day not in LookupModule.weekdays:
|
||||
raise AnsibleError('Parameter on_days must only contain values {0}'.format(', '.join(LookupModule.weekdays.keys())))
|
||||
days.append(LookupModule.weekdays[day])
|
||||
|
||||
rrule_kwargs['byweekday'] = days
|
||||
|
||||
# A month based frequency can also deal with month_day_number and on_the options
|
||||
if frequency == 'month':
|
||||
if 'month_day_number' in kwargs and 'on_the' in kwargs:
|
||||
raise AnsibleError('Month based frquencies can have month_day_number or on_the but not both')
|
||||
|
||||
if 'month_day_number' in kwargs:
|
||||
try:
|
||||
my_month_day = int(kwargs['month_day_number'])
|
||||
if my_month_day < 1 or my_month_day > 31:
|
||||
raise Exception()
|
||||
except Exception:
|
||||
raise AnsibleError('month_day_number must be between 1 and 31')
|
||||
|
||||
rrule_kwargs['bymonthday'] = my_month_day
|
||||
|
||||
if 'on_the' in kwargs:
|
||||
try:
|
||||
(occurance, weekday) = kwargs['on_the'].split(' ')
|
||||
except Exception:
|
||||
raise AnsibleError('on_the parameter must be two space seperated words')
|
||||
|
||||
if weekday not in LookupModule.weekdays:
|
||||
raise AnsibleError('Weekday portion of on_the parameter is not valid')
|
||||
if occurance not in LookupModule.set_positions:
|
||||
raise AnsibleError('The first string of the on_the parameter is not valid')
|
||||
|
||||
rrule_kwargs['byweekday'] = LookupModule.weekdays[weekday]
|
||||
rrule_kwargs['bysetpos'] = LookupModule.set_positions[occurance]
|
||||
|
||||
my_rule = rrule.rrule(**rrule_kwargs)
|
||||
|
||||
# All frequencies can use a timezone but rrule can't support the format that tower uses.
|
||||
# So we will do a string manip here if we need to
|
||||
timezone = 'America/New_York'
|
||||
if 'timezone' in kwargs:
|
||||
if kwargs['timezone'] not in pytz.all_timezones:
|
||||
raise AnsibleError('Timezone parameter is not valid')
|
||||
timezone = kwargs['timezone']
|
||||
|
||||
# rrule puts a \n in the rule instad of a space and can't hand timezones
|
||||
return_rrule = str(my_rule).replace('\n', ' ').replace('DTSTART:', 'DTSTART;TZID={0}:'.format(timezone))
|
||||
# Tower requires an interval. rrule will not add interval if its set to 1
|
||||
if kwargs.get('every', 1) == 1:
|
||||
return_rrule = "{0};INTERVAL=1".format(return_rrule)
|
||||
|
||||
return return_rrule
|
||||
250
awx_collection/plugins/modules/tower_schedule.py
Normal file
250
awx_collection/plugins/modules/tower_schedule.py
Normal file
@ -0,0 +1,250 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
|
||||
# (c) 2020, John Westcott IV <john.westcott.iv@redhat.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_schedule
|
||||
author: "John Westcott IV (@john-westcott-iv)"
|
||||
version_added: "2.3"
|
||||
short_description: create, update, or destroy Ansible Tower schedules.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower schedules. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
rrule:
|
||||
description:
|
||||
- A value representing the schedules iCal recurrence rule.
|
||||
- See rrule plugin for help constructing this value
|
||||
required: False
|
||||
type: str
|
||||
name:
|
||||
description:
|
||||
- Name of this schedule.
|
||||
required: True
|
||||
type: str
|
||||
new_name:
|
||||
description:
|
||||
- Setting this option will change the existing name (looked up via the name field.
|
||||
required: False
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- Optional description of this schedule.
|
||||
required: False
|
||||
type: str
|
||||
extra_data:
|
||||
description:
|
||||
- Specify C(extra_vars) for the template.
|
||||
required: False
|
||||
type: dict
|
||||
default: {}
|
||||
inventory:
|
||||
description:
|
||||
- Inventory applied as a prompt, assuming job template prompts for inventory
|
||||
required: False
|
||||
type: str
|
||||
scm_branch:
|
||||
description:
|
||||
- Branch to use in job run. Project default used if blank. Only allowed if project allow_override field is set to true.
|
||||
required: False
|
||||
type: str
|
||||
job_type:
|
||||
description:
|
||||
- The job type to use for the job template.
|
||||
required: False
|
||||
type: str
|
||||
choices:
|
||||
- 'run'
|
||||
- 'check'
|
||||
job_tags:
|
||||
description:
|
||||
- Comma separated list of the tags to use for the job template.
|
||||
required: False
|
||||
type: str
|
||||
skip_tags:
|
||||
description:
|
||||
- Comma separated list of the tags to skip for the job template.
|
||||
required: False
|
||||
type: str
|
||||
limit:
|
||||
description:
|
||||
- A host pattern to further constrain the list of hosts managed or affected by the playbook
|
||||
required: False
|
||||
type: str
|
||||
diff_mode:
|
||||
description:
|
||||
- Enable diff mode for the job template.
|
||||
required: False
|
||||
type: bool
|
||||
verbosity:
|
||||
description:
|
||||
- Control the output level Ansible produces as the playbook runs. 0 - Normal, 1 - Verbose, 2 - More Verbose, 3 - Debug, 4 - Connection Debug.
|
||||
required: False
|
||||
type: int
|
||||
choices:
|
||||
- 0
|
||||
- 1
|
||||
- 2
|
||||
- 3
|
||||
- 4
|
||||
- 5
|
||||
unified_job_template:
|
||||
description:
|
||||
- Name of unified job template to schedule.
|
||||
required: False
|
||||
type: str
|
||||
enabled:
|
||||
description:
|
||||
- Enables processing of this schedule.
|
||||
required: False
|
||||
type: bool
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
choices: ["present", "absent"]
|
||||
default: "present"
|
||||
type: str
|
||||
tower_oauthtoken:
|
||||
description:
|
||||
- The Tower OAuth token to use.
|
||||
required: False
|
||||
type: str
|
||||
version_added: "3.7"
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Build a schedule for Demo Job Template
|
||||
tower_schedule:
|
||||
name: "{{ sched1 }}"
|
||||
state: present
|
||||
unified_job_template: "Demo Job Template"
|
||||
rrule: "DTSTART:20191219T130551Z RRULE:FREQ=WEEKLY;INTERVAL=1;COUNT=1"
|
||||
register: result
|
||||
|
||||
- name: Build the same schedule using the rrule plugin
|
||||
tower_schedule:
|
||||
name: "{{ sched1 }}"
|
||||
state: present
|
||||
unified_job_template: "Demo Job Template"
|
||||
rrule: "{{ query('awx.awx.tower_schedule_rrule', 'week', start_date='2019-12-19 13:05:51') }}"
|
||||
register: result
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
rrule=dict(),
|
||||
name=dict(required=True),
|
||||
new_name=dict(),
|
||||
description=dict(),
|
||||
extra_data=dict(type='dict'),
|
||||
inventory=dict(),
|
||||
scm_branch=dict(),
|
||||
job_type=dict(choices=['run', 'check']),
|
||||
job_tags=dict(),
|
||||
skip_tags=dict(),
|
||||
limit=dict(),
|
||||
diff_mode=dict(type='bool'),
|
||||
verbosity=dict(type='int', choices=[0, 1, 2, 3, 4, 5]),
|
||||
unified_job_template=dict(),
|
||||
enabled=dict(type='bool'),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
rrule = module.params.get('rrule')
|
||||
name = module.params.get('name')
|
||||
new_name = module.params.get("new_name")
|
||||
description = module.params.get('description')
|
||||
extra_data = module.params.get('extra_data')
|
||||
inventory = module.params.get('inventory')
|
||||
scm_branch = module.params.get('scm_branch')
|
||||
job_type = module.params.get('job_type')
|
||||
job_tags = module.params.get('job_tags')
|
||||
skip_tags = module.params.get('skip_tags')
|
||||
limit = module.params.get('limit')
|
||||
diff_mode = module.params.get('diff_mode')
|
||||
verbosity = module.params.get('verbosity')
|
||||
unified_job_template = module.params.get('unified_job_template')
|
||||
enabled = module.params.get('enabled')
|
||||
state = module.params.get('state')
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
inventory_id = None
|
||||
if inventory:
|
||||
inventory_id = module.resolve_name_to_id('inventories', inventory)
|
||||
unified_job_template_id = None
|
||||
if unified_job_template:
|
||||
unified_job_template_id = module.resolve_name_to_id('unified_job_templates', unified_job_template)
|
||||
|
||||
# Attempt to look up an existing item based on the provided data
|
||||
existing_item = module.get_one('schedules', **{
|
||||
'data': {
|
||||
'name': name,
|
||||
}
|
||||
})
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
new_fields = {}
|
||||
if rrule is not None:
|
||||
new_fields['rrule'] = rrule
|
||||
new_fields['name'] = new_name if new_name else name
|
||||
if description is not None:
|
||||
new_fields['description'] = description
|
||||
if extra_data is not None:
|
||||
new_fields['extra_data'] = extra_data
|
||||
if inventory is not None:
|
||||
new_fields['inventory'] = inventory_id
|
||||
if scm_branch is not None:
|
||||
new_fields['scm_branch'] = scm_branch
|
||||
if job_type is not None:
|
||||
new_fields['job_type'] = job_type
|
||||
if job_tags is not None:
|
||||
new_fields['job_tags'] = job_tags
|
||||
if skip_tags is not None:
|
||||
new_fields['skip_tags'] = skip_tags
|
||||
if limit is not None:
|
||||
new_fields['limit'] = limit
|
||||
if diff_mode is not None:
|
||||
new_fields['diff_mode'] = diff_mode
|
||||
if verbosity is not None:
|
||||
new_fields['verbosity'] = verbosity
|
||||
if unified_job_template is not None:
|
||||
new_fields['unified_job_template'] = unified_job_template_id
|
||||
if enabled is not None:
|
||||
new_fields['enabled'] = enabled
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(existing_item)
|
||||
elif state == 'present':
|
||||
# If the state was present and we can let the module build or update the existing item, this will return on its own
|
||||
module.create_or_update_if_needed(
|
||||
existing_item, new_fields,
|
||||
endpoint='schedules', item_type='schedule',
|
||||
associations={
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@ -15,7 +15,7 @@ from requests.models import Response
|
||||
import pytest
|
||||
|
||||
from awx.main.tests.functional.conftest import _request
|
||||
from awx.main.models import Organization, Project, Inventory, Credential, CredentialType
|
||||
from awx.main.models import Organization, Project, Inventory, JobTemplate, Credential, CredentialType
|
||||
|
||||
try:
|
||||
import tower_cli # noqa
|
||||
@ -221,6 +221,16 @@ def inventory(organization):
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job_template(project, inventory):
|
||||
return JobTemplate.objects.create(
|
||||
name='test-jt',
|
||||
project=project,
|
||||
inventory=inventory,
|
||||
playbook='helloworld.yml'
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def machine_credential(organization):
|
||||
ssh_type = CredentialType.defaults['ssh']()
|
||||
|
||||
107
awx_collection/test/awx/test_schedule.py
Normal file
107
awx_collection/test/awx/test_schedule.py
Normal file
@ -0,0 +1,107 @@
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
|
||||
import pytest
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
|
||||
from awx.main.models import Schedule
|
||||
from awx.api.serializers import SchedulePreviewSerializer
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_create_schedule(run_module, job_template, admin_user):
|
||||
my_rrule = 'DTSTART;TZID=Zulu:20200416T034507 RRULE:FREQ=MONTHLY;INTERVAL=1'
|
||||
result = run_module('tower_schedule', {
|
||||
'name': 'foo_schedule',
|
||||
'unified_job_template': job_template.name,
|
||||
'rrule': my_rrule
|
||||
}, admin_user)
|
||||
assert not result.get('failed', False), result.get('msg', result)
|
||||
|
||||
schedule = Schedule.objects.filter(name='foo_schedule').first()
|
||||
|
||||
assert result['id'] == schedule.id
|
||||
assert result['changed']
|
||||
|
||||
assert schedule.rrule == my_rrule
|
||||
|
||||
|
||||
@pytest.mark.parametrize("freq, kwargs, expect", [
|
||||
# Test with a valid start date (no time) (also tests none frequency and count)
|
||||
('none', {'start_date': '2020-04-16'}, 'DTSTART;TZID=America/New_York:20200416T000000 RRULE:FREQ=DAILY;COUNT=1;INTERVAL=1'),
|
||||
# Test with a valid start date and time
|
||||
('none', {'start_date': '2020-04-16 03:45:07'}, 'DTSTART;TZID=America/New_York:20200416T034507 RRULE:FREQ=DAILY;COUNT=1;INTERVAL=1'),
|
||||
# Test end_on as count (also integration test)
|
||||
('minute', {'start_date': '2020-4-16 03:45:07', 'end_on': '2'}, 'DTSTART;TZID=America/New_York:20200416T034507 RRULE:FREQ=MINUTELY;COUNT=2;INTERVAL=1'),
|
||||
# Test end_on as date
|
||||
('minute', {'start_date': '2020-4-16 03:45:07', 'end_on': '2020-4-17 03:45:07'},
|
||||
'DTSTART;TZID=America/New_York:20200416T034507 RRULE:FREQ=MINUTELY;UNTIL=20200417T034507;INTERVAL=1'),
|
||||
# Test on_days as a single day
|
||||
('week', {'start_date': '2020-4-16 03:45:07', 'on_days': 'saturday'},
|
||||
'DTSTART;TZID=America/New_York:20200416T034507 RRULE:FREQ=WEEKLY;BYDAY=SA;INTERVAL=1'),
|
||||
# Test on_days as multiple days (with some whitespaces)
|
||||
('week', {'start_date': '2020-4-16 03:45:07', 'on_days': 'saturday,monday , friday'},
|
||||
'DTSTART;TZID=America/New_York:20200416T034507 RRULE:FREQ=WEEKLY;BYDAY=MO,FR,SA;INTERVAL=1'),
|
||||
# Test valid month_day_number
|
||||
('month', {'start_date': '2020-4-16 03:45:07', 'month_day_number': '18'},
|
||||
'DTSTART;TZID=America/New_York:20200416T034507 RRULE:FREQ=MONTHLY;BYMONTHDAY=18;INTERVAL=1'),
|
||||
# Test a valid on_the
|
||||
('month', {'start_date': '2020-4-16 03:45:07', 'on_the': 'second sunday'},
|
||||
'DTSTART;TZID=America/New_York:20200416T034507 RRULE:FREQ=MONTHLY;BYSETPOS=2;BYDAY=SU;INTERVAL=1'),
|
||||
# Test an valid timezone
|
||||
('month', {'start_date': '2020-4-16 03:45:07', 'timezone': 'Zulu'},
|
||||
'DTSTART;TZID=Zulu:20200416T034507 RRULE:FREQ=MONTHLY;INTERVAL=1'),
|
||||
])
|
||||
def test_rrule_lookup_plugin(collection_import, freq, kwargs, expect):
|
||||
LookupModule = collection_import('plugins.lookup.tower_schedule_rrule').LookupModule
|
||||
generated_rule = LookupModule.get_rrule(freq, kwargs)
|
||||
assert generated_rule == expect
|
||||
rrule_checker = SchedulePreviewSerializer()
|
||||
# Try to run our generated rrule through the awx validator
|
||||
# This will raise its own exception on failure
|
||||
rrule_checker.validate_rrule(generated_rule)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("freq", ('none', 'minute', 'hour', 'day', 'week', 'month'))
|
||||
def test_empty_schedule_rrule(collection_import, freq):
|
||||
LookupModule = collection_import('plugins.lookup.tower_schedule_rrule').LookupModule
|
||||
if freq == 'day':
|
||||
pfreq = 'DAILY'
|
||||
elif freq == 'none':
|
||||
pfreq = 'DAILY;COUNT=1'
|
||||
else:
|
||||
pfreq = freq.upper() + 'LY'
|
||||
assert LookupModule.get_rrule(freq, {}).endswith(' RRULE:FREQ={0};INTERVAL=1'.format(pfreq))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("freq, kwargs, msg", [
|
||||
# Test end_on as junk
|
||||
('minute', {'start_date': '2020-4-16 03:45:07', 'end_on': 'junk'},
|
||||
'Parameter end_on must either be an integer or in the format YYYY-MM-DD'),
|
||||
# Test on_days as junk
|
||||
('week', {'start_date': '2020-4-16 03:45:07', 'on_days': 'junk'},
|
||||
'Parameter on_days must only contain values monday, tuesday, wednesday, thursday, friday, saturday, sunday'),
|
||||
# Test combo of both month_day_number and on_the
|
||||
('month', dict(start_date='2020-4-16 03:45:07', on_the='something', month_day_number='else'),
|
||||
"Month based frquencies can have month_day_number or on_the but not both"),
|
||||
# Test month_day_number as not an integer
|
||||
('month', dict(start_date='2020-4-16 03:45:07', month_day_number='junk'), "month_day_number must be between 1 and 31"),
|
||||
# Test month_day_number < 1
|
||||
('month', dict(start_date='2020-4-16 03:45:07', month_day_number='0'), "month_day_number must be between 1 and 31"),
|
||||
# Test month_day_number > 31
|
||||
('month', dict(start_date='2020-4-16 03:45:07', month_day_number='32'), "month_day_number must be between 1 and 31"),
|
||||
# Test on_the as junk
|
||||
('month', dict(start_date='2020-4-16 03:45:07', on_the='junk'), "on_the parameter must be two space seperated words"),
|
||||
# Test on_the with invalid occurance
|
||||
('month', dict(start_date='2020-4-16 03:45:07', on_the='junk wednesday'), "The first string of the on_the parameter is not valid"),
|
||||
# Test on_the with invalid weekday
|
||||
('month', dict(start_date='2020-4-16 03:45:07', on_the='second junk'), "Weekday portion of on_the parameter is not valid"),
|
||||
# Test an invalid timezone
|
||||
('month', dict(start_date='2020-4-16 03:45:07', timezone='junk'), 'Timezone parameter is not valid'),
|
||||
])
|
||||
def test_rrule_lookup_plugin_failure(collection_import, freq, kwargs, msg):
|
||||
LookupModule = collection_import('plugins.lookup.tower_schedule_rrule').LookupModule
|
||||
with pytest.raises(AnsibleError) as e:
|
||||
assert LookupModule.get_rrule(freq, kwargs)
|
||||
assert msg in str(e.value)
|
||||
@ -0,0 +1,88 @@
|
||||
---
|
||||
- name: Generate a random string for test
|
||||
set_fact:
|
||||
test_id: "{{ lookup('password', '/dev/null chars=ascii_letters length=16') }}"
|
||||
|
||||
- name: generate random string for project
|
||||
set_fact:
|
||||
sched1: "AWX-Collection-tests-tower_schedule-sched1-{{ test_id }}"
|
||||
|
||||
- name: Try to create without an rrule
|
||||
tower_schedule:
|
||||
name: "{{ sched1 }}"
|
||||
state: present
|
||||
unified_job_template: "Demo Job Template"
|
||||
enabled: true
|
||||
register: result
|
||||
ignore_errors: true
|
||||
|
||||
- assert:
|
||||
that:
|
||||
- result is failed
|
||||
- "'Unable to create schedule {{ sched1 }}' in result.msg"
|
||||
|
||||
- name: Create with options that the JT does not support
|
||||
tower_schedule:
|
||||
name: "{{ sched1 }}"
|
||||
state: present
|
||||
unified_job_template: "Demo Job Template"
|
||||
rrule: "DTSTART:20191219T130551Z RRULE:FREQ=WEEKLY;INTERVAL=1;COUNT=1"
|
||||
description: "This hopefully will not work"
|
||||
extra_data:
|
||||
some: var
|
||||
inventory: Demo Inventory
|
||||
scm_branch: asdf1234
|
||||
job_type: run
|
||||
job_tags: other_tags
|
||||
skip_tags: some_tags
|
||||
limit: node1
|
||||
diff_mode: true
|
||||
verbosity: 4
|
||||
enabled: true
|
||||
register: result
|
||||
ignore_errors: true
|
||||
|
||||
- assert:
|
||||
that:
|
||||
- result is failed
|
||||
- "'Unable to create schedule {{ sched1 }}' in result.msg"
|
||||
|
||||
- name: Build a real schedule
|
||||
tower_schedule:
|
||||
name: "{{ sched1 }}"
|
||||
state: present
|
||||
unified_job_template: "Demo Job Template"
|
||||
rrule: "DTSTART:20191219T130551Z RRULE:FREQ=WEEKLY;INTERVAL=1;COUNT=1"
|
||||
register: result
|
||||
|
||||
- assert:
|
||||
that:
|
||||
- result is changed
|
||||
|
||||
- name: Rebuild the same schedule
|
||||
tower_schedule:
|
||||
name: "{{ sched1 }}"
|
||||
state: present
|
||||
unified_job_template: "Demo Job Template"
|
||||
rrule: "DTSTART:20191219T130551Z RRULE:FREQ=WEEKLY;INTERVAL=1;COUNT=1"
|
||||
register: result
|
||||
|
||||
- assert:
|
||||
that:
|
||||
- result is not changed
|
||||
|
||||
- name: Disable a schedule
|
||||
tower_schedule:
|
||||
name: "{{ sched1 }}"
|
||||
state: present
|
||||
enabled: "false"
|
||||
register: result
|
||||
|
||||
- assert:
|
||||
that:
|
||||
- result is changed
|
||||
|
||||
- name: Delete the schedule
|
||||
tower_schedule:
|
||||
name: "{{ sched1 }}"
|
||||
state: absent
|
||||
@ -0,0 +1,42 @@
|
||||
---
|
||||
- name: Test too many params (failure from validation of terms)
|
||||
debug:
|
||||
msg: "{{ query('awx.awx.tower_schedule_rrule', 'none', 'weekly', start_date='2020-4-16 03:45:07') }}"
|
||||
ignore_errors: true
|
||||
register: result
|
||||
|
||||
- assert:
|
||||
that:
|
||||
- result is failed
|
||||
- "'You may only pass one schedule type in at a time' in result.msg"
|
||||
|
||||
- name: Test invalid frequency (failure from validation of term)
|
||||
debug:
|
||||
msg: "{{ query('awx.awx.tower_schedule_rrule', 'john', start_date='2020-4-16 03:45:07') }}"
|
||||
ignore_errors: true
|
||||
register: result
|
||||
|
||||
- assert:
|
||||
that:
|
||||
- result is failed
|
||||
- "'Frequency of john is invalid' in result.msg"
|
||||
|
||||
- name: Test an invalid start date (generic failure case from get_rrule)
|
||||
debug:
|
||||
msg: "{{ query('awx.awx.tower_schedule_rrule', 'none', start_date='invalid') }}"
|
||||
ignore_errors: true
|
||||
register: result
|
||||
|
||||
- assert:
|
||||
that:
|
||||
- result is failed
|
||||
- "'Parameter start_date must be in the format YYYY-MM-DD' in result.msg"
|
||||
|
||||
- name: Test end_on as count (generic success case)
|
||||
debug:
|
||||
msg: "{{ query('awx.awx.tower_schedule_rrule', 'minute', start_date='2020-4-16 03:45:07', end_on='2') }}"
|
||||
register: result
|
||||
|
||||
- assert:
|
||||
that:
|
||||
- result.msg == 'DTSTART;TZID=America/New_York:20200416T034507 RRULE:FREQ=MINUTELY;COUNT=2;INTERVAL=1'
|
||||
Loading…
x
Reference in New Issue
Block a user