Ejemplo n.º 1
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
Ejemplo n.º 2
0
    def payload(self, workflow_job_template, unified_job_template, **kwargs):
        if not unified_job_template:
            # May pass "None" to explicitly create an approval node
            payload = PseudoNamespace(workflow_job_template=workflow_job_template.id)
        else:
            payload = PseudoNamespace(workflow_job_template=workflow_job_template.id, unified_job_template=unified_job_template.id)

        optional_fields = (
            'diff_mode',
            'extra_data',
            'limit',
            'scm_branch',
            'job_tags',
            'job_type',
            'skip_tags',
            'verbosity',
            'extra_data',
            'identifier',
            'all_parents_must_converge',
        )

        update_payload(payload, optional_fields, kwargs)

        if 'inventory' in kwargs:
            payload['inventory'] = kwargs['inventory'].id

        return payload
Ejemplo n.º 3
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
Ejemplo n.º 4
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', '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)
        return payload
Ejemplo n.º 5
0
    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
Ejemplo n.º 6
0
    def payload(self, organization, notification_type='slack', **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)

        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
            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
Ejemplo n.º 7
0
    def payload(self, **kwargs):
        payload = PseudoNamespace(
            name=kwargs.get('name') or 'OAuth2Application - {}'.format(random_title()),
            description=kwargs.get('description') or random_title(10),
            client_type=kwargs.get('client_type', 'public'),
            authorization_grant_type=kwargs.get('authorization_grant_type', 'password'),
        )
        if kwargs.get('organization'):
            payload.organization = kwargs['organization'].id

        optional_fields = ('redirect_uris', 'skip_authorization')
        update_payload(payload, optional_fields, kwargs)
        return payload
Ejemplo n.º 8
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)

        for fk_field in ('execution_environment', '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
Ejemplo n.º 9
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', 'kind', 'variables')

        update_payload(payload, optional_fields, kwargs)

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

        return payload
Ejemplo n.º 10
0
 def payload(self, organization, **kwargs):
     payload = PseudoNamespace(name=kwargs.get('name')
                               or 'Label - {}'.format(random_title()),
                               description=kwargs.get('description')
                               or random_title(10),
                               organization=organization.id)
     return payload
Ejemplo n.º 11
0
    def payload(self, inventory, credential=None, **kwargs):
        payload = PseudoNamespace(
            name=kwargs.get('name')
            or 'Group{}'.format(random_title(non_ascii=False)),
            description=kwargs.get('description') or random_title(10),
            inventory=inventory.id)

        if credential:
            payload.credential = credential.id

        update_payload(payload, ('variables', ), kwargs)

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

        return payload
Ejemplo n.º 12
0
def set_config_cred_to_desired(config, location):
    split = location.split('.')
    config_ref = config.credentials
    for _location in split[:-1]:
        setattr(config_ref, _location, PseudoNamespace())
        config_ref = config_ref[_location]
    setattr(config_ref, split[-1], 'desired')
Ejemplo n.º 13
0
 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')
     update_payload(payload, fields, kwargs)
     return payload
Ejemplo n.º 14
0
 def payload(self, organization, **kwargs):
     payload = PseudoNamespace(
         name=kwargs.get('name')
         or 'Inventory Script - {}'.format(random_title()),
         description=kwargs.get('description') or random_title(10),
         organization=organization.id,
         script=kwargs.get('script') or self._generate_script())
     return payload
Ejemplo n.º 15
0
    def payload(self, inventory, credential, module_name='ping', **kwargs):
        payload = PseudoNamespace(inventory=inventory.id,
                                  credential=credential.id,
                                  module_name=module_name)

        optional_fields = ('diff_mode', 'extra_vars', 'module_args',
                           'job_type', 'limit', 'forks', 'verbosity')
        return update_payload(payload, optional_fields, kwargs)
Ejemplo n.º 16
0
    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",
                           "survey_enabled")
        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('ask_inventory_on_launch'):
            payload.ask_inventory_on_launch = kwargs.get(
                'ask_inventory_on_launch')

        return payload
Ejemplo n.º 17
0
 def payload(self, kind='cloud', **kwargs):
     payload = PseudoNamespace(
         name=kwargs.get('name')
         or 'CredentialType - {}'.format(random_title()),
         description=kwargs.get('description') or random_title(10),
         kind=kind)
     fields = ('inputs', 'injectors')
     update_payload(payload, fields, kwargs)
     return payload
Ejemplo n.º 18
0
    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
