Exemplo n.º 1
0
def test_validate_certs_with_server_config(global_ignore_certs, server_config,
                                           monkeypatch):

    # test sidesteps real resolution and forces the server config to override the cli option
    get_plugin_options = MagicMock(side_effect=server_config)
    monkeypatch.setattr(C.config, 'get_plugin_options', get_plugin_options)

    cli_args = [
        'ansible-galaxy',
        'collection',
        'install',
        'namespace.collection:1.0.0',
    ]
    if global_ignore_certs:
        cli_args.append('--ignore-certs')

    galaxy_cli = GalaxyCLI(args=cli_args)
    mock_execute_install = MagicMock()
    monkeypatch.setattr(galaxy_cli, '_execute_install_collection',
                        mock_execute_install)
    galaxy_cli.run()

    # server cfg, so should match def above, if not specified so it should use default (true)
    assert galaxy_cli.api_servers[0].validate_certs is server_config[0].get(
        'validate_certs', True)
    assert galaxy_cli.api_servers[1].validate_certs is server_config[1].get(
        'validate_certs', True)
    assert galaxy_cli.api_servers[2].validate_certs is server_config[2].get(
        'validate_certs', True)
Exemplo n.º 2
0
    def _install_roles_from_file(plugin_path):
        # Ansible Galaxy - install roles from file
        for req_file in ['requirements.yml', 'requirements.yaml']:
            galaxy_reqs_file = os.path.join(plugin_path, req_file)
            if not os.path.isfile(galaxy_reqs_file):
                continue
            LOG.debug(
                "Installing Ansible Galaxy "
                "requirements from file... ({})".format(galaxy_reqs_file))
            from ansible.cli.galaxy import GalaxyCLI
            from ansible.errors import AnsibleError

            glxy_cli_params = [
                'ansible-galaxy', 'role', 'install', '-r', galaxy_reqs_file
            ]
            if InfraredPluginManager._is_collection_requirements(
                    galaxy_reqs_file):
                glxy_cli_params[1] = 'collection'
            LOG.debug("Ansible Galaxy command: {}".format(glxy_cli_params))
            glxy_cli = GalaxyCLI(glxy_cli_params)
            glxy_cli.parse()

            LOG.debug(
                "Trying to install Ansible Galaxy required "
                "collection 5 times to circumvent potential network issues")
            try:
                glxy_cli.run()
            except AnsibleError as e:
                raise IRGalaxyRoleInstallFailedException(
                    "Failed to install Ansible Galaxy requirements, aborting! Error: {}"
                    .format(e))
        else:
            LOG.debug("Ansible Galaxy requirements files weren't found.")
Exemplo n.º 3
0
def test_invalid_skeleton_path():
    expected = "- the skeleton path '/fake/path' does not exist, cannot init collection"

    gc = GalaxyCLI(args=['ansible-galaxy', 'collection', 'init', 'my.collection', '--collection-skeleton',
                         '/fake/path'])
    with pytest.raises(AnsibleError, match=expected):
        gc.run()
Exemplo n.º 4
0
    def setUpClass(cls):
        '''creating prerequisites for installing a role; setUpClass occurs ONCE whereas setUp occurs with every method tested.'''
        # class data for easy viewing: role_dir, role_tar, role_name, role_req, role_path

        if os.path.exists("./delete_me"):
            shutil.rmtree("./delete_me")

        # creating framework for a role
        gc = GalaxyCLI(args=["init"])
        with patch('sys.argv', ["-c", "--offline", "delete_me"]):
            gc.parse()
        gc.run()
        cls.role_dir = "./delete_me"
        cls.role_name = "delete_me"

        # making a temp dir for role installation
        cls.role_path = os.path.join(tempfile.mkdtemp(), "roles")
        if not os.path.isdir(cls.role_path):
            os.makedirs(cls.role_path)

        # creating a tar file name for class data
        cls.role_tar = './delete_me.tar.gz'
        cls.makeTar(cls.role_tar, cls.role_dir)

        # creating a temp file with installation requirements
        cls.role_req = './delete_me_requirements.yml'
        fd = open(cls.role_req, "w")
        fd.write("- 'src': '%s'\n  'name': '%s'\n  'path': '%s'" %
                 (cls.role_tar, cls.role_name, cls.role_path))
        fd.close()
