コード例 #1
0
ファイル: test_vm_actions.py プロジェクト: jaczhan/azure-cli
    def test_generate_specfied_ssh_key_files(self):
        _, private_key_file = tempfile.mkstemp()
        public_key_file = private_key_file + '.pub'
        args = mock.MagicMock()
        args.ssh_key_value = public_key_file
        args.generate_ssh_keys = True

        # 1 verify we generate key files if not existing
        validate_ssh_key(args)

        generated_public_key_string = args.ssh_key_value
        self.assertTrue(bool(args.ssh_key_value))
        self.assertTrue(
            _is_valid_ssh_rsa_public_key(generated_public_key_string))
        self.assertTrue(os.path.isfile(private_key_file))

        # 2 verify we load existing key files
        # for convinience we will reuse the generated file in the previous step
        args2 = mock.MagicMock()
        args2.ssh_key_value = generated_public_key_string
        args2.generate_ssh_keys = False
        validate_ssh_key(args2)
        # we didn't regenerate
        self.assertEqual(generated_public_key_string, args.ssh_key_value)

        # 3 verify we do not generate unless told so
        _, private_key_file2 = tempfile.mkstemp()
        public_key_file2 = private_key_file2 + '.pub'
        args3 = mock.MagicMock()
        args3.ssh_key_value = public_key_file2
        args3.generate_ssh_keys = False
        with self.assertRaises(CLIError):
            validate_ssh_key(args3)

        # 4 verify file naming if the pub file doesn't end with .pub
        _, public_key_file4 = tempfile.mkstemp()
        public_key_file4 += '1'  # make it nonexisting
        args4 = mock.MagicMock()
        args4.ssh_key_value = public_key_file4
        args4.generate_ssh_keys = True
        validate_ssh_key(args4)
        self.assertTrue(os.path.isfile(public_key_file4 + '.private'))
        self.assertTrue(os.path.isfile(public_key_file4))
コード例 #2
0
    def test_generate_specfied_ssh_key_files(self):
        _, private_key_file = tempfile.mkstemp()
        public_key_file = private_key_file + ".pub"
        args = mock.MagicMock()
        args.ssh_key_value = public_key_file
        args.generate_ssh_keys = True

        # 1 verify we generate key files if not existing
        validate_ssh_key(args)

        generated_public_key_string = args.ssh_key_value
        self.assertTrue(bool(args.ssh_key_value))
        self.assertTrue(_is_valid_ssh_rsa_public_key(generated_public_key_string))
        self.assertTrue(os.path.isfile(private_key_file))

        # 2 verify we load existing key files
        # for convinience we will reuse the generated file in the previous step
        args2 = mock.MagicMock()
        args2.ssh_key_value = generated_public_key_string
        args2.generate_ssh_keys = False
        validate_ssh_key(args2)
        # we didn't regenerate
        self.assertEqual(generated_public_key_string, args.ssh_key_value)

        # 3 verify we do not generate unless told so
        _, private_key_file2 = tempfile.mkstemp()
        public_key_file2 = private_key_file2 + ".pub"
        args3 = mock.MagicMock()
        args3.ssh_key_value = public_key_file2
        args3.generate_ssh_keys = False
        with self.assertRaises(CLIError):
            validate_ssh_key(args3)

        # 4 verify file naming if the pub file doesn't end with .pub
        _, public_key_file4 = tempfile.mkstemp()
        public_key_file4 += "1"  # make it nonexisting
        args4 = mock.MagicMock()
        args4.ssh_key_value = public_key_file4
        args4.generate_ssh_keys = True
        validate_ssh_key(args4)
        self.assertTrue(os.path.isfile(public_key_file4 + ".private"))
        self.assertTrue(os.path.isfile(public_key_file4))
