def test_positive_run_job_effective_user_by_ip(self, fixture_vmsetup):
        """Run default job template as effective user on a host by ip

        :id: 0cd75cab-f699-47e6-94d3-4477d2a94bb7

        :BZ: 1451675

        :expectedresults: Verify the job was successfully run under the
            effective user identity on host

        :parametrized: yes
        """
        client = fixture_vmsetup
        # create a user on client via remote job
        username = gen_string('alpha')
        filename = gen_string('alpha')
        make_user_job = make_job_invocation({
            'job-template':
            'Run Command - SSH Default',
            'inputs':
            f"command='useradd -m {username}'",
            'search-query':
            f"name ~ {client.hostname}",
        })
        result = JobInvocation.info({'id': make_user_job['id']})
        try:
            assert result['success'] == '1'
        except AssertionError:
            result = 'host output: {}'.format(' '.join(
                JobInvocation.get_output({
                    'id': make_user_job['id'],
                    'host': client.hostname
                })))
            raise AssertionError(result)
        # create a file as new user
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - SSH Default',
            'inputs':
            f"command='touch /home/{username}/{filename}'",
            'search-query':
            f"name ~ {client.hostname}",
            'effective-user':
            f'{username}',
        })
        result = JobInvocation.info({'id': invocation_command['id']})
        try:
            assert result['success'] == '1'
        except AssertionError:
            result = 'host output: {}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command['id'],
                    'host': client.hostname
                })))
            raise AssertionError(result)
        # check the file owner
        result = client.execute(
            f'''stat -c '%U' /home/{username}/{filename}''', )
        # assert the file is owned by the effective user
        assert username == result.stdout.strip('\n')
    def test_positive_run_scheduled_job_template_by_ip(self, fixture_vmsetup,
                                                       fixture_org):
        """Schedule a job to be ran against a host

        :id: 0407e3de-ef59-4706-ae0d-b81172b81e5c

        :expectedresults: Verify the job was successfully ran after the
            designated time

        :parametrized: yes
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        system_current_time = ssh.command(
            'date --utc +"%b %d %Y %I:%M%p"').stdout[0]
        current_time_object = datetime.strptime(system_current_time,
                                                '%b %d %Y %I:%M%p')
        plan_time = (current_time_object +
                     timedelta(seconds=30)).strftime("%Y-%m-%d %H:%M")
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - SSH Default',
            'inputs':
            'command="ls"',
            'start-at':
            plan_time,
            'search-query':
            "name ~ {0}".format(self.client.hostname),
        })
        # Wait until the job runs
        pending_state = '1'
        while pending_state != '0':
            invocation_info = JobInvocation.info(
                {'id': invocation_command['id']})
            pending_state = invocation_info['pending']
            sleep(30)
        invocation_info = JobInvocation.info({'id': invocation_command['id']})
        try:
            assert invocation_info['success'] == '1'
        except AssertionError:
            result = 'host output: {0}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command['id'],
                    'host': self.client.hostname
                })))
            raise AssertionError(result)
Exemple #3
0
    def test_positive_run_recurring_job_with_max_iterations_by_ip(
            self, rex_contenthost):
        """Run default job template multiple times with max iteration by ip

        :id: 0a3d1627-95d9-42ab-9478-a908f2a7c509

        :expectedresults: Verify the job was run not more than the specified
            number of times.

        :parametrized: yes
        """
        client = rex_contenthost
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': 'command="ls"',
            'search-query': f"name ~ {client.hostname}",
            'cron-line': '* * * * *',  # every minute
            'max-iteration': 2,  # just two runs
        })

        result = JobInvocation.info({'id': invocation_command['id']})
        try:
            assert result['status'] == 'queued'
        except AssertionError:
            result = 'host output: {}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command['id'],
                    'host': client.hostname
                })))
            raise AssertionError(result)

        sleep(150)
        rec_logic = RecurringLogic.info({'id': result['recurring-logic-id']})
        assert rec_logic['state'] == 'finished'
        assert rec_logic['iteration'] == '2'
    def test_positive_run_reccuring_job(self, fixture_vmsetup, fixture_org):
        """Tests Ansible REX reccuring job runs successfully multiple times

        :id: 49b0d31d-58f9-47f1-aa5d-561a1dcb0d66

        :Steps:

            0. Create a VM and register to SAT and prepare for REX (ssh key)

            1. Run recurring Ansible Command job for the host

            2. Check the multiple job results at the host

        :expectedresults: multiple asserts along the code

        :caseautomation: automated

        :CaseLevel: System
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        # set connecting to host by ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - Ansible Default',
            'inputs': 'command="ls"',
            'search-query': "name ~ {0}".format(self.client.hostname),
            'cron-line': '* * * * *',  # every minute
            'max-iteration': 2,  # just two runs
        })
        JobInvocation.get_output({
            'id': invocation_command[u'id'],
            'host': self.client.hostname
        })
        try:
            assert invocation_command['status'] == u'queued'
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
        # Wait until the job runs
        pending_state = u'1'
        for _ in range(5):
            if pending_state != u'0':
                invocation_info = JobInvocation.info({
                    'id': invocation_command[u'id']})
                pending_state = invocation_info[u'pending']
                sleep(30)
        rec_logic = RecurringLogic.info({
            'id': invocation_command['recurring-logic-id']})
        assert rec_logic['state'] == u'finished'
        assert rec_logic['iteration'] == u'2'
    def test_positive_run_scheduled_job_template(self):
        """Schedule a job to be ran against a host

        @id: 1953517b-6908-40aa-858b-747629d2f374

        @Assert: Verify the job was successfully ran after the designated time
        """
        system_current_time = ssh.command('date +"%b %d %Y %I:%M%p"').stdout[0]
        current_time_object = datetime.strptime(system_current_time,
                                                '%b %d %Y %I:%M%p')
        plan_time = (current_time_object +
                     timedelta(seconds=30)).strftime("%Y-%m-%d %H:%M")
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - SSH Default',
            'inputs':
            'command="ls"',
            'start-at':
            plan_time,
            'search-query':
            "name ~ {0}".format(self.client.hostname),
        })
        for _ in range(5):
            try:
                invocation_info = JobInvocation.info(
                    {'id': invocation_command[u'id']})
                self.assertEqual(invocation_info[u'success'], u'1')
            except AssertionError:
                sleep(30)
    def test_positive_run_default_job_template_multiple_hosts_by_ip(
            self, fixture_vmsetup, module_org):
        """Run default job template against multiple hosts by ip

        :id: 694a21d3-243b-4296-8bd0-4bad9663af15

        :expectedresults: Verify the job was successfully ran against all hosts

        :parametrized: yes
        """
        clients = fixture_vmsetup
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - SSH Default',
            'inputs':
            'command="ls"',
            'search-query':
            f'name ~ {clients[0].hostname} or name ~ {clients[1].hostname}',
        })
        # collect output messages from clients
        output_msgs = []
        for vm in clients:
            output_msgs.append('host output from {}: {}'.format(
                vm.hostname,
                ' '.join(
                    JobInvocation.get_output({
                        'id': invocation_command['id'],
                        'host': vm.hostname
                    })),
            ))
        result = JobInvocation.info({'id': invocation_command['id']})
        assert result['success'] == '2', output_msgs
    def test_positive_run_scheduled_job_template_by_ip(self, fixture_vmsetup, fixture_org):
        """Schedule a job to be ran against a host

        :id: 0407e3de-ef59-4706-ae0d-b81172b81e5c

        :expectedresults: Verify the job was successfully ran after the
            designated time
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        system_current_time = ssh.command('date --utc +"%b %d %Y %I:%M%p"').stdout[0]
        current_time_object = datetime.strptime(
            system_current_time, '%b %d %Y %I:%M%p')
        plan_time = (current_time_object + timedelta(seconds=30)).strftime(
            "%Y-%m-%d %H:%M")
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': 'command="ls"',
            'start-at': plan_time,
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        # Wait until the job runs
        pending_state = u'1'
        while pending_state != u'0':
            invocation_info = JobInvocation.info({
                'id': invocation_command[u'id']})
            pending_state = invocation_info[u'pending']
            sleep(30)
        invocation_info = JobInvocation.info({
            'id': invocation_command[u'id']})
        try:
            assert invocation_info['success'] == u'1'
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
    def test_positive_install_multiple_packages_with_a_job_by_ip(
            self, fixture_vmsetup, module_org):
        """Run job to install several packages on host by ip

        :id: 8b73033f-83c9-4024-83c3-5e442a79d320

        :expectedresults: Verify the packages were successfully installed
            on host

        :parametrized: yes
        """
        self.org = module_org
        client = fixture_vmsetup
        packages = ["cow", "dog", "lion"]
        # Create a custom repo
        repo = entities.Repository(
            content_type='yum',
            product=entities.Product(organization=self.org).create(),
            url=settings.repos.yum_0.url,
        ).create()
        repo.sync()
        prod = repo.product.read()
        subs = entities.Subscription(organization=self.org).search(
            query={'search': f'name={prod.name}'})
        assert len(subs) > 0, 'No subscriptions matching the product returned'

        ak = entities.ActivationKey(
            organization=self.org,
            content_view=self.org.default_content_view,
            environment=self.org.library,
        ).create()
        ak.add_subscriptions(data={'subscriptions': [{'id': subs[0].id}]})
        client.register_contenthost(org=self.org.label, activation_key=ak.name)

        invocation_command = make_job_invocation({
            'job-template':
            'Install Package - Katello SSH Default',
            'inputs':
            'package={} {} {}'.format(*packages),
            'search-query':
            f'name ~ {client.hostname}',
        })
        result = JobInvocation.info({'id': invocation_command['id']})
        try:
            assert result['success'] == '1'
        except AssertionError:
            result = 'host output: {}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command['id'],
                    'host': client.hostname
                })))
            raise AssertionError(result)
        result = client.run(f'rpm -q {" ".join(packages)}')
        assert result.status == 0
    def test_positive_run_scheduled_job_template(self):
        """Schedule a job to be ran against a host

        :id: 1953517b-6908-40aa-858b-747629d2f374

        :expectedresults: Verify the job was successfully ran after the
            designated time
        """
        system_current_time = ssh.command('date +"%b %d %Y %I:%M%p"').stdout[0]
        current_time_object = datetime.strptime(system_current_time,
                                                '%b %d %Y %I:%M%p')
        plan_time = (current_time_object +
                     timedelta(seconds=30)).strftime("%Y-%m-%d %H:%M")
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - SSH Default',
            'inputs':
            'command="ls"',
            'start-at':
            plan_time,
            'search-query':
            "name ~ {0}".format(self.client.hostname),
        })
        # Wait until the job runs
        pending_state = u'1'
        while pending_state != u'0':
            invocation_info = JobInvocation.info(
                {'id': invocation_command[u'id']})
            pending_state = invocation_info[u'pending']
            sleep(30)
        invocation_info = JobInvocation.info({'id': invocation_command[u'id']})
        try:
            self.assertEqual(invocation_info['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname
                })))
            raise AssertionError(result)
    def test_positive_run_scheduled_job_template(self):
        """Schedule a job to be ran against a host

        :id: 1953517b-6908-40aa-858b-747629d2f374

        :expectedresults: Verify the job was successfully ran after the
            designated time
        """
        system_current_time = ssh.command('date +"%b %d %Y %I:%M%p"').stdout[0]
        current_time_object = datetime.strptime(
            system_current_time, '%b %d %Y %I:%M%p')
        plan_time = (current_time_object + timedelta(seconds=30)).strftime(
            "%Y-%m-%d %H:%M")
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - SSH Default',
            'inputs': 'command="ls"',
            'start-at': plan_time,
            'search-query': "name ~ {0}".format(self.client.hostname),
        })
        # Wait until the job runs
        pending_state = u'1'
        while pending_state != u'0':
            invocation_info = JobInvocation.info({
                'id': invocation_command[u'id']})
            pending_state = invocation_info[u'pending']
            sleep(30)
        invocation_info = JobInvocation.info({
            'id': invocation_command[u'id']})
        try:
            self.assertEqual(invocation_info['success'], u'1')
        except AssertionError:
            result = 'host output: {0}'.format(
                ' '.join(JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname})
                    )
                )
            raise AssertionError(result)
Exemple #11
0
    def test_positive_install_ansible_collection(self, fixture_sca_vmsetup,
                                                 module_gt_manifest_org):
        """Test whether Ansible collection can be installed via REX

        :Steps:

            1. Upload a manifest.
            2. Enable and sync Ansible repository.
            3. Register content host to Satellite.
            4. Enable Ansible repo on content host.
            5. Install ansible package.
            6. Run REX job to install Ansible collection on content host.

        :id: ad25aee5-4ea3-4743-a301-1c6271856f79

        :CaseComponent: Ansible

        :Assignee: dsynk
        """

        # Configure repository to prepare for installing ansible on host
        RepositorySet.enable({
            'basearch': 'x86_64',
            'name': REPOSET['rhae2'],
            'organization-id': module_gt_manifest_org.id,
            'product': PRDS['rhae'],
            'releasever': '7Server',
        })
        Repository.synchronize({
            'name': REPOS['rhae2']['name'],
            'organization-id': module_gt_manifest_org.id,
            'product': PRDS['rhae'],
        })
        client = fixture_sca_vmsetup
        client.execute(
            f'subscription-manager repos --enable {REPOS["rhae2"]["id"]}')
        client.execute('yum -y install ansible')
        collection_job = make_job_invocation({
            'job-template':
            'Ansible Collection - Install from Galaxy',
            'inputs':
            'ansible_collections_list="oasis_roles.system"',
            'search-query':
            f'name ~ {client.hostname}',
        })
        result = JobInvocation.info({'id': collection_job['id']})
        assert result['success'] == '1'
        collection_path = str(
            client.execute('ls /etc/ansible/collections/ansible_collections'))
        assert 'oasis' in collection_path
    def test_positive_use_alternate_directory(self, fixture_vmsetup,
                                              module_org, default_sat):
        """Use alternate working directory on client to execute rex jobs

        :id: a0181f18-d3dc-4bd9-a2a6-430c2a49809e

        :expectedresults: Verify the job was successfully ran against the host

        :customerscenario: true

        :parametrized: yes
        """
        client = fixture_vmsetup
        testdir = gen_string('alpha')
        result = client.run(f'mkdir /{testdir}')
        assert result.status == 0
        result = client.run(f'chcon --reference=/var /{testdir}')
        assert result.status == 0
        result = default_sat.execute(
            f"sed -i r's/^:remote_working_dir:.*/:remote_working_dir: \\/{testdir}/' \
            /etc/foreman-proxy/settings.d/remote_execution_ssh.yml", )
        assert result.status == 0
        result = default_sat.execute('systemctl restart foreman-proxy')
        assert result.status == 0

        command = f'echo {gen_string("alpha")}'
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - SSH Default',
            'inputs':
            f'command={command}',
            'search-query':
            f"name ~ {client.hostname}",
        })
        result = JobInvocation.info({'id': invocation_command['id']})
        try:
            assert result['success'] == '1'
        except AssertionError:
            output = ' '.join(
                JobInvocation.get_output({
                    'id': invocation_command['id'],
                    'host': client.hostname
                }))
            result = f'host output: {output}'
            raise AssertionError(result)

        task = Task.list_tasks({"search": command})[0]
        search = Task.list_tasks({"search": f'id={task["id"]}'})
        assert search[0]["action"] == task["action"]
    def test_positive_run_concurrent_jobs(self, fixture_vmsetup, module_org):
        """Tests Ansible REX concurent jobs without batch trigger

        :id: ad0f108c-03f2-49c7-8732-b1056570567b

        :Steps:

            0. Create 2 hosts, disable foreman_tasks_proxy_batch_trigger

            1. Run Ansible Command job with concurrency-setting

        :expectedresults: multiple asserts along the code

        :CaseAutomation: Automated

        :customerscenario: true

        :CaseLevel: System

        :BZ: 1817320

        :parametrized: yes
        """
        param_name = 'foreman_tasks_proxy_batch_trigger'
        GlobalParameter().set({'name': param_name, 'value': 'false'})
        clients = fixture_vmsetup
        output_msgs = []
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - Ansible Default',
            'inputs': 'command="ls"',
            'search-query':
            f'name ~ {clients[0].hostname} or name ~ {clients[1].hostname}',
            'concurrency-level': 2,
        })
        for vm in clients:
            output_msgs.append('host output from {}: {}'.format(
                vm.hostname,
                ' '.join(
                    JobInvocation.get_output({
                        'id': invocation_command['id'],
                        'host': vm.hostname
                    })),
            ))
        result = JobInvocation.info({'id': invocation_command['id']})
        assert result['success'] == '2', output_msgs
        GlobalParameter().delete({'name': param_name})
        assert len(GlobalParameter().list({'search': param_name})) == 0
    def test_positive_run_reccuring_job(self, fixture_vmsetup):
        """Tests Ansible REX reccuring job runs successfully multiple times

        :id: 49b0d31d-58f9-47f1-aa5d-561a1dcb0d66

        :Steps:

            0. Create a VM and register to SAT and prepare for REX (ssh key)

            1. Run recurring Ansible Command job for the host

            2. Check the multiple job results at the host

        :expectedresults: multiple asserts along the code

        :CaseAutomation: Automated

        :CaseLevel: System

        :parametrized: yes
        """
        client = fixture_vmsetup
        invocation_command = make_job_invocation({
            'job-template': 'Run Command - Ansible Default',
            'inputs': 'command="ls"',
            'search-query': f"name ~ {client.hostname}",
            'cron-line': '* * * * *',  # every minute
            'max-iteration': 2,  # just two runs
        })
        result = JobInvocation.info({'id': invocation_command['id']})
        try:
            assert result['status'] == 'queued'
        except AssertionError:
            result = 'host output: {}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command['id'],
                    'host': client.hostname
                })))
            raise AssertionError(result)
        sleep(150)
        rec_logic = RecurringLogic.info({'id': result['recurring-logic-id']})
        assert rec_logic['state'] == 'finished'
        assert rec_logic['iteration'] == '2'
Exemple #15
0
    def test_positive_run_custom_job_template_by_ip(self, rex_contenthost,
                                                    module_org, default_sat):
        """Run custom template on host connected by ip

        :id: 9740eb1d-59f5-42b2-b3ab-659ca0202c74

        :expectedresults: Verify the job was successfully ran against the host

        :bz: 1872688, 1811166

        :customerscenario: true

        :CaseImportance: Critical

        :parametrized: yes
        """
        self.org = module_org
        client = rex_contenthost
        template_file = 'template_file.txt'
        default_sat.execute(f'echo "echo Enforcing" > {template_file}')
        template_name = gen_string('alpha', 7)
        make_job_template({
            'organizations': self.org.name,
            'name': template_name,
            'file': template_file
        })
        invocation_command = make_job_invocation({
            'job-template':
            template_name,
            'search-query':
            f'name ~ {client.hostname}'
        })
        result = JobInvocation.info({'id': invocation_command['id']})
        try:
            assert result['success'] == '1'
        except AssertionError:
            result = 'host output: {}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command['id'],
                    'host': client.hostname
                })))
            raise AssertionError(result)
    def test_positive_run_default_job_template_by_ip(self, fixture_vmsetup):
        """Run default template on host connected by ip and list task

        :id: 811c7747-bec6-4a2d-8e5c-b5045d3fbc0d

        :expectedresults: Verify the job was successfully ran against the host
            and task can be listed by name and ID

        :BZ: 1647582

        :customerscenario: true

        :parametrized: yes
        """
        client = fixture_vmsetup
        command = "echo {}".format(gen_string('alpha'))
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - SSH Default',
            'inputs':
            f'command={command}',
            'search-query':
            f"name ~ {client.hostname}",
        })
        result = JobInvocation.info({'id': invocation_command['id']})
        try:
            assert result['success'] == '1'
        except AssertionError:
            result = 'host output: {}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command['id'],
                    'host': client.hostname
                })))
            raise AssertionError(result)

        task = Task.list_tasks({"search": command})[0]
        search = Task.list_tasks({"search": 'id={}'.format(task["id"])})
        assert search[0]["action"] == task["action"]
    def test_positive_run_scheduled_job_template(self):
        """Schedule a job to be ran against a host

        @id: 1953517b-6908-40aa-858b-747629d2f374

        @Assert: Verify the job was successfully ran after the designated time
        """
        system_current_time = ssh.command('date +"%b %d %Y %I:%M%p"').stdout[0]
        current_time_object = datetime.strptime(system_current_time, "%b %d %Y %I:%M%p")
        plan_time = (current_time_object + timedelta(seconds=30)).strftime("%Y-%m-%d %H:%M")
        invocation_command = make_job_invocation(
            {
                "job-template": "Run Command - SSH Default",
                "inputs": 'command="ls"',
                "start-at": plan_time,
                "search-query": "name ~ {0}".format(self.client.hostname),
            }
        )
        for _ in range(5):
            try:
                invocation_info = JobInvocation.info({"id": invocation_command[u"id"]})
                self.assertEqual(invocation_info[u"success"], u"1")
            except AssertionError:
                sleep(30)
Exemple #18
0
def test_positive_oscap_run_via_ansible(module_org, default_proxy,
                                        content_view, lifecycle_env, distro):
    """End-to-End Oscap run via ansible

    :id: c7ea56eb-6cf1-4e79-8d6a-fb872d1bb804

    :parametrized: yes

    :setup: scap content, scap policy, host group

    :steps:

        1. Create a valid scap content
        2. Import Ansible role theforeman.foreman_scap_client
        3. Import Ansible Variables needed for the role
        4. Create a scap policy with anisble as deploy option
        5. Associate the policy with a hostgroup
        6. Provision a host using the hostgroup
        7. Configure REX and associate the Ansible role to created host
        8. Play roles for the host

    :expectedresults: REX job should be success and ARF report should be sent to satellite

    :BZ: 1716307

    :CaseImportance: Critical
    """
    if distro == 'rhel7':
        rhel_repo = settings.repos.rhel7_repo
        profile = OSCAP_PROFILE['security7']
    else:
        rhel_repo = settings.repos.rhel8_repo
        profile = OSCAP_PROFILE['ospp8']
    content = OSCAP_DEFAULT_CONTENT[f'{distro}_content']
    hgrp_name = gen_string('alpha')
    policy_name = gen_string('alpha')
    # Creates host_group for rhel7
    make_hostgroup({
        'content-source-id': default_proxy,
        'name': hgrp_name,
        'organizations': module_org.name,
    })
    # Creates oscap_policy.
    scap_id, scap_profile_id = fetch_scap_and_profile_id(content, profile)
    Ansible.roles_import({'proxy-id': default_proxy})
    Ansible.variables_import({'proxy-id': default_proxy})
    role_id = Ansible.roles_list({'search':
                                  'foreman_scap_client'})[0].get('id')
    make_scap_policy({
        'scap-content-id': scap_id,
        'hostgroups': hgrp_name,
        'deploy-by': 'ansible',
        'name': policy_name,
        'period': OSCAP_PERIOD['weekly'].lower(),
        'scap-content-profile-id': scap_profile_id,
        'weekday': OSCAP_WEEKDAY['friday'].lower(),
        'organizations': module_org.name,
    })
    with VMBroker(nick=distro, host_classes={'host': ContentHost}) as vm:
        host_name, _, host_domain = vm.hostname.partition('.')
        vm.install_katello_ca()
        vm.register_contenthost(module_org.name, ak_name[distro])
        assert vm.subscribed
        Host.set_parameter({
            'host': vm.hostname.lower(),
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        vm.configure_rhel_repo(rhel_repo)
        add_remote_execution_ssh_key(vm.ip_addr)
        Host.update({
            'name': vm.hostname.lower(),
            'lifecycle-environment': lifecycle_env.name,
            'content-view': content_view.name,
            'hostgroup': hgrp_name,
            'openscap-proxy-id': default_proxy,
            'organization': module_org.name,
            'ansible-role-ids': role_id,
        })
        job_id = Host.ansible_roles_play({'name':
                                          vm.hostname.lower()})[0].get('id')
        wait_for_tasks(
            f'resource_type = JobInvocation and resource_id = {job_id} and action ~ "hosts job"'
        )
        try:
            result = JobInvocation.info({'id': job_id})['success']
            assert result == '1'
        except AssertionError:
            output = ' '.join(
                JobInvocation.get_output({
                    'id': job_id,
                    'host': vm.hostname
                }))
            result = f'host output: {output}'
            raise AssertionError(result)
        result = vm.run(
            'cat /etc/foreman_scap_client/config.yaml | grep profile')
        assert result.status == 0
        # Runs the actual oscap scan on the vm/clients and
        # uploads report to Internal Capsule.
        vm.execute_foreman_scap_client()
        # Assert whether oscap reports are uploaded to
        # Satellite6.
        result = Arfreport.list({'search': f'host={vm.hostname.lower()}'})
        assert result is not None
Exemple #19
0
    def test_positive_rex_against_infra_hosts(
        self,
        rex_contenthost,
        class_rexmanager_user,
        class_rexinfra_user,
        default_sat,
        infra_host,
        module_org,
    ):
        """
        Tests related to remote execution against Satellite host

        :id: 36942e30-b885-4ba3-933b-7f59888935c9

        :steps:
            1. Run rex job against Satellite and Capsule as admin
            2. Run rex job against Satellite and Capsule as a REX admin
            3. Run rex job against Satellite and Capsule as a custom user with
               required permission

        :expectedresults: Only users with execute_jobs_on_infrastructure_host perm
            can run rex against Satellite

        :caseautomation: Automated

        :parametrized: yes

        """
        client = rex_contenthost
        infra_host.add_rex_key(satellite=default_sat)
        Host.update({
            'name': infra_host.hostname,
            'new-organization-id': module_org.id
        })

        # run job as admin
        command = f"echo {gen_string('alpha')}"
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - SSH Default',
            'inputs':
            f'command={command}',
            'search-query':
            f"name ^ ({client.hostname}, {infra_host.hostname})",
        })
        output_msgs = []
        hostnames = [client.hostname, infra_host.hostname]
        for hostname in hostnames:
            inv_output = ' '.join(
                JobInvocation.get_output({
                    'id': invocation_command['id'],
                    'host': hostname
                }))
            output_msgs.append(f"host output from {hostname}: { inv_output }")
        result = JobInvocation.info({'id': invocation_command['id']})
        assert result['success'] == '2', output_msgs

        # run job as regular rex user on all hosts
        invocation_command = make_job_invocation_with_credentials(
            {
                'job-template':
                'Run Command - SSH Default',
                'inputs':
                f'command={command}',
                'search-query':
                f"name ^ ({client.hostname}, {infra_host.hostname})",
            },
            class_rexmanager_user,
        )

        result = JobInvocation.info({'id': invocation_command['id']})
        assert result['success'] == '1'

        # run job as regular rex user just on infra hosts
        invocation_command = make_job_invocation_with_credentials(
            {
                'job-template': 'Run Command - SSH Default',
                'inputs': f'command={command}',
                'search-query': f"name ^ ({infra_host.hostname})",
            },
            class_rexmanager_user,
        )
        result = JobInvocation.info({'id': invocation_command['id']})
        assert result['success'] == '0'

        # run job as rex user on Satellite
        invocation_command = make_job_invocation_with_credentials(
            {
                'job-template': 'Run Command - SSH Default',
                'inputs': f'command={command}',
                'search-query': f"name ^ ({infra_host.hostname})",
            },
            class_rexinfra_user,
        )
        result = JobInvocation.info({'id': invocation_command['id']})
        assert result['success'] == '1'
    def test_positive_run_effective_user_job(self, fixture_vmsetup):
        """Tests Ansible REX job having effective user runs successfully

        :id: a5fa20d8-c2bd-4bbf-a6dc-bf307b59dd8c

        :Steps:

            0. Create a VM and register to SAT and prepare for REX (ssh key)

            1. Run Ansible Command job for the host to create a user

            2. Run Ansible Command job using effective user

            3. Check the job result at the host is done under that user

        :expectedresults: multiple asserts along the code

        :CaseAutomation: Automated

        :CaseLevel: System

        :parametrized: yes
        """
        client = fixture_vmsetup
        # create a user on client via remote job
        username = gen_string('alpha')
        filename = gen_string('alpha')
        make_user_job = make_job_invocation({
            'job-template':
            'Run Command - Ansible Default',
            'inputs':
            f"command='useradd -m {username}'",
            'search-query':
            f"name ~ {client.hostname}",
        })
        result = JobInvocation.info({'id': make_user_job['id']})
        try:
            assert result['success'] == '1'
        except AssertionError:
            result = 'host output: {}'.format(' '.join(
                JobInvocation.get_output({
                    'id': make_user_job['id'],
                    'host': client.hostname
                })))
            raise AssertionError(result)
        # create a file as new user
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - Ansible Default',
            'inputs':
            f"command='touch /home/{username}/{filename}'",
            'search-query':
            f"name ~ {client.hostname}",
            'effective-user':
            f'{username}',
        })
        result = JobInvocation.info({'id': invocation_command['id']})
        try:
            assert result['success'] == '1'
        except AssertionError:
            result = 'host output: {}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command['id'],
                    'host': client.hostname
                })))
            raise AssertionError(result)
        # check the file owner
        result = client.execute(
            f'''stat -c '%U' /home/{username}/{filename}''', )
        # assert the file is owned by the effective user
        assert username == result.stdout.strip('\n'), "file ownership mismatch"
    def test_positive_run_packages_and_services_job(self, fixture_vmsetup,
                                                    module_org):
        """Tests Ansible REX job can install packages and start services

        :id: 47ed82fb-77ca-43d6-a52e-f62bae5d3a42

        :Steps:

            0. Create a VM and register to SAT and prepare for REX (ssh key)

            1. Run Ansible Package job for the host to install a package

            2. Check the package is present at the host

            3. Run Ansible Service job for the host to start a service

            4. Check the service is started on the host

        :expectedresults: multiple asserts along the code

        :CaseAutomation: Automated

        :CaseLevel: System

        :bz: 1872688, 1811166

        :customerscenario: true

        :parametrized: yes
        """
        self.org = module_org
        client = fixture_vmsetup
        packages = ["cow"]
        # Create a custom repo
        repo = entities.Repository(
            content_type='yum',
            product=entities.Product(organization=self.org).create(),
            url=settings.repos.yum_0.url,
        ).create()
        repo.sync()
        prod = repo.product.read()
        subs = entities.Subscription(organization=self.org).search(
            query={'search': f'name={prod.name}'})
        assert len(subs), 'No subscriptions matching the product returned'
        ak = entities.ActivationKey(
            organization=self.org,
            content_view=self.org.default_content_view,
            environment=self.org.library,
        ).create()
        ak.add_subscriptions(data={'subscriptions': [{'id': subs[0].id}]})
        client.register_contenthost(org=self.org.label, activation_key=ak.name)

        # install package
        invocation_command = make_job_invocation({
            'job-template':
            'Package Action - Ansible Default',
            'inputs':
            'state=latest, name={}'.format(*packages),
            'search-query':
            f'name ~ {client.hostname}',
        })
        result = JobInvocation.info({'id': invocation_command['id']})
        try:
            assert result['success'] == '1'
        except AssertionError:
            result = 'host output: {}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command['id'],
                    'host': client.hostname
                })))
            raise AssertionError(result)
        result = client.run(f'rpm -q {" ".join(packages)}')
        assert result.status == 0

        # start a service
        service = "postfix"
        client.execute(
            "sed -i 's/^inet_protocols.*/inet_protocols = ipv4/' /etc/postfix/main.cf",
        )
        invocation_command = make_job_invocation({
            'job-template':
            'Service Action - Ansible Default',
            'inputs':
            f'state=started, name={service}',
            'search-query':
            f"name ~ {client.hostname}",
        })
        result = JobInvocation.info({'id': invocation_command['id']})
        try:
            assert result['success'] == '1'
        except AssertionError:
            result = 'host output: {}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command['id'],
                    'host': client.hostname
                })))
            raise AssertionError(result)
        result = client.execute(f"systemctl status {service}")
        assert result.status == 0
Exemple #22
0
def test_positive_oscap_run_via_ansible_bz_1814988(module_org, default_proxy,
                                                   content_view,
                                                   lifecycle_env):
    """End-to-End Oscap run via ansible

    :id: 375f8f08-9299-4d16-91f9-9426eeecb9c5

    :parametrized: yes

    :customerscenario: true

    :setup: scap content, scap policy, host group

    :steps:

        1. Create a valid scap content
        2. Import Ansible role theforeman.foreman_scap_client
        3. Import Ansible Variables needed for the role
        4. Create a scap policy with anisble as deploy option
        5. Associate the policy with a hostgroup
        6. Provision a host using the hostgroup
        7. Harden the host by remediating it with DISA STIG security policy
        8. Configure REX and associate the Ansible role to created host
        9. Play roles for the host

    :expectedresults: REX job should be success and ARF report should be sent to satellite

    :BZ: 1814988

    :CaseImportance: Critical
    """
    hgrp_name = gen_string('alpha')
    policy_name = gen_string('alpha')
    # Creates host_group for rhel7
    make_hostgroup({
        'content-source-id': default_proxy,
        'name': hgrp_name,
        'organizations': module_org.name,
    })
    # Creates oscap_policy.
    scap_id, scap_profile_id = fetch_scap_and_profile_id(
        OSCAP_DEFAULT_CONTENT['rhel7_content'], OSCAP_PROFILE['dsrhel7'])
    Ansible.roles_import({'proxy-id': default_proxy})
    Ansible.variables_import({'proxy-id': default_proxy})
    role_id = Ansible.roles_list({'search':
                                  'foreman_scap_client'})[0].get('id')
    make_scap_policy({
        'scap-content-id': scap_id,
        'hostgroups': hgrp_name,
        'deploy-by': 'ansible',
        'name': policy_name,
        'period': OSCAP_PERIOD['weekly'].lower(),
        'scap-content-profile-id': scap_profile_id,
        'weekday': OSCAP_WEEKDAY['friday'].lower(),
        'organizations': module_org.name,
    })
    with VMBroker(nick=DISTRO_RHEL7, host_classes={'host': ContentHost}) as vm:
        host_name, _, host_domain = vm.hostname.partition('.')
        vm.install_katello_ca()
        vm.register_contenthost(module_org.name, ak_name[DISTRO_RHEL7])
        assert vm.subscribed
        Host.set_parameter({
            'host': vm.hostname.lower(),
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        vm.configure_rhel_repo(settings.repos.rhel7_repo)
        # Harden the rhel7 client with DISA STIG security policy
        vm.run('yum install -y scap-security-guide')
        vm.run(
            'oscap xccdf eval --remediate --profile xccdf_org.ssgproject.content_profile_stig '
            '--fetch-remote-resources --results-arf results.xml '
            '/usr/share/xml/scap/ssg/content/ssg-rhel7-ds.xml', )
        add_remote_execution_ssh_key(vm.ip_addr)
        Host.update({
            'name': vm.hostname.lower(),
            'lifecycle-environment': lifecycle_env.name,
            'content-view': content_view.name,
            'hostgroup': hgrp_name,
            'openscap-proxy-id': default_proxy,
            'organization': module_org.name,
            'ansible-role-ids': role_id,
        })
        job_id = Host.ansible_roles_play({'name':
                                          vm.hostname.lower()})[0].get('id')
        wait_for_tasks(
            f'resource_type = JobInvocation and resource_id = {job_id} and action ~ "hosts job"'
        )
        try:
            result = JobInvocation.info({'id': job_id})['success']
            assert result == '1'
        except AssertionError:
            output = ' '.join(
                JobInvocation.get_output({
                    'id': job_id,
                    'host': vm.hostname
                }))
            result = f'host output: {output}'
            raise AssertionError(result)
        result = vm.run(
            'cat /etc/foreman_scap_client/config.yaml | grep profile')
        assert result.status == 0
        # Runs the actual oscap scan on the vm/clients and
        # uploads report to Internal Capsule.
        vm.execute_foreman_scap_client()
        # Assert whether oscap reports are uploaded to
        # Satellite6.
        result = Arfreport.list({'search': f'host={vm.hostname.lower()}'})
        assert result is not None
    def test_positive_run_reccuring_job(self, fixture_vmsetup, fixture_org):
        """Tests Ansible REX reccuring job runs successfully multiple times

        :id: 49b0d31d-58f9-47f1-aa5d-561a1dcb0d66

        :Steps:

            0. Create a VM and register to SAT and prepare for REX (ssh key)

            1. Run recurring Ansible Command job for the host

            2. Check the multiple job results at the host

        :expectedresults: multiple asserts along the code

        :CaseAutomation: automated

        :CaseLevel: System
        """
        self.org = fixture_org
        self.client = fixture_vmsetup
        # set connecting to host by ip
        Host.set_parameter({
            'host': self.client.hostname,
            'name': 'remote_execution_connect_by_ip',
            'value': 'True',
        })
        invocation_command = make_job_invocation({
            'job-template':
            'Run Command - Ansible Default',
            'inputs':
            'command="ls"',
            'search-query':
            "name ~ {0}".format(self.client.hostname),
            'cron-line':
            '* * * * *',  # every minute
            'max-iteration':
            2,  # just two runs
        })
        JobInvocation.get_output({
            'id': invocation_command[u'id'],
            'host': self.client.hostname
        })
        try:
            assert invocation_command['status'] == u'queued'
        except AssertionError:
            result = 'host output: {0}'.format(' '.join(
                JobInvocation.get_output({
                    'id': invocation_command[u'id'],
                    'host': self.client.hostname
                })))
            raise AssertionError(result)
        # Wait until the job runs
        pending_state = u'1'
        for _ in range(10):
            if pending_state != u'0':
                invocation_info = JobInvocation.info(
                    {'id': invocation_command[u'id']})
                pending_state = invocation_info[u'pending']
                sleep(30)
            else:
                break
        rec_logic = RecurringLogic.info(
            {'id': invocation_command['recurring-logic-id']})
        assert rec_logic['state'] == u'finished'
        assert rec_logic['iteration'] == u'2'
Exemple #24
0
    def test_positive_oscap_run_with_tailoring_file_with_ansible(self):
        """End-to-End Oscap run with tailoring files via ansible

        :id: c7ea56eb-6cf1-4e79-8d6a-fb872d1bb804

        :setup: scap content, scap policy, tailoring file, host group

        :steps:

            1. Create a valid scap content
            2. Upload a valid tailoring file
            3. Import Ansible role theforeman.foreman_scap_client
            4. Import Ansible Variables needed for the role
            5. Create a scap policy with anisble as deploy option
            6. Associate scap content with it's tailoring file
            7. Associate the policy with a hostgroup
            8. Provision a host using the hostgroup
            9. Configure REX and associate the Ansible role to created host
            10. Play roles for the host

        :expectedresults: REX job should be success and ARF report should be sent to satellite
                         reflecting the changes done via tailoring files

        :BZ: 1716307

        :CaseImportance: Critical
        """
        if settings.rhel7_repo is None:
            self.skipTest('Missing configuration for rhel7_repo')
        rhel7_repo = settings.rhel7_repo
        hgrp7_name = gen_string('alpha')
        policy_values = {
            'content': self.rhel7_content,
            'hgrp': hgrp7_name,
            'policy': gen_string('alpha'),
            'profile': OSCAP_PROFILE['security7'],
        }
        vm_values = {
            'distro': DISTRO_RHEL7,
            'hgrp': hgrp7_name,
            'rhel_repo': rhel7_repo
        }
        tailoring_file_name = gen_string('alpha')
        tailor_path = file_downloader(file_url=settings.oscap.tailoring_path,
                                      hostname=settings.server.hostname)[0]
        # Creates host_group for rhel7
        make_hostgroup({
            'content-source-id': self.proxy_id,
            'name': hgrp7_name,
            'organizations': self.config_env['org_name'],
        })

        tailor_result = make_tailoringfile({
            'name':
            tailoring_file_name,
            'scap-file':
            tailor_path,
            'organization':
            self.config_env['org_name'],
        })
        result = TailoringFiles.info({'name': tailoring_file_name})
        assert result['name'] == tailoring_file_name
        # Creates oscap_policy for rhel7.
        scap_id, scap_profile_id = self.fetch_scap_and_profile_id(
            policy_values.get('content'), policy_values.get('profile'))
        Ansible.roles_import({'proxy-id': self.proxy_id})
        Ansible.variables_import({'proxy-id': self.proxy_id})
        role_id = Ansible.roles_list({'search':
                                      'foreman_scap_client'})[0].get('id')
        make_scap_policy({
            'scap-content-id':
            scap_id,
            'hostgroups':
            policy_values.get('hgrp'),
            'deploy-by':
            'ansible',
            'name':
            policy_values.get('policy'),
            'period':
            OSCAP_PERIOD['weekly'].lower(),
            'scap-content-profile-id':
            scap_profile_id,
            'weekday':
            OSCAP_WEEKDAY['friday'].lower(),
            'tailoring-file-id':
            tailor_result['id'],
            'tailoring-file-profile-id':
            tailor_result['tailoring-file-profiles'][0]['id'],
            'organizations':
            self.config_env['org_name'],
        })
        distro_os = vm_values.get('distro')
        with VirtualMachine(distro=distro_os) as vm:
            host_name, _, host_domain = vm.hostname.partition('.')
            vm.install_katello_ca()
            vm.register_contenthost(self.config_env['org_name'],
                                    self.config_env['ak_name'].get(distro_os))
            assert vm.subscribed
            Host.set_parameter({
                'host': vm.hostname.lower(),
                'name': 'remote_execution_connect_by_ip',
                'value': 'True',
            })
            vm.configure_rhel_repo(settings.rhel7_repo)
            add_remote_execution_ssh_key(vm.ip_addr)
            Host.update({
                'name': vm.hostname.lower(),
                'lifecycle-environment': self.config_env['env_name'],
                'content-view': self.config_env['cv_name'],
                'hostgroup': vm_values.get('hgrp'),
                'openscap-proxy-id': self.proxy_id,
                'organization': self.config_env['org_name'],
                'ansible-role-ids': role_id,
            })
            job_id = Host.ansible_roles_play({'name': vm.hostname.lower()
                                              })[0].get('id')
            wait_for_tasks(
                f"resource_type = JobInvocation and resource_id = {job_id} and "
                "action ~ \"hosts job\"")
            try:
                result = JobInvocation.info({'id': job_id})['success']
                assert result == '1'
            except AssertionError:
                output = ' '.join(
                    JobInvocation.get_output({
                        'id': job_id,
                        'host': vm.hostname
                    }))
                result = f'host output: {output}'
                raise AssertionError(result)
            result = vm.run(
                'cat /etc/foreman_scap_client/config.yaml | grep profile')
            assert result.return_code == 0
            # Runs the actual oscap scan on the vm/clients and
            # uploads report to Internal Capsule.
            vm.execute_foreman_scap_client()
            # Assert whether oscap reports are uploaded to
            # Satellite6.
            result = Arfreport.list({'search': f'host={vm.hostname.lower()}'})
            assert result is not None