Exemple #1
0
    def payload(self, organization, **kwargs):
        payload = PseudoNamespace(name=kwargs.get('name')
                                  or 'Inventory - {}'.format(random_title()),
                                  description=kwargs.get('description')
                                  or random_title(10),
                                  organization=organization.id)

        optional_fields = ('host_filter', 'insights_credential', 'kind',
                           'variables')

        update_payload(payload, optional_fields, kwargs)

        if 'variables' in payload and isinstance(payload.variables, dict):
            payload.variables = json.dumps(payload.variables)
        if 'insights_credential' in payload and isinstance(
                payload.insights_credential, Credential):
            payload.insights_credential = payload.insights_credential.id

        return payload
Exemple #2
0
    def payload(self, **kwargs):
        payload = PseudoNamespace(
            name=kwargs.get('name')
            or 'Organization - {}'.format(random_title()),
            description=kwargs.get('description') or random_title(10))

        for fk_field in ('default_environment', ):
            rel_obj = kwargs.get(fk_field)
            if rel_obj is None:
                continue
            elif isinstance(rel_obj, int):
                payload.update(**{fk_field: int(rel_obj)})
            elif hasattr(rel_obj, 'id'):
                payload.update(**{fk_field: rel_obj.id})
            else:
                raise AttributeError(
                    f'Related field {fk_field} must be either integer of pkid or object'
                )
        return payload
Exemple #3
0
 def add_survey(self,
                spec=None,
                name=None,
                description=None,
                required=False,
                enabled=True):
     payload = dict(
         name=name or 'Survey - {}'.format(random_title()),
         description=description or random_title(10),
         spec=spec or [
             dict(required=required,
                  question_name="What's the password?",
                  variable="secret",
                  type="password",
                  default="foo")
         ],
     )
     if enabled != self.survey_enabled:
         self.patch(survey_enabled=enabled)
     return self.related.survey_spec.post(payload).get()
    def add_schedule(
            self,
            name='',
            description='',
            enabled=True,
            rrule=None,
            **kwargs):
        if rrule is None:
            rrule = "DTSTART:30180101T000000Z RRULE:FREQ=YEARLY;INTERVAL=1"
        payload = dict(
            name=name or "{0} Schedule {1}".format(
                self.name,
                random_title()),
            description=description or random_title(10),
            enabled=enabled,
            rrule=str(rrule))

        update_payload(payload, self.optional_schedule_fields, kwargs)

        return self.related.schedules.post(payload)
    def payload(self, **kwargs):
        payload = PseudoNamespace(
            name=kwargs.get('name')
            or 'Instance Group - {}'.format(random_title()))
        fields = ('policy_instance_percentage', 'policy_instance_minimum',
                  'policy_instance_list', 'is_container_group')
        update_payload(payload, fields, kwargs)

        set_payload_foreign_key_args(payload, ('credential', ), kwargs)

        return payload
    def payload(self, name='', image=None, organization=None, credential=None, pull='', **kwargs):
        payload = PseudoNamespace(
            name=name or "EE - {}".format(random_title()),
            image=image or "example.invalid/component:tagname",
            organization=organization.id if organization else None,
            credential=credential.id if credential else None,
            pull=pull,
            **kwargs
        )

        return payload
    def payload(self, **kwargs):
        payload = PseudoNamespace(description=kwargs.get('description')
                                  or random_title(10),
                                  scope=kwargs.get('scope', 'write'))

        if kwargs.get('oauth_2_application'):
            payload.application = kwargs['oauth_2_application'].id

        optional_fields = ('expires', )
        update_payload(payload, optional_fields, kwargs)
        return payload
Exemple #8
0
def upload_inventory(ansible_runner, nhosts=10, ini=False):
    """Helper to upload inventory script to target host"""
    # Create an inventory script
    if ini:
        copy_mode = '0644'
        copy_dest = '/tmp/inventory{}.ini'.format(random_title(non_ascii=False))
        copy_content = ini_inventory(nhosts)
    else:
        copy_mode = '0755'
        copy_dest = '/tmp/inventory{}.sh'.format(random_title(non_ascii=False))
        copy_content = '''#!/bin/bash
cat <<EOF
%s
EOF''' % json_inventory(nhosts)

    # Copy script to test system
    contacted = ansible_runner.copy(dest=copy_dest, force=True, mode=copy_mode, content=copy_content)
    for result in contacted.values():
        assert not result.get('failed', False), \
            "Failed to create inventory file: %s" % result
    return copy_dest