Exemplo n.º 5
0
def test_bool_type_server_config_options(config, server, monkeypatch):
    cli_args = [
        'ansible-galaxy',
        'collection',
        'install',
        'namespace.collection:1.0.0',
    ]

    config_lines = [
        "[galaxy]",
        "server_list=server1\n",
        "[galaxy_server.server1]",
        "url=%s" % config['url'],
        "v3=%s" % config['v3'],
        "validate_certs=%s\n" % config['validate_certs'],
    ]

    with tempfile.NamedTemporaryFile(suffix='.cfg') as tmp_file:
        tmp_file.write(to_bytes('\n'.join(config_lines)))
        tmp_file.flush()

        with patch.object(C, 'GALAXY_SERVER_LIST', ['server1']):
            with patch.object(C.config, '_config_file', tmp_file.name):
                C.config._parse_config_file()
                galaxy_cli = GalaxyCLI(args=cli_args)
                mock_execute_install = MagicMock()
                monkeypatch.setattr(galaxy_cli, '_execute_install_collection',
                                    mock_execute_install)
                galaxy_cli.run()

    assert galaxy_cli.api_servers[0].name == 'server1'
    assert galaxy_cli.api_servers[0].validate_certs == server['validate_certs']
    assert galaxy_cli.api_servers[0]._available_api_versions == server[
        '_available_api_versions']
Exemplo n.º 6
0
 def test_exit_without_ignore_with_flag(self):
     ''' tests that GalaxyCLI exits without the error specified if the --ignore-errors flag is used  '''
     # testing with --ignore-errors flag
     gc = GalaxyCLI(args=["ansible-galaxy", "install", "--server=None", "fake_role_name", "--ignore-errors"])
     with patch.object(ansible.utils.display.Display, "display", return_value=None) as mocked_display:
         gc.run()
         self.assertTrue(mocked_display.called_once_with("- downloading role 'fake_role_name', owned by "))
Exemplo n.º 7
0
def test_install_installed_collection(monkeypatch, tmp_path_factory,
                                      galaxy_server):

    mock_installed_collections = MagicMock(
        return_value=[Candidate('namespace.collection', '1.2.3', None, 'dir')])

    monkeypatch.setattr(collection, 'find_existing_collections',
                        mock_installed_collections)

    test_dir = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections'))
    concrete_artifact_cm = collection.concrete_artifact_manager.ConcreteArtifactsManager(
        test_dir, validate_certs=False)

    mock_display = MagicMock()
    monkeypatch.setattr(Display, 'display', mock_display)

    mock_get_info = MagicMock()
    mock_get_info.return_value = api.CollectionVersionMetadata(
        'namespace', 'collection', '1.2.3', None, None, {})
    monkeypatch.setattr(galaxy_server, 'get_collection_version_metadata',
                        mock_get_info)

    mock_get_versions = MagicMock(return_value=['1.2.3', '1.3.0'])
    monkeypatch.setattr(galaxy_server, 'get_collection_versions',
                        mock_get_versions)

    cli = GalaxyCLI(args=[
        'ansible-galaxy', 'collection', 'install', 'namespace.collection'
    ])
    cli.run()

    expected = "Nothing to do. All requested collections are already installed. If you want to reinstall them, consider using `--force`."
    assert mock_display.mock_calls[1][1][0] == expected
Exemplo n.º 8
0
    def test_exit_without_ignore(self):
        ''' tests that GalaxyCLI exits with the error specified unless the --ignore-errors flag is used '''
        gc = GalaxyCLI(args=["install"])

        # testing without --ignore-errors flag
        with patch('sys.argv', ["-c", "fake_role_name"]):
            galaxy_parser = gc.parse()
        with patch.object(ansible.utils.display.Display,
                          "display",
                          return_value=None) as mocked_display:
            # testing that error expected is raised
            self.assertRaises(AnsibleError, gc.run)
            self.assertTrue(
                mocked_display.called_once_with(
                    "- downloading role 'fake_role_name', owned by "))

        # testing with --ignore-errors flag
        with patch('sys.argv', ["-c", "fake_role_name", "--ignore-errors"]):
            galalxy_parser = gc.parse()
        with patch.object(ansible.utils.display.Display,
                          "display",
                          return_value=None) as mocked_display:
            # testing that error expected is not raised with --ignore-errors flag in use
            gc.run()
            self.assertTrue(
                mocked_display.called_once_with(
                    "- downloading role 'fake_role_name', owned by "))