Ejemplo n.º 19
0
def kind_and_config_cred_from_credential_type(credential_type):
    kind = ''

    if not credential_type.managed_by_tower:
        return kind, PseudoNamespace()
    try:
        if credential_type.kind == 'net':
            config_cred = config.credentials.network
            kind = 'net'
        elif credential_type.kind == 'cloud':
            kind = credential_type_name_to_config_kind_map[
                credential_type.name.lower()]
            config_kind = kind if kind != 'azure_rm' else 'azure'
            config_cred = config.credentials.cloud[config_kind]
        else:
            kind = credential_type.kind.lower()
            config_cred = config.credentials[kind]
        return kind, config_cred
    except (KeyError, AttributeError):
        return kind, PseudoNamespace()
Ejemplo n.º 20
0
    def payload(self, name='', image=None, organization=None, credential=None, pull='', **kwargs):
        payload = PseudoNamespace(
            name=name or "EE - {}".format(random_title()),
            image=image or random_title(10),
            organization=organization.id if organization else None,
            credential=credential.id if credential else None,
            pull=pull,
            **kwargs
        )

        return payload
Ejemplo n.º 21
0
    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
Ejemplo n.º 22
0
    def payload(self, **kwargs):
        payload = PseudoNamespace(
            name=kwargs.get('name')
            or 'Organization - {}'.format(random_title()),
            description=kwargs.get('description') or random_title(10))

        payload = set_payload_foreign_key_args(payload,
                                               ('default_environment', ),
                                               kwargs)

        return payload
Ejemplo n.º 23
0
def objectify_response_json(response):
    """return a PseudoNamespace() from requests.Response.json()."""
    try:
        json = response.json()
    except ValueError:
        json = dict()

    # PseudoNamespace arg must be a dict, and json can be an array.
    # TODO: Assess if list elements should be PseudoNamespace
    if isinstance(json, dict):
        return PseudoNamespace(json)
    return json
Ejemplo n.º 24
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
Ejemplo n.º 25
0
    def payload(self, workflow_job_template, unified_job_template, **kwargs):
        payload = PseudoNamespace(
            workflow_job_template=workflow_job_template.id,
            unified_job_template=unified_job_template.id)

        optional_fields = ('diff_mode', 'extra_data', 'limit', 'job_tags',
                           'job_type', 'skip_tags', 'verbosity', 'extra_data')

        update_payload(payload, optional_fields, kwargs)

        if 'inventory' in kwargs:
            payload['inventory'] = kwargs['inventory'].id

        return payload
Ejemplo n.º 26
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
Ejemplo n.º 27
0
def config_cred_from_kind(kind):
    try:
        if kind == 'net':
            config_cred = config.credentials.network
        elif kind in cloud_types:
            if kind == 'azure_rm':
                config_cred = config.credentials.cloud.azure
            else:
                config_cred = config.credentials.cloud[kind]
        else:
            config_cred = config.credentials[kind]
        return config_cred
    except (KeyError, AttributeError):
        return PseudoNamespace()
Ejemplo n.º 28
0
    def payload(self,
                credential_type,
                user=None,
                team=None,
                organization=None,
                inputs=None,
                **kwargs):
        if not any((user, team, organization)):
            raise TypeError(
                '{0.__class__.__name__} requires user, team, and/or organization instances.'
                .format(self))

        if inputs is None:
            inputs = {}

        payload = PseudoNamespace(
            name=kwargs.get('name')
            or 'Credential - {}'.format(random_title()),
            description=kwargs.get('description') or random_title(10),
            credential_type=credential_type.id,
            inputs=inputs,
        )
        if user:
            payload.user = user.id
        if team:
            payload.team = team.id
        if organization:
            payload.organization = organization.id

        kind, config_cred = kind_and_config_cred_from_credential_type(
            credential_type)

        for field in credential_input_fields:
            field, value = get_payload_field_and_value_from_kwargs_or_config_cred(
                field, kind, inputs or kwargs, config_cred)
            if value != not_provided:
                payload.inputs[field] = value

        if kind == 'net':
            payload.inputs.authorize = inputs.get(
                'authorize', bool(inputs.get('authorize_password')))

        if kind in ('ssh', 'net') and 'ssh_key_data' not in payload.inputs:
            payload.inputs.ssh_key_data = inputs.get('ssh_key_data',
                                                     generate_private_key())

        return payload
Ejemplo n.º 29
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
Ejemplo n.º 30
0
 def variables(self):
     return PseudoNamespace(
         yaml.load(self.json.variables, Loader=yaml.FullLoader))