Exemple #9
0
    def payload(self, organization, scm_type='git', **kwargs):
        payload = PseudoNamespace(name=kwargs.get('name')
                                  or 'Project - {}'.format(random_title()),
                                  description=kwargs.get('description')
                                  or random_title(10),
                                  scm_type=scm_type,
                                  scm_url=kwargs.get('scm_url')
                                  or config.project_urls.get(scm_type, ''))

        if organization is not None:
            payload.organization = organization.id

        if kwargs.get('credential'):
            payload.credential = kwargs.get('credential').id

        fields = ('scm_branch', 'local_path', 'scm_clean',
                  'scm_delete_on_update', 'scm_update_cache_timeout',
                  'scm_update_on_launch', 'scm_refspec', 'allow_override')
        update_payload(payload, fields, kwargs)

        return payload
Exemple #10
0
    def payload(self, inventory, **kwargs):
        payload = PseudoNamespace(
            name=kwargs.get('name') or 'Host{}'.format(random_title(non_ascii=False)),
            description=kwargs.get('description') or random_title(10),
            inventory=inventory.id,
        )

        optional_fields = ('enabled', 'instance_id')

        update_payload(payload, optional_fields, kwargs)

        variables = kwargs.get('variables', not_provided)

        if variables is None:
            variables = dict(ansible_host='127.0.0.1', ansible_connection='local')

        if variables != not_provided:
            if isinstance(variables, dict):
                variables = json.dumps(variables)
            payload.variables = variables

        return payload
Exemple #11
0
    def payload(self, job_type='run', playbook='ping.yml', **kwargs):
        name = kwargs.get('name') or 'JobTemplate - {}'.format(random_title())
        description = kwargs.get('description') or random_title(10)
        payload = PseudoNamespace(name=name,
                                  description=description,
                                  job_type=job_type)

        optional_fields = ('ask_scm_branch_on_launch',
                           'ask_credential_on_launch',
                           'ask_diff_mode_on_launch',
                           'ask_inventory_on_launch', 'ask_job_type_on_launch',
                           'ask_limit_on_launch', 'ask_skip_tags_on_launch',
                           'ask_tags_on_launch', 'ask_variables_on_launch',
                           'ask_verbosity_on_launch', 'allow_simultaneous',
                           'become_enabled', 'diff_mode', 'force_handlers',
                           'forks', 'host_config_key', 'job_tags', 'limit',
                           'skip_tags', 'start_at_task', 'survey_enabled',
                           'timeout', 'use_fact_cache', 'vault_credential',
                           'verbosity', 'job_slice_count', 'webhook_service',
                           'webhook_credential', 'scm_branch')

        update_payload(payload, optional_fields, kwargs)

        extra_vars = kwargs.get('extra_vars', not_provided)
        if extra_vars != not_provided:
            if isinstance(extra_vars, dict):
                extra_vars = json.dumps(extra_vars)
            payload.update(extra_vars=extra_vars)

        if kwargs.get('project'):
            payload.update(project=kwargs.get('project').id, playbook=playbook)

        payload = set_payload_foreign_key_args(
            payload, ('inventory', 'credential', 'webhook_credential',
                      'execution_environment'), kwargs)

        return payload
Exemple #12
0
    def payload(self,
                inventory,
                source='custom',
                credential=None,
                source_script=None,
                project=None,
                **kwargs):
        payload = PseudoNamespace(
            name=kwargs.get('name')
            or 'InventorySource - {}'.format(random_title()),
            description=kwargs.get('description') or random_title(10),
            inventory=inventory.id,
            source=source,
        )

        if credential:
            payload.credential = credential.id
        if source_script:
            payload.source_script = source_script.id
        if project:
            payload.source_project = project.id

        optional_fields = (
            'source_path',
            'source_vars',
            'timeout',
            'overwrite',
            'overwrite_vars',
            'update_cache_timeout',
            'update_on_launch',
            'update_on_project_update',
            'verbosity',
        )

        update_payload(payload, optional_fields, kwargs)

        return payload