Exemplo n.º 9
0
    def setUpClass(cls):
        '''creating prerequisites for installing a role; setUpClass occurs ONCE whereas setUp occurs with every method tested.'''
        # class data for easy viewing: role_dir, role_tar, role_name, role_req, role_path

        if os.path.exists("./delete_me"):
            shutil.rmtree("./delete_me")

        # creating framework for a role
        gc = GalaxyCLI(args=["init"])
        with patch('sys.argv', ["-c", "--offline", "delete_me"]):
            gc.parse()
        gc.run()
        cls.role_dir = "./delete_me"
        cls.role_name = "delete_me"

        # making a temp dir for role installation
        cls.role_path = os.path.join(tempfile.mkdtemp(), "roles")
        if not os.path.isdir(cls.role_path):
            os.makedirs(cls.role_path)

        # creating a tar file name for class data
        cls.role_tar = './delete_me.tar.gz'
        cls.makeTar(cls.role_tar, cls.role_dir)

        # creating a temp file with installation requirements
        cls.role_req = './delete_me_requirements.yml'
        fd = open(cls.role_req, "w")
        fd.write("- 'src': '%s'\n  'name': '%s'\n  'path': '%s'" % (cls.role_tar, cls.role_name, cls.role_path))
        fd.close()
Exemplo n.º 10
0
    def setUpRole(cls, role_name, galaxy_args=None, skeleton_path=None):
        if galaxy_args is None:
            galaxy_args = []

        if skeleton_path is not None:
            cls.role_skeleton_path = skeleton_path
            galaxy_args += ['--role-skeleton', skeleton_path]

        # Make temp directory for testing
        cls.test_dir = tempfile.mkdtemp()
        if not os.path.isdir(cls.test_dir):
            os.makedirs(cls.test_dir)

        cls.role_dir = os.path.join(cls.test_dir, role_name)
        cls.role_name = role_name

        # create role using default skeleton
        gc = GalaxyCLI(args=['ansible-galaxy', 'init', '-c', '--offline'] +
                       galaxy_args +
                       ['--init-path', cls.test_dir, cls.role_name])
        gc.parse()
        gc.run()
        cls.gc = gc

        if skeleton_path is None:
            cls.role_skeleton_path = gc.galaxy.default_role_skeleton_path
Exemplo n.º 11
0
 def test_exit_without_ignore_with_flag(self):
     ''' tests that GalaxyCLI exits without the error specified if the --ignore-errors flag is used  '''
     # testing with --ignore-errors flag
     gc = GalaxyCLI(args=["ansible-galaxy", "install", "--server=None", "fake_role_name", "--ignore-errors"])
     gc.parse()
     with patch.object(ansible.utils.display.Display, "display", return_value=None) as mocked_display:
         gc.run()
         self.assertTrue(mocked_display.called_once_with("- downloading role 'fake_role_name', owned by "))
Exemplo n.º 12
0
def test_verbosity_arguments(cli_args, expected, monkeypatch):
    # Mock out the functions so we don't actually execute anything
    for func_name in [f for f in dir(GalaxyCLI) if f.startswith("execute_")]:
        monkeypatch.setattr(GalaxyCLI, func_name, MagicMock())

    cli = GalaxyCLI(args=cli_args)
    cli.run()

    assert context.CLIARGS['verbosity'] == expected
Exemplo n.º 13
0
 def test_run(self):
     ''' verifies that the GalaxyCLI object's api is created and that execute() is called. '''
     gc = GalaxyCLI(args=["ansible-galaxy", "install", "--ignore-errors", "imaginary_role"])
     gc.parse()
     with patch.object(ansible.cli.CLI, "run", return_value=None) as mock_run:
         gc.run()
         # testing
         self.assertIsInstance(gc.galaxy, ansible.galaxy.Galaxy)
         self.assertEqual(mock_run.call_count, 1)
         self.assertTrue(isinstance(gc.api, ansible.galaxy.api.GalaxyAPI))