コード例 #3
0
ファイル: custom.py プロジェクト: voellm/azure-cli
def acs_create(resource_group_name,
               deployment_name,
               name,
               ssh_key_value,
               dns_name_prefix=None,
               content_version=None,
               admin_username="******",
               agent_count="3",
               agent_vm_size="Standard_D2_v2",
               location=None,
               master_count="3",
               orchestrator_type="dcos",
               service_principal=None,
               client_secret=None,
               tags=None,
               custom_headers=None,
               raw=False,
               **operation_config):  #pylint: disable=too-many-locals
    """Create a new Acs.
    :param resource_group_name: The name of the resource group. The name
     is case insensitive.
    :type resource_group_name: str
    :param deployment_name: The name of the deployment.
    :type deployment_name: str
    :param dns_name_prefix: Sets the Domain name prefix for the cluster.
     The concatenation of the domain name and the regionalized DNS zone
     make up the fully qualified domain name associated with the public
     IP address.
    :type dns_name_prefix: str
    :param name: Resource name for the container service.
    :type name: str
    :param ssh_key_value: Configure all linux machines with the SSH RSA
     public key string.  Your key should include three parts, for example
    'ssh-rsa AAAAB...snip...UcyupgH azureuser@linuxvm
    :type ssh_key_value: str
    :param content_version: If included it must match the ContentVersion
     in the template.
    :type content_version: str
    :param admin_username: User name for the Linux Virtual Machines.
    :type admin_username: str
    :param agent_count: The number of agents for the cluster.  Note, for
     DC/OS clusters you will also get 1 or 2 public agents in addition to
     these seleted masters.
    :type agent_count: str
    :param agent_vm_size: The size of the Virtual Machine.
    :type agent_vm_size: str
    :param location: Location for VM resources.
    :type location: str
    :param master_count: The number of DC/OS masters for the cluster.
    :type master_count: str
    :param orchestrator_type: The type of orchestrator used to manage the
     applications on the cluster. Possible values include: 'dcos', 'swarm'
    :type orchestrator_type: str or :class:`orchestratorType
     <Default.models.orchestratorType>`
    :param service_principal: The service principal used for cluster authentication
     to Azure APIs. If not specified, it is created for you and stored in the
     ${HOME}/.azure directory.
    :type service_principal: str
    :param client_secret: The secret associated with the service principal. If
     --service-principal is specified, then secret should also be specified. If
     --service-principal is not specified, the secret is auto-generated for you
     and stored in ${HOME}/.azure/ directory.
    :param tags: Tags object.
    :type tags: object
    :param dict custom_headers: headers that will be added to the request
    :param bool raw: returns the direct response alongside the
     deserialized response
    :rtype:
    :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>`
     instance that returns :class:`DeploymentExtended
     <Default.models.DeploymentExtended>`
    :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
     if raw=true
    :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
    """
    if ssh_key_value is not None and not _is_valid_ssh_rsa_public_key(
            ssh_key_value):
        raise CLIError(
            'Provided ssh key ({}) is invalid or non-existent'.format(
                ssh_key_value))

    subscription_id = _get_subscription_id()
    if not dns_name_prefix:
        # Use subscription id to provide uniqueness and prevent DNS name clashes
        dns_name_prefix = '{}-{}-{}'.format(name, resource_group_name,
                                            subscription_id[0:6])

    register_providers()
    groups = _resource_client_factory().resource_groups
    # Just do the get, we don't need the result, it will error out if the group doesn't exist.
    groups.get(resource_group_name)

    if orchestrator_type == 'Kubernetes' or orchestrator_type == 'kubernetes':
        from azure.cli.command_modules.role.custom import _graph_client_factory
        # TODO: This really needs to be broken out and unit tested.
        client = _graph_client_factory()
        if not service_principal:
            # --service-principal not specified, try to load it from local disk
            principalObj = load_acs_service_principal(subscription_id)
            if principalObj:
                service_principal = principalObj.get('service_principal')
                client_secret = principalObj.get('client_secret')
                _validate_service_principal(client, service_principal)
            else:
                # Nothing to load, make one.
                if not client_secret:
                    client_secret = binascii.b2a_hex(
                        os.urandom(10)).decode('utf-8')
                salt = binascii.b2a_hex(os.urandom(3)).decode('utf-8')
                url = 'http://{}.{}.{}.cloudapp.azure.com'.format(
                    salt, dns_name_prefix, location)

                service_principal = _build_service_principal(
                    client, name, url, client_secret)
                logger.info('Created a service principal: %s',
                            service_principal)
                store_acs_service_principal(subscription_id, client_secret,
                                            service_principal)
            # Either way, update the role assignment, this fixes things if we fail part-way through
            if not _add_role_assignment('Owner', service_principal):
                raise CLIError(
                    'Could not create a service principal with the right permissions. Are you an Owner on this project?'
                )
        else:
            # --service-principal specfied, validate --client-secret was too
            if not client_secret:
                raise CLIError(
                    '--client-secret is required if --service-principal is specified'
                )
            _validate_service_principal(client, service_principal)
        return _create_kubernetes(resource_group_name,
                                  deployment_name,
                                  dns_name_prefix,
                                  name,
                                  ssh_key_value,
                                  admin_username=admin_username,
                                  agent_count=agent_count,
                                  agent_vm_size=agent_vm_size,
                                  location=location,
                                  service_principal=service_principal,
                                  client_secret=client_secret)

    ops = get_mgmt_service_client(ACSClient).acs
    return ops.create_or_update(resource_group_name,
                                deployment_name,
                                dns_name_prefix,
                                name,
                                ssh_key_value,
                                content_version=content_version,
                                admin_username=admin_username,
                                agent_count=agent_count,
                                agent_vm_size=agent_vm_size,
                                location=location,
                                master_count=master_count,
                                orchestrator_type=orchestrator_type,
                                tags=tags,
                                custom_headers=custom_headers,
                                raw=raw,
                                operation_config=operation_config)