Exemple #13
0
 def payload(self, **kwargs):
     payload = PseudoNamespace(
         username=kwargs.get('username') or 'User-{}'.format(
             random_title(
                 non_ascii=False)),
         password=kwargs.get('password') or config.credentials.default.password,
         is_superuser=kwargs.get(
             'is_superuser',
             False),
         is_system_auditor=kwargs.get(
             'is_system_auditor',
             False),
         first_name=kwargs.get(
             'first_name',
             random_title()),
         last_name=kwargs.get(
             'last_name',
             random_title()),
         email=kwargs.get(
             'email',
             '{}@example.com'.format(random_title(5, non_ascii=False))
         )
     )
     return payload
    def add_schedule(self,
                     name='',
                     description='',
                     enabled=True,
                     rrule=None,
                     **kwargs):
        if rrule is None:
            rrule = "DTSTART:30180101T000000Z RRULE:FREQ=YEARLY;INTERVAL=1"
        payload = dict(name=name
                       or "{0} Schedule {1}".format(self.name, random_title()),
                       description=description or random_title(10),
                       enabled=enabled,
                       rrule=str(rrule))

        update_payload(payload, self.optional_schedule_fields, kwargs)

        schedule = self.related.schedules.post(payload)
        # register schedule in temporary dependency store as means of
        # getting its teardown method to run on cleanup
        if not hasattr(self, '_schedules_store'):
            self._schedules_store = set()
        if schedule not in self._schedules_store:
            self._schedules_store.add(schedule)
        return schedule
Exemple #15
0
    def _generate_script(self):
        script = '\n'.join([
            '#!/usr/bin/env python', '# -*- coding: utf-8 -*-', 'import json',
            'inventory = dict()', 'inventory["{0}"] = dict()',
            'inventory["{0}"]["hosts"] = list()',
            'inventory["{0}"]["hosts"].append("{1}")',
            'inventory["{0}"]["hosts"].append("{2}")',
            'inventory["{0}"]["hosts"].append("{3}")',
            'inventory["{0}"]["hosts"].append("{4}")',
            'inventory["{0}"]["hosts"].append("{5}")',
            'inventory["{0}"]["vars"] = dict(ansible_host="127.0.0.1", ansible_connection="local")',
            'print(json.dumps(inventory))'
        ])
        group_name = re.sub(r"[\']", "",
                            "group_{}".format(random_title(non_ascii=False)))
        host_names = [
            re.sub(r"[\':]", "", "host_{}".format(random_utf8()))
            for _ in range(5)
        ]

        return script.format(group_name, *host_names)
    def payload(self, **kwargs):
        payload = PseudoNamespace(name=kwargs.get('name') or 'WorkflowJobTemplate - {}'.format(random_title()),
                                  description=kwargs.get('description') or random_title(10))

        optional_fields = (
            "allow_simultaneous",
            "ask_variables_on_launch",
            "ask_inventory_on_launch",
            "ask_scm_branch_on_launch",
            "ask_limit_on_launch",
            "limit",
            "scm_branch",
            "survey_enabled",
            "webhook_service",
            "webhook_credential",
        )
        update_payload(payload, optional_fields, kwargs)

        extra_vars = kwargs.get('extra_vars', not_provided)
        if extra_vars != not_provided:
            if isinstance(extra_vars, dict):
                extra_vars = json.dumps(extra_vars)
            payload.update(extra_vars=extra_vars)

        if kwargs.get('organization'):
            payload.organization = kwargs.get('organization').id

        if kwargs.get('inventory'):
            payload.inventory = kwargs.get('inventory').id

        if kwargs.get('webhook_credential'):
            webhook_cred = kwargs.get('webhook_credential')
            if isinstance(webhook_cred, int):
                payload.update(webhook_credential=int(webhook_cred))
            elif hasattr(webhook_cred, 'id'):
                payload.update(webhook_credential=webhook_cred.id)
            else:
                raise AttributeError("Webhook credential must either be integer of pkid or Credential object")

        return payload
Exemple #17
0
 def make_approval_node(self, **kwargs):
     if 'name' not in kwargs:
         kwargs['name'] = 'approval node {}'.format(random_title())
     self.related.create_approval_template.post(kwargs)
     return self.get()
Exemple #18
0
 def payload(self, **kwargs):
     payload = PseudoNamespace(
         name=kwargs.get('name')
         or 'Organization - {}'.format(random_title()),
         description=kwargs.get('description') or random_title(10))
     return payload