Exemplo n.º 14
0
def test_require_one_of_collections_requirements_with_neither():
    cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'verify'])

    with pytest.raises(AnsibleError) as req_err:
        cli._require_one_of_collections_requirements((), '')

    with pytest.raises(AnsibleError) as cli_err:
        cli.run()

    assert req_err.value.message == cli_err.value.message == 'You must specify a collection name or a requirements file.'
Exemplo n.º 15
0
def test_require_one_of_collections_requirements_with_both():
    cli = GalaxyCLI(args=['ansible-galaxy', 'collection', 'verify', 'namespace.collection', '-r', 'requirements.yml'])

    with pytest.raises(AnsibleError) as req_err:
        cli._require_one_of_collections_requirements(('namespace.collection',), 'requirements.yml')

    with pytest.raises(AnsibleError) as cli_err:
        cli.run()

    assert req_err.value.message == cli_err.value.message == 'The positional collection_name arg and --requirements-file are mutually exclusive.'
Exemplo n.º 16
0
def test_invalid_collection_name_install(name, expected, tmp_path_factory):
    install_path = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections'))
    expected = "Invalid collection name '%s', name must be in the format <namespace>.<collection>" % expected

    gc = GalaxyCLI(args=[
        'ansible-galaxy', 'collection', 'install', name, '-p',
        os.path.join(install_path, 'install')
    ])
    with pytest.raises(AnsibleError, match=expected):
        gc.run()
Exemplo n.º 17
0
    def test_run(self):
        ''' verifies that the GalaxyCLI object's api is created and that execute() is called. '''
        gc = GalaxyCLI(args=["ansible-galaxy", "install", "--ignore-errors", "imaginary_role"])
        gc.parse()
        with patch.object(ansible.cli.CLI, "execute", return_value=None) as mock_ex:
            with patch.object(ansible.cli.CLI, "run", return_value=None) as mock_run:
                gc.run()

                # testing
                self.assertEqual(mock_run.call_count, 1)
                self.assertTrue(isinstance(gc.api, ansible.galaxy.api.GalaxyAPI))
                self.assertEqual(mock_ex.call_count, 1)
Exemplo n.º 18
0
def collection_artifact(collection_skeleton, tmp_path_factory):
    ''' Creates a collection artifact tarball that is ready to be published and installed '''
    output_dir = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Output'))

    # Because we call GalaxyCLI in collection_skeleton we need to reset the singleton back to None so it uses the new
    # args, we reset the original args once it is done.
    orig_cli_args = co.GlobalCLIArgs._Singleton__instance
    try:
        co.GlobalCLIArgs._Singleton__instance = None
        galaxy_args = ['ansible-galaxy', 'collection', 'build', collection_skeleton, '--output-path', output_dir]
        gc = GalaxyCLI(args=galaxy_args)
        gc.run()

        yield output_dir
    finally:
        co.GlobalCLIArgs._Singleton__instance = orig_cli_args
Exemplo n.º 19
0
def test_validate_certs_with_server_url(global_ignore_certs, monkeypatch):
    cli_args = [
        'ansible-galaxy', 'collection', 'install',
        'namespace.collection:1.0.0', '-s', 'https://galaxy.ansible.com'
    ]
    if global_ignore_certs:
        cli_args.append('--ignore-certs')

    galaxy_cli = GalaxyCLI(args=cli_args)
    mock_execute_install = MagicMock()
    monkeypatch.setattr(galaxy_cli, '_execute_install_collection',
                        mock_execute_install)
    galaxy_cli.run()

    assert len(galaxy_cli.api_servers) == 1
    assert galaxy_cli.api_servers[0].validate_certs is not global_ignore_certs
Exemplo n.º 20
0
    def test_run(self):
        ''' verifies that the GalaxyCLI object's api is created and that execute() is called. '''
        gc = GalaxyCLI(args=["install"])
        with patch('sys.argv',
                   ["-c", "-v", '--ignore-errors', 'imaginary_role']):
            galaxy_parser = gc.parse()
        with patch.object(ansible.cli.CLI, "execute",
                          return_value=None) as mock_ex:
            with patch.object(ansible.cli.CLI, "run",
                              return_value=None) as mock_run:
                gc.run()

                # testing
                self.assertEqual(mock_run.call_count, 1)
                self.assertTrue(
                    isinstance(gc.api, ansible.galaxy.api.GalaxyAPI))
                self.assertEqual(mock_ex.call_count, 1)
Exemplo n.º 21
0
def test_cli_options(required_signature_count, valid, monkeypatch):
    cli_args = [
        'ansible-galaxy', 'collection', 'install',
        'namespace.collection:1.0.0', '--keyring', '~/.ansible/pubring.kbx',
        '--required-valid-signature-count', required_signature_count
    ]

    galaxy_cli = GalaxyCLI(args=cli_args)
    mock_execute_install = MagicMock()
    monkeypatch.setattr(galaxy_cli, '_execute_install_collection',
                        mock_execute_install)

    if valid:
        galaxy_cli.run()
    else:
        with pytest.raises(SystemExit, match='2') as error:
            galaxy_cli.run()
Exemplo n.º 22
0
    def test_execute_remove(self):
        # installing role
        gc = GalaxyCLI(args=["ansible-galaxy", "install", "-p", self.role_path, "-r", self.role_req, '--force'])
        gc.parse()
        gc.run()

        # location where the role was installed
        role_file = os.path.join(self.role_path, self.role_name)

        # removing role
        gc = GalaxyCLI(args=["ansible-galaxy", "remove", role_file, self.role_name])
        gc.parse()
        gc.run()

        # testing role was removed
        removed_role = not os.path.exists(role_file)
        self.assertTrue(removed_role)
Exemplo n.º 23
0
    def test_execute_remove(self):
        # installing role
        gc = GalaxyCLI(args=["install", "--offline", "-p", self.role_path, "-r", self.role_req, '--force'])
        gc.parse()
        gc.run()

        # location where the role was installed
        role_file = os.path.join(self.role_path, self.role_name)

        # removing role
        gc = GalaxyCLI(args=["remove", "-p", role_file, self.role_name])
        gc.parse()
        gc.run()

        # testing role was removed
        removed_role = not os.path.exists(role_file)
        self.assertTrue(removed_role)
Exemplo n.º 24
0
    def test_exit_without_ignore(self):
        ''' tests that GalaxyCLI exits with the error specified unless the --ignore-errors flag is used '''
        gc = GalaxyCLI(args=["install", "--server=None", "-c", "fake_role_name"])

        # testing without --ignore-errors flag
        galaxy_parser = gc.parse()
        with patch.object(ansible.utils.display.Display, "display", return_value=None) as mocked_display:
            # testing that error expected is raised
            self.assertRaises(AnsibleError, gc.run)
            self.assertTrue(mocked_display.called_once_with("- downloading role 'fake_role_name', owned by "))

        # testing with --ignore-errors flag
        gc = GalaxyCLI(args=["install", "--server=None", "-c", "fake_role_name", "--ignore-errors"])
        galalxy_parser = gc.parse()
        with patch.object(ansible.utils.display.Display, "display", return_value=None) as mocked_display:
            # testing that error expected is not raised with --ignore-errors flag in use
            gc.run()
            self.assertTrue(mocked_display.called_once_with("- downloading role 'fake_role_name', owned by "))
Exemplo n.º 25
0
    def test_execute_remove(self):
        # installing role
        gc = GalaxyCLI(args=["ansible-galaxy", "install", "-p", self.role_path, "-r", self.role_req, '--force'])
        gc.run()

        # location where the role was installed
        role_file = os.path.join(self.role_path, self.role_name)

        # removing role
        # Have to reset the arguments in the context object manually since we're doing the
        # equivalent of running the command line program twice
        co.GlobalCLIArgs._Singleton__instance = None
        gc = GalaxyCLI(args=["ansible-galaxy", "remove", role_file, self.role_name])
        gc.run()

        # testing role was removed
        removed_role = not os.path.exists(role_file)
        self.assertTrue(removed_role)
Exemplo n.º 26
0
    def test_execute_remove(self):
        # installing role
        gc = GalaxyCLI(args=["install", "--offline", "-p", self.role_path, "-r", self.role_req])
        galaxy_parser = gc.parse()
        gc.run()

        # checking that installation worked
        role_file = os.path.join(self.role_path, self.role_name)
        self.assertTrue(os.path.exists(role_file))

        # removing role
        gc = GalaxyCLI(args=["remove", "-c", "-p", self.role_path, self.role_name])
        galaxy_parser = gc.parse()
        super(GalaxyCLI, gc).run()
        gc.api = ansible.galaxy.api.GalaxyAPI(gc.galaxy)
        completed_task = gc.execute_remove()

        # testing role was removed
        self.assertTrue(completed_task == 0)
        self.assertTrue(not os.path.exists(role_file))
Exemplo n.º 27
0
def test_validate_certs(global_ignore_certs, server_config, monkeypatch):
    get_plugin_options = MagicMock(side_effect=server_config)
    monkeypatch.setattr(C.config, 'get_plugin_options', get_plugin_options)

    cli_args = [
        'ansible-galaxy',
        'collection',
        'install',
        'namespace.collection:1.0.0',
    ]
    if global_ignore_certs:
        cli_args.append('--ignore-certs')

    galaxy_cli = GalaxyCLI(args=cli_args)
    mock_execute_install = MagicMock()
    monkeypatch.setattr(galaxy_cli, '_execute_install_collection',
                        mock_execute_install)
    galaxy_cli.run()

    assert galaxy_cli.api_servers[0].validate_certs is False
    assert galaxy_cli.api_servers[1].validate_certs is True
    assert galaxy_cli.api_servers[2].validate_certs is not global_ignore_certs
Exemplo n.º 28
0
def test_client_id(monkeypatch):
    monkeypatch.setattr(C, 'GALAXY_SERVER_LIST', ['server1', 'server2'])

    test_server_config = {option[0]: None for option in SERVER_DEF}
    test_server_config.update(
        {
            'url': 'http://my_galaxy_ng:8000/api/automation-hub/',
            'auth_url': 'http://my_keycloak:8080/auth/realms/myco/protocol/openid-connect/token',
            'client_id': 'galaxy-ng',
            'token': 'access_token',
        }
    )

    test_server_default = {option[0]: None for option in SERVER_DEF}
    test_server_default.update(
        {
            'url': 'https://cloud.redhat.com/api/automation-hub/',
            'auth_url': 'https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token',
            'token': 'access_token',
        }
    )

    get_plugin_options = MagicMock(side_effect=[test_server_config, test_server_default])
    monkeypatch.setattr(C.config, 'get_plugin_options', get_plugin_options)

    cli_args = [
        'ansible-galaxy',
        'collection',
        'install',
        'namespace.collection:1.0.0',
    ]

    galaxy_cli = GalaxyCLI(args=cli_args)
    mock_execute_install = MagicMock()
    monkeypatch.setattr(galaxy_cli, '_execute_install_collection', mock_execute_install)
    galaxy_cli.run()

    assert galaxy_cli.api_servers[0].token.client_id == 'galaxy-ng'
    assert galaxy_cli.api_servers[1].token.client_id == 'cloud-services'
Exemplo n.º 29
0
    def setUpRole(cls, role_name, galaxy_args=None, skeleton_path=None):
        if galaxy_args is None:
            galaxy_args = []

        if skeleton_path is not None:
            cls.role_skeleton_path = skeleton_path
            galaxy_args += ['--role-skeleton', skeleton_path]

        # Make temp directory for testing
        cls.test_dir = tempfile.mkdtemp()
        if not os.path.isdir(cls.test_dir):
            os.makedirs(cls.test_dir)

        cls.role_dir = os.path.join(cls.test_dir, role_name)
        cls.role_name = role_name

        # create role using default skeleton
        gc = GalaxyCLI(args=['ansible-galaxy', 'init', '-c', '--offline'] + galaxy_args + ['--init-path', cls.test_dir, cls.role_name])
        gc.parse()
        gc.run()
        cls.gc = gc

        if skeleton_path is None:
            cls.role_skeleton_path = gc.galaxy.default_role_skeleton_path
Exemplo n.º 30
0
    def run(self):

        super(PlaybookCLI, self).run()

        # Note: slightly wrong, this is written so that implicit localhost
        # Manage passwords
        sshpass = None
        becomepass = None
        passwords = {}

        if self.options.role_file:
            args = ["install"]
            if self.options.ignore_errors:
                args.append("--ignore-errors")

            force = ""
            if self.options.force:
                args.append("--force")

            if self.options.roles_path:
                args.extend(["--roles-path", self.options.roles_path])

            if self.options.no_deps:
                args.append("--no-deps")

            args.extend(["--role-file", self.options.role_file])
            gc = GalaxyCLI(args=args)
            gc.parse()
            gc.run()

        # initial error check, to make sure all specified playbooks are accessible
        # before we start running anything through the playbook executor
        for playbook in self.args:
            if not os.path.exists(playbook):
                raise AnsibleError("the playbook: %s could not be found" %
                                   playbook)
            if not (os.path.isfile(playbook)
                    or stat.S_ISFIFO(os.stat(playbook).st_mode)):
                raise AnsibleError(
                    "the playbook: %s does not appear to be a file" % playbook)

        # don't deal with privilege escalation or passwords when we don't need to
        if not self.options.listhosts and not self.options.listtasks and not self.options.listtags and not self.options.syntax:
            self.normalize_become_options()
            (sshpass, becomepass) = self.ask_passwords()
            passwords = {'conn_pass': sshpass, 'become_pass': becomepass}

        loader, inventory, variable_manager = self._play_prereqs(self.options)

        # (which is not returned in list_hosts()) is taken into account for
        # warning if inventory is empty.  But it can't be taken into account for
        # checking if limit doesn't match any hosts.  Instead we don't worry about
        # limit if only implicit localhost was in inventory to start with.
        #
        # Fix this when we rewrite inventory by making localhost a real host (and thus show up in list_hosts())
        no_hosts = False
        if len(inventory.list_hosts()) == 0:
            # Empty inventory
            display.warning(
                "provided hosts list is empty, only localhost is available")
            no_hosts = True
        inventory.subset(self.options.subset)
        if len(inventory.list_hosts()) == 0 and no_hosts is False:
            # Invalid limit
            raise AnsibleError("Specified --limit does not match any hosts")

        # flush fact cache if requested
        if self.options.flush_cache:
            self._flush_cache(inventory, variable_manager)

        # create the playbook executor, which manages running the plays via a task queue manager
        pbex = PlaybookExecutor(playbooks=self.args,
                                inventory=inventory,
                                variable_manager=variable_manager,
                                loader=loader,
                                options=self.options,
                                passwords=passwords)

        results = pbex.run()

        if isinstance(results, list):
            for p in results:

                display.display('\nplaybook: %s' % p['playbook'])
                for idx, play in enumerate(p['plays']):
                    if play._included_path is not None:
                        loader.set_basedir(play._included_path)
                    else:
                        pb_dir = os.path.realpath(
                            os.path.dirname(p['playbook']))
                        loader.set_basedir(pb_dir)

                    msg = "\n  play #%d (%s): %s" % (idx + 1, ','.join(
                        play.hosts), play.name)
                    mytags = set(play.tags)
                    msg += '\tTAGS: [%s]' % (','.join(mytags))

                    if self.options.listhosts:
                        playhosts = set(inventory.get_hosts(play.hosts))
                        msg += "\n    pattern: %s\n    hosts (%d):" % (
                            play.hosts, len(playhosts))
                        for host in playhosts:
                            msg += "\n      %s" % host

                    display.display(msg)

                    all_tags = set()
                    if self.options.listtags or self.options.listtasks:
                        taskmsg = ''
                        if self.options.listtasks:
                            taskmsg = '    tasks:\n'

                        def _process_block(b):
                            taskmsg = ''
                            for task in b.block:
                                if isinstance(task, Block):
                                    taskmsg += _process_block(task)
                                else:
                                    if task.action == 'meta':
                                        continue

                                    all_tags.update(task.tags)
                                    if self.options.listtasks:
                                        cur_tags = list(
                                            mytags.union(set(task.tags)))
                                        cur_tags.sort()
                                        if task.name:
                                            taskmsg += "      %s" % task.get_name(
                                            )
                                        else:
                                            taskmsg += "      %s" % task.action
                                        taskmsg += "\tTAGS: [%s]\n" % ', '.join(
                                            cur_tags)

                            return taskmsg

                        all_vars = variable_manager.get_vars(play=play)
                        play_context = PlayContext(play=play,
                                                   options=self.options)
                        for block in play.compile():
                            block = block.filter_tagged_tasks(
                                play_context, all_vars)
                            if not block.has_tasks():
                                continue
                            taskmsg += _process_block(block)

                        if self.options.listtags:
                            cur_tags = list(mytags.union(all_tags))
                            cur_tags.sort()
                            taskmsg += "      TASK TAGS: [%s]\n" % ', '.join(
                                cur_tags)

                        display.display(taskmsg)

            return 0
        else:
            return results