コード例 #4
0
def acs_create(resource_group_name, deployment_name, name, ssh_key_value, dns_name_prefix=None,
               content_version=None, admin_username="******", agent_count="3",
               agent_vm_size="Standard_D2_v2", location=None, master_count="3",
               orchestrator_type="dcos", service_principal=None, client_secret=None, tags=None,
               custom_headers=None, raw=False,
               **operation_config):  # pylint: disable=too-many-locals
    """Create a new Acs.
    :param resource_group_name: The name of the resource group. The name
     is case insensitive.
    :type resource_group_name: str
    :param deployment_name: The name of the deployment.
    :type deployment_name: str
    :param dns_name_prefix: Sets the Domain name prefix for the cluster.
     The concatenation of the domain name and the regionalized DNS zone
     make up the fully qualified domain name associated with the public
     IP address.
    :type dns_name_prefix: str
    :param name: Resource name for the container service.
    :type name: str
    :param ssh_key_value: Configure all linux machines with the SSH RSA
     public key string.  Your key should include three parts, for example
    'ssh-rsa AAAAB...snip...UcyupgH azureuser@linuxvm
    :type ssh_key_value: str
    :param content_version: If included it must match the ContentVersion
     in the template.
    :type content_version: str
    :param admin_username: User name for the Linux Virtual Machines.
    :type admin_username: str
    :param agent_count: The number of agents for the cluster.  Note, for
     DC/OS clusters you will also get 1 or 2 public agents in addition to
     these selected masters.
    :type agent_count: str
    :param agent_vm_size: The size of the Virtual Machine.
    :type agent_vm_size: str
    :param location: Location for VM resources.
    :type location: str
    :param master_count: The number of masters for the cluster.
    :type master_count: str
    :param orchestrator_type: The type of orchestrator used to manage the
     applications on the cluster. Possible values include: 'dcos', 'swarm'
    :type orchestrator_type: str or :class:`orchestratorType
     <Default.models.orchestratorType>`
    :param service_principal: The service principal used for cluster authentication
     to Azure APIs. If not specified, it is created for you and stored in the
     ${HOME}/.azure directory.
    :type service_principal: str
    :param client_secret: The secret associated with the service principal. If
     --service-principal is specified, then secret should also be specified. If
     --service-principal is not specified, the secret is auto-generated for you
     and stored in ${HOME}/.azure/ directory.
    :param tags: Tags object.
    :type tags: object
    :param dict custom_headers: headers that will be added to the request
    :param bool raw: returns the direct response alongside the
     deserialized response
    :rtype:
    :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>`
     instance that returns :class:`DeploymentExtended
     <Default.models.DeploymentExtended>`
    :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
     if raw=true
    :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
    """
    if ssh_key_value is not None and not _is_valid_ssh_rsa_public_key(ssh_key_value):
        raise CLIError('Provided ssh key ({}) is invalid or non-existent'.format(ssh_key_value))

    subscription_id = _get_subscription_id()
    if not dns_name_prefix:
        # Use subscription id to provide uniqueness and prevent DNS name clashes
        dns_name_prefix = '{}-{}-{}'.format(name, resource_group_name, subscription_id[0:6])

    register_providers()
    groups = _resource_client_factory().resource_groups
    # Just do the get, we don't need the result, it will error out if the group doesn't exist.
    groups.get(resource_group_name)

    if orchestrator_type == 'Kubernetes' or orchestrator_type == 'kubernetes':
        # TODO: This really needs to be broken out and unit tested.
        client = _graph_client_factory()
        if not service_principal:
            # --service-principal not specified, try to load it from local disk
            principalObj = load_acs_service_principal(subscription_id)
            if principalObj:
                service_principal = principalObj.get('service_principal')
                client_secret = principalObj.get('client_secret')
                _validate_service_principal(client, service_principal)
            else:
                # Nothing to load, make one.
                if not client_secret:
                    client_secret = binascii.b2a_hex(os.urandom(10)).decode('utf-8')
                salt = binascii.b2a_hex(os.urandom(3)).decode('utf-8')
                url = 'http://{}.{}.{}.cloudapp.azure.com'.format(salt, dns_name_prefix, location)

                service_principal = _build_service_principal(client, name, url, client_secret)
                logger.info('Created a service principal: %s', service_principal)
                store_acs_service_principal(subscription_id, client_secret, service_principal)
            # Either way, update the role assignment, this fixes things if we fail part-way through
            if not _add_role_assignment('Owner', service_principal):
                raise CLIError(
                    'Could not create a service principal with the right permissions. Are you an Owner on this project?')
        else:
            # --service-principal specfied, validate --client-secret was too
            if not client_secret:
                raise CLIError('--client-secret is required if --service-principal is specified')
            _validate_service_principal(client, service_principal)
        return _create_kubernetes(resource_group_name, deployment_name, dns_name_prefix, name,
                                  ssh_key_value, admin_username=admin_username,
                                  agent_count=agent_count, agent_vm_size=agent_vm_size,
                                  location=location, service_principal=service_principal,
                                  client_secret=client_secret)

    ops = get_mgmt_service_client(ACSClient).acs
    return ops.create_or_update(resource_group_name, deployment_name, dns_name_prefix, name,
                                ssh_key_value, content_version=content_version,
                                admin_username=admin_username, agent_count=agent_count,
                                agent_vm_size=agent_vm_size, location=location,
                                master_count=master_count, orchestrator_type=orchestrator_type,
                                tags=tags, custom_headers=custom_headers, raw=raw,
                                operation_config=operation_config)