Exemple #19
0
    def payload(self,
                organization,
                notification_type='slack',
                messages=not_provided,
                **kwargs):
        payload = PseudoNamespace(name=kwargs.get('name')
                                  or 'NotificationTemplate ({0}) - {1}'.format(
                                      notification_type, random_title()),
                                  description=kwargs.get('description')
                                  or random_title(10),
                                  organization=organization.id,
                                  notification_type=notification_type)
        if messages != not_provided:
            payload['messages'] = messages

        notification_configuration = kwargs.get('notification_configuration',
                                                {})
        payload.notification_configuration = notification_configuration

        if payload.notification_configuration == {}:
            services = config.credentials.notification_services

            if notification_type == 'email':
                fields = ('host', 'username', 'password', 'port', 'use_ssl',
                          'use_tls', 'sender', 'recipients')
                cred = services.email
            elif notification_type == 'irc':
                fields = ('server', 'port', 'use_ssl', 'password', 'nickname',
                          'targets')
                cred = services.irc
            elif notification_type == 'pagerduty':
                fields = ('client_name', 'service_key', 'subdomain', 'token')
                cred = services.pagerduty
            elif notification_type == 'slack':
                fields = ('channels', 'token')
                cred = services.slack
            elif notification_type == 'twilio':
                fields = ('account_sid', 'account_token', 'from_number',
                          'to_numbers')
                cred = services.twilio
            elif notification_type == 'webhook':
                fields = ('url', 'headers')
                cred = services.webhook
            elif notification_type == 'mattermost':
                fields = ('mattermost_url', 'mattermost_username',
                          'mattermost_channel', 'mattermost_icon_url',
                          'mattermost_no_verify_ssl')
                cred = services.mattermost
            elif notification_type == 'grafana':
                fields = ('grafana_url', 'grafana_key')
                cred = services.grafana
            elif notification_type == 'rocketchat':
                fields = ('rocketchat_url', 'rocketchat_no_verify_ssl')
                cred = services.rocketchat
            else:
                raise ValueError(
                    'Unknown notification_type {0}'.format(notification_type))

            for field in fields:
                if field == 'bot_token':
                    payload_field = 'token'
                else:
                    payload_field = field
                value = kwargs.get(field, cred.get(field, not_provided))
                if value != not_provided:
                    payload.notification_configuration[payload_field] = value

        return payload
Exemple #20
0
    def payload(self, job_type='run', playbook='ping.yml', **kwargs):
        name = kwargs.get('name') or 'JobTemplate - {}'.format(random_title())
        description = kwargs.get('description') or random_title(10)
        payload = PseudoNamespace(
            name=name,
            description=description,
            job_type=job_type)

        optional_fields = (
            'ask_scm_branch_on_launch',
            'ask_credential_on_launch',
            'ask_diff_mode_on_launch',
            'ask_inventory_on_launch',
            'ask_job_type_on_launch',
            'ask_limit_on_launch',
            'ask_skip_tags_on_launch',
            'ask_tags_on_launch',
            'ask_variables_on_launch',
            'ask_verbosity_on_launch',
            'allow_simultaneous',
            'become_enabled',
            'diff_mode',
            'force_handlers',
            'forks',
            'host_config_key',
            'job_tags',
            'limit',
            'skip_tags',
            'start_at_task',
            'survey_enabled',
            'timeout',
            'use_fact_cache',
            'vault_credential',
            'verbosity',
            'job_slice_count',
            'webhook_service',
            'webhook_credential',
            'scm_branch')

        update_payload(payload, optional_fields, kwargs)

        extra_vars = kwargs.get('extra_vars', not_provided)
        if extra_vars != not_provided:
            if isinstance(extra_vars, dict):
                extra_vars = json.dumps(extra_vars)
            payload.update(extra_vars=extra_vars)

        if kwargs.get('project'):
            payload.update(project=kwargs.get('project').id, playbook=playbook)
        if kwargs.get('inventory'):
            payload.update(inventory=kwargs.get('inventory').id)
        if kwargs.get('credential'):
            payload.update(credential=kwargs.get('credential').id)
        if kwargs.get('webhook_credential'):
            webhook_cred = kwargs.get('webhook_credential')
            if isinstance(webhook_cred, int):
                payload.update(webhook_credential=int(webhook_cred))
            elif hasattr(webhook_cred, 'id'):
                payload.update(webhook_credential=webhook_cred.id)
            else:
                raise AttributeError("Webhook credential must either be integer of pkid or Credential object")

        return payload
Exemple #21
0
def test_random_titles_are_unicode(non_ascii):
    assert isinstance(utils.random_title(non_ascii=non_ascii), str)
 def copy(self, name=''):
     """Return a copy of current page"""
     payload = {"name": name or "Copy - " + random_title()}
     endpoint = self.json.related['copy']
     page = Page(self.connection, endpoint=endpoint)
     return page.post(payload)