Exemplo n.º 31
0
        ansible_vars_path = None
        inventory_path = None
    vars_file = conf.write_ansible_vars(
                    dstname=ansible_vars_path)
    inventory_file = conf.write_ansible_inventory(dstname=inventory_path)
    exit_code = 0

    if not options.no_ansible_galaxy:
        print("[+] launching ansible-galaxy")
        default_opts = ["ansible-galaxy"]
        default_opts += ["install"]
        default_opts += ["-r", "ansible-requirements.yml"]
        default_opts += ["--force"]
        galaxy_cli = GalaxyCLI(default_opts)
        galaxy_cli.parse()
        exit_code = galaxy_cli.run()
        if exit_code:
            clean_and_exit(tmpdir, exit_code)

    if not options.no_ansible:
        print("[+] launching ansible-playbook")
        default_opts = ["ansible-playbook"]
        default_opts += ["-i", "default_groups"]
        default_opts += ["-i", inventory_file]
        default_opts += ["-e", "@{}".format(vars_file)]
        if '-u' not in options.ansible_args:
            default_opts += ["-u", "vagrant"]
        if options.offline:
            default_opts += [
                "--module-path",
                "ansible_plugins/modules:offline/ansible_modules/offline"]
Exemplo n.º 32
0
def install_ansible_requirements():
    cmd = ['ansible-galaxy', 'install', '-r', 'ansible-requirements.yml']
    cli = GalaxyCLI(cmd)
    sys.argv = cmd
    cli.parse()
    return cli.run()
Exemplo n.º 33
0
    if (options.no_ansible_galaxy and options.no_ansible):
        ansible_vars_path = None
        inventory_path = None
    vars_file = conf.write_ansible_vars(dstname=ansible_vars_path)
    inventory_file = conf.write_ansible_inventory(dstname=inventory_path)
    exit_code = 0

    if not options.no_ansible_galaxy:
        print("[+] launching ansible-galaxy")
        default_opts = ["ansible-galaxy"]
        default_opts += ["install"]
        default_opts += ["-r", "ansible-requirements.yml"]
        default_opts += ["--force"]
        galaxy_cli = GalaxyCLI(default_opts)
        galaxy_cli.parse()
        exit_code = galaxy_cli.run()
        if exit_code:
            clean_and_exit(tmpdir, exit_code)

    if not options.no_ansible:
        print("[+] launching ansible-playbook")
        default_opts = ["ansible-playbook"]
        default_opts += ["-i", "default_groups"]
        default_opts += ["-i", inventory_file]
        default_opts += ["-e", "@{}".format(vars_file)]
        if '-u' not in options.ansible_args:
            default_opts += ["-u", "vagrant"]
        if options.offline:
            default_opts += [
                "--module-path",
                "ansible_plugins/modules:offline/ansible_modules/offline"
Exemplo n.º 34
0
def test_invalid_collection_name_init(name):
    expected = "Invalid collection name '%s', name must be in the format <namespace>.<collection>" % name

    gc = GalaxyCLI(args=['ansible-galaxy', 'collection', 'init', name])
    with pytest.raises(AnsibleError, match=expected):
        gc.run()