def RunKubectl(args): """Runs a kubectl command with the cluster referenced by this client. Args: args: command line arguments to pass to kubectl Returns: The contents of stdout if the return code is 0, stderr (or a fabricated error if stderr is empty) otherwise """ cmd = [util.CheckKubectlInstalled()] cmd.extend(args) out = io.StringIO() err = io.StringIO() env = _GetEnvs() returncode = execution_utils.Exec(cmd, no_exit=True, out_func=out.write, err_func=err.write, in_str=None, env=env) if returncode != 0 and not err.getvalue(): err.write('kubectl exited with return code {}'.format(returncode)) return out.getvalue() if returncode == 0 else None, err.getvalue( ) if returncode != 0 else None
def TryDeleteNamespace(args): """Delete the namespace in the cluster that contains the connect agent. Args: args: an argparse namespace. All arguments that were provided to this command invocation. """ # The namespace is created by # //cloud/kubernetes/hub/enrollment/connect_agent.go namespace = 'gke-connect-{0}'.format( properties.VALUES.core.project.GetOrFail()) cleanup_msg = 'please delete namespace {0} manually in your cluster.'.format( namespace) # Warn if kubectl is not installed. if not c_util.CheckKubectlInstalled(): log.warning('kubectl not installed. {0}'.format(cleanup_msg)) return try: kubeconfig, context = GetKubeconfigAndContext(args) except calliope_exceptions.MinimumArgumentException: log.warning( 'No Kubeconfig specified and $KUBECONFIG is not set. {0}'.format( cleanup_msg)) return cmd = ['delete', 'namespaces', namespace] out, err, returncode = RunKubectl(kubeconfig, context, cmd, '') log.status.Print(out) if returncode != 0: log.warning('Failed to delete namespace {0}. {1}'.format( err, cleanup_msg))
def PopulateMembership(ref, args, request): """Populate membership object with metadata read from the cluster. Args: ref: reference to the membership object. args: command line arguments. request: API request to be issued Returns: modified request """ kubeconfig, context = GetKubeconfigAndContext(args) cmd = [ 'get', 'namespace', 'kube-system', '-o', 'jsonpath=\'{.metadata.uid}\'' ] membership = GetMembership(ref) # Warn if kubectl is not installed. if not c_util.CheckKubectlInstalled(): raise c_util.Error('kubectl not installed.') out, err, returncode = RunKubectl(kubeconfig, context, cmd, '') if returncode != 0: raise c_util.Error('Failed to get the UID of cluster: {0}'.format(err)) uuid = out.replace("'", '') membership.name = uuid request.membershipId = membership.name request.membership = membership return request
def _RunKubectl(self, args, stdin=None): """Runs a kubectl command with the cluster referenced by this client. Args: args: command line arguments to pass to kubectl stdin: text to be passed to kubectl via stdin Returns: The contents of stdout if the return code is 0, stderr (or a fabricated error if stderr is empty) otherwise """ cmd = [c_util.CheckKubectlInstalled()] if self.context: cmd.extend(['--context', self.context]) if self.kubeconfig: cmd.extend(['--kubeconfig', self.kubeconfig]) cmd.extend(['--request-timeout', self.kubectl_timeout]) cmd.extend(args) out = io.StringIO() err = io.StringIO() returncode = execution_utils.Exec(cmd, no_exit=True, out_func=out.write, err_func=err.write, in_str=stdin) if returncode != 0 and not err.getvalue(): err.write('kubectl exited with return code {}'.format(returncode)) return out.getvalue() if returncode == 0 else None, err.getvalue( ) if returncode != 0 else None
def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Raises: util.Error: if the cluster is unreachable or not running. """ util.CheckKubectlInstalled() adapter = self.context['api_adapter'] location_get = self.context['location_get'] location = location_get(args) cluster_ref = adapter.ParseCluster(args.name, location) if getattr(args, 'region', None): message = messages.NonGAFeatureUsingV1APIWarning( self._release_track) if message: console_io.PromptContinue(message=message, cancel_on_no=True) log.status.Print('Fetching cluster endpoint and auth data.') # Call DescribeCluster to get auth info and cache for next time cluster = adapter.GetCluster(cluster_ref) auth = cluster.masterAuth has_creds = (auth and ((auth.clientCertificate and auth.clientKey) or (auth.username and auth.password))) if not has_creds and not util.ClusterConfig.UseGCPAuthProvider( cluster): raise util.Error( 'get-credentials requires edit permission on {0}'.format( cluster_ref.projectId)) if not adapter.IsRunning(cluster): log.warn(NOT_RUNNING_MSG.format(cluster_ref.clusterId)) util.ClusterConfig.Persist(cluster, cluster_ref.projectId)
def _RunKubectlDiff(self, args, stdin=None): """Runs a kubectl diff command with the specified args. Args: args: command line arguments to pass to kubectl stdin: text to be passed to kubectl via stdin Returns: The contents of stdout if the return code is 1, stderr (or a fabricated error if stderr is empty) otherwise """ cmd = [c_util.CheckKubectlInstalled()] if self.context: cmd.extend(['--context', self.context]) if self.kubeconfig: cmd.extend(['--kubeconfig', self.kubeconfig]) cmd.extend(['--request-timeout', self.kubectl_timeout]) cmd.extend(args) out = io.StringIO() err = io.StringIO() returncode = execution_utils.Exec(cmd, no_exit=True, out_func=out.write, err_func=err.write, in_str=stdin) # kubectl diff return is different with other CLI. # Exit status: 0 No differences were found. 1 Differences were found. # >1 Kubectl or diff failed with an error. return out.getvalue() if returncode == 1 else None, err.getvalue( ) if returncode > 1 else None
def _CheckPreqs(private_endpoint=False): """Checks the prerequisites to run get-credentials commands.""" util.CheckKubectlInstalled() if not private_endpoint: project_id = properties.VALUES.core.project.GetOrFail() connect_gateway_util.CheckGatewayApiEnablement( project_id, _GetConnectGatewayEndpoint())
def __init__(self, api_adapter, gke_uri, gke_cluster, kubeconfig, internal_ip, cross_connect_subnetwork, private_endpoint_fqdn, context): """Constructor for KubeconfigProcessor. Args: api_adapter: the GKE api adapter used for running kubernetes commands gke_uri: the URI of the GKE cluster; for example, 'https://container.googleapis.com/v1/projects/my-project/locations/us-central1-a/clusters/my-cluster' gke_cluster: the "location/name" of the GKE cluster. The location can be a zone or a region for e.g `us-central1-a/my-cluster` kubeconfig: the kubeconfig path internal_ip: whether to persist the internal IP of the endpoint. cross_connect_subnetwork: full path of the cross connect subnet whose endpoint to persist (optional) private_endpoint_fqdn: whether to persist the private fqdn. context: the context to use Raises: exceptions.Error: if kubectl is not installed """ self.api_adapter = api_adapter self.gke_uri = gke_uri self.gke_cluster = gke_cluster self.kubeconfig = kubeconfig self.internal_ip = internal_ip self.cross_connect_subnetwork = cross_connect_subnetwork self.private_endpoint_fqdn = private_endpoint_fqdn self.context = context # Warn if kubectl is not installed. if not c_util.CheckKubectlInstalled(): raise exceptions.Error('kubectl not installed.') self.gke_cluster_self_link = None self.gke_cluster_uri = None
def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Raises: util.Error: if the cluster is unreachable or not running. """ util.CheckKubectlInstalled() adapter = self.context['api_adapter'] cluster_ref = adapter.ParseCluster(args.name) log.status.Print('Fetching cluster endpoint and auth data.') # Call DescribeCluster to get auth info and cache for next time cluster = adapter.GetCluster(cluster_ref) auth = cluster.masterAuth has_creds = (auth and ((auth.clientCertificate and auth.clientKey) or (auth.username and auth.password))) if not has_creds and not util.ClusterConfig.UseGCPAuthProvider( cluster): raise util.Error( 'get-credentials requires edit permission on {0}'.format( cluster_ref.projectId)) if not adapter.IsRunning(cluster): log.error( 'cluster %s is not running. The kubernetes API will probably be ' 'unreachable.' % cluster_ref.clusterId) util.ClusterConfig.Persist(cluster, cluster_ref.projectId)
def _RunKubectl(self, args, stdin=None): """Runs a kubectl command with the cluster referenced by this client. Args: args: command line arguments to pass to kubectl stdin: text to be passed to kubectl via stdin Returns: The contents of stdout if the return code is 0, stderr (or a fabricated error if stderr is empty) otherwise """ cmd = [ c_util.CheckKubectlInstalled(), '--context', self.context, '--kubeconfig', self.kubeconfig, '--request-timeout', self.kubectl_timeout ] cmd.extend(args) p = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate(stdin) if p.returncode != 0 and not err: err = 'kubectl exited with return code {}'.format(p.returncode) return out if p.returncode == 0 else None, err if p.returncode != 0 else None
def PopulateMembership(ref, args, request): """Populate membership object with metadata read from the cluster. Args: ref: reference to the membership object. args: command line arguments. request: API request to be issued Returns: modified request """ kubeconfig, context = GetKubeconfigAndContext(args) cmd = [ 'get', 'namespace', 'kube-system', '-o', 'jsonpath=\'{.metadata.uid}\'' ] membership = GetMembership(ref) # Warn if kubectl is not installed and ask user to manually fill in # resource_id field. if not c_util.CheckKubectlInstalled(): raise c_util.Error('kubectl not installed') out, err, returncode = RunKubectl(kubeconfig, context, cmd, '') if returncode != 0: raise c_util.Error('Failed to get the UID of cluster: {0}'.format(err)) membership.name = out membership.endpoint = core_apis.GetMessagesModule( 'gkehub', 'v1beta1').MembershipEndpoint(resourceId=out) request.membershipId = membership.name request.membership = membership args.membershipsId = membership.name return request
def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Raises: util.Error: if the cluster is unreachable or not running. """ util.CheckKubectlInstalled() adapter = self.context['api_adapter'] location_get = self.context['location_get'] location = location_get(args) cluster_ref = adapter.ParseCluster(args.name, location) log.status.Print('Fetching cluster endpoint and auth data.') # Call DescribeCluster to get auth info and cache for next time cluster = adapter.GetCluster(cluster_ref) auth = cluster.masterAuth # TODO(b/70856999) Make this consistent with the checks in # api_lib/container/kubeconfig.py. missing_creds = not (auth and auth.clientCertificate and auth.clientKey) if missing_creds and not util.ClusterConfig.UseGCPAuthProvider(): raise util.Error( 'get-credentials requires edit permission on {0}'.format( cluster_ref.projectId)) if not adapter.IsRunning(cluster): log.warning(NOT_RUNNING_MSG.format(cluster_ref.clusterId)) util.ClusterConfig.Persist(cluster, cluster_ref.projectId, args.internal_ip)
def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: Cluster message for the successfully created cluster. Raises: util.Error, if creation failed. """ util.CheckKubectlInstalled() if not args.password: args.password = ''.join( random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(16)) adapter = self.context['api_adapter'] if not args.scopes: args.scopes = [] cluster_ref = adapter.ParseCluster(args.name) options = self.ParseCreateOptions(args) try: operation_ref = adapter.CreateCluster(cluster_ref, options) if not args.wait: return adapter.GetCluster(cluster_ref) adapter.WaitForOperation(operation_ref, 'Creating cluster {0}'.format( cluster_ref.clusterId), timeout_s=args.timeout) cluster = adapter.GetCluster(cluster_ref) except apitools_base.HttpError as error: raise exceptions.HttpException(util.GetError(error)) log.CreatedResource(cluster_ref) # Persist cluster config current_context = kconfig.Kubeconfig.Default().current_context c_config = util.ClusterConfig.Persist(cluster, cluster_ref.projectId, self.cli) if not c_config.has_certs: # Purge config so we retry the cert fetch on next kubectl command util.ClusterConfig.Purge(cluster.name, cluster.zone, cluster_ref.projectId) # reset current context if current_context: kubeconfig = kconfig.Kubeconfig.Default() kubeconfig.SetCurrentContext(current_context) kubeconfig.SaveToFile() raise util.Error( NO_CERTS_ERROR_FMT.format( command=' '.join(args.command_path[:-1] + ['get-credentials', cluster.name]))) return cluster
def _BaseRun(args): """Base operations for `get-config-connector-identity` run command.""" container_util.CheckKubectlInstalled() cluster_id = 'krmapihost-' + args.name location = args.location project_id = args.project or properties.VALUES.core.project.GetOrFail() GetConfigConnectorIdentityForCluster(location, cluster_id, project_id)
def __init__(self): """Constructor for KubeconfigProcessor. Raises: exceptions.Error: if kubectl is not installed """ # Warn if kubectl is not installed. if not c_util.CheckKubectlInstalled(): raise exceptions.Error('kubectl not installed.')
def Run(self, args): util.CheckKubectlInstalled() log.status.Print('Starting to build Gateway kubeconfig...') # Parse Args: get project_id from flag or default project_id = arg_utils.GetFromNamespace( args, '--project', use_defaults=True) log.status.Print('Current project_id: ' + project_id) self.RunIamCheck(project_id) self.ReadClusterMembership(project_id, args.MEMBERSHIP) self.GenerateKubeconfig(project_id, args.MEMBERSHIP)
def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: Cluster message for the successfully created cluster. Raises: util.Error, if creation failed. """ util.CheckKubectlInstalled() if not args.password: args.password = ''.join( random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(16)) adapter = self.context['api_adapter'] if not args.scopes: args.scopes = [] cluster_ref = adapter.ParseCluster(args.name) options = self.ParseCreateOptions(args) operation = None try: operation_ref = adapter.CreateCluster(cluster_ref, options) if not args.wait: return adapter.GetCluster(cluster_ref) operation = adapter.WaitForOperation(operation_ref, 'Creating cluster {0}'.format( cluster_ref.clusterId), timeout_s=args.timeout) cluster = adapter.GetCluster(cluster_ref) except apitools_exceptions.HttpError as error: raise exceptions.HttpException(util.GetError(error)) log.CreatedResource(cluster_ref) if operation.detail: # Non-empty detail on a DONE create operation should be surfaced as # a warning to end user. log.warning(operation.detail) try: util.ClusterConfig.Persist(cluster, cluster_ref.projectId) except kconfig.MissingEnvVarError as error: log.warning(error.message) return cluster
def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: Cluster message for the successfully created cluster. Raises: util.Error, if creation failed. """ util.CheckKubectlInstalled() adapter = self.context['api_adapter'] if not args.scopes: args.scopes = [] cluster_ref = adapter.ParseCluster(args.name) options = self.ParseCreateOptions(args) if options.enable_kubernetes_alpha: console_io.PromptContinue( message=constants.KUBERNETES_ALPHA_PROMPT, throw_if_unattended=True, cancel_on_no=True) if options.enable_autorepair is not None: log.status.Print( messages.AutoUpdateUpgradeRepairMessage( options.enable_autorepair, 'autorepair')) if options.enable_autoupgrade is not None: log.status.Print( messages.AutoUpdateUpgradeRepairMessage( options.enable_autoupgrade, 'autoupgrade')) operation = None try: operation_ref = adapter.CreateCluster(cluster_ref, options) if flags.GetAsyncValueFromAsyncAndWaitFlags( args. async, args.wait): return adapter.GetCluster(cluster_ref) operation = adapter.WaitForOperation(operation_ref, 'Creating cluster {0}'.format( cluster_ref.clusterId), timeout_s=args.timeout) cluster = adapter.GetCluster(cluster_ref)
def TemporaryKubeconfig(location_id, cluster_id): """Context manager that manages a temporary kubeconfig file for a GKE cluster. The kubeconfig file will be automatically created and destroyed and will contain only the credentials for the specified GKE cluster. The 'KUBECONFIG' value in `os.environ` will be temporarily updated with the temporary kubeconfig's path. Consequently, subprocesses started with googlecloudsdk.core.execution_utils.Exec while in this context manager will see the temporary KUBECONFIG environment variable. Args: location_id: string, the id of the location to which the cluster belongs cluster_id: string, the id of the cluster Raises: Error: If unable to get credentials for kubernetes cluster. Returns: the path to the temporary kubeconfig file Yields: Due to b/73533917, linter crashes without yields. """ gke_util.CheckKubectlInstalled() with files.TemporaryDirectory() as tempdir: kubeconfig = os.path.join(tempdir, 'kubeconfig') old_kubeconfig = encoding.GetEncodedValue(os.environ, KUBECONFIG_ENV_VAR_NAME) try: encoding.SetEncodedValue(os.environ, KUBECONFIG_ENV_VAR_NAME, kubeconfig) gke_api = gke_api_adapter.NewAPIAdapter(GKE_API_VERSION) cluster_ref = gke_api.ParseCluster(cluster_id, location_id) cluster = gke_api.GetCluster(cluster_ref) auth = cluster.masterAuth missing_creds = not (auth and auth.clientCertificate and auth.clientKey) if missing_creds and not gke_util.ClusterConfig.UseGCPAuthProvider( ): raise Error( 'Unable to get cluster credentials. User must have edit ' 'permission on {}'.format(cluster_ref.projectId)) gke_util.ClusterConfig.Persist(cluster, cluster_ref.projectId) yield kubeconfig finally: encoding.SetEncodedValue(os.environ, KUBECONFIG_ENV_VAR_NAME, old_kubeconfig)
def _BaseRun(args): """Base operations for `get-credentials` run command.""" container_util.CheckKubectlInstalled() cluster_id = 'krmapihost-' + args.name location_id = args.location project = None gke_api = container_api_adapter.NewAPIAdapter('v1') log.status.Print('Fetching cluster endpoint and auth data.') cluster_ref = gke_api.ParseCluster(cluster_id, location_id, project) cluster = gke_api.GetCluster(cluster_ref) if not gke_api.IsRunning(cluster): log.warning(NOT_RUNNING_MSG.format(cluster_ref.clusterId)) return cluster, cluster_ref
def __init__(self, flags): """Constructor for KubernetesClient. Args: flags: the flags passed to the enclosing command Raises: exceptions.Error: if the client cannot be configured calliope_exceptions.MinimumArgumentException: if a kubeconfig file cannot be deduced from the command line flags or environment """ self.kubectl_timeout = '20s' # Warn if kubectl is not installed. if not c_util.CheckKubectlInstalled(): raise exceptions.Error('kubectl not installed.') self.kubeconfig, self.context = self._GetKubeconfigAndContext( flags.kubeconfig_file, flags.context)
def Run(self, args): container_util.CheckKubectlInstalled() project_id = properties.VALUES.core.project.GetOrFail() location = getattr(args, 'location', 'global') if location is None: location = 'global' log.status.Print('Starting to build Gateway kubeconfig...') log.status.Print('Current project_id: ' + project_id) self.RunIamCheck(project_id) hub_endpoint_override = properties.VALUES.api_endpoint_overrides.AllValues( ).get('gkehub', '') # API enablement is only done once per environment, regardless of which # region is being accessed. cg_util.CheckGatewayApiEnablement( project_id, util.GetConnectGatewayServiceName(hub_endpoint_override, None)) membership = self.ReadClusterMembership(project_id, location, args.MEMBERSHIP) resource_type = 'memberships' fleetgke = getattr(args, 'fleetgke', False) # TODO(b/232276553): Blocklist prober project upon promotion of this flag to # default behavior. if fleetgke: if not (hasattr(membership, 'endpoint') and hasattr(membership.endpoint, 'gkeCluster') and membership.endpoint.gkeCluster): raise memberships_errors.InvalidFlagValueError( "Flag '--fleetgke' provided, but cluster is not a registered GKE cluster." ) resource_type = 'fleetgke' self.GenerateKubeconfig( util.GetConnectGatewayServiceName(hub_endpoint_override, location), project_id, location, resource_type, args.MEMBERSHIP) msg = 'A new kubeconfig entry \"' + KUBECONTEXT_FORMAT.format( project=project_id, location=location, membership=args.MEMBERSHIP ) + '\" has been generated and set as the current context.' log.status.Print(msg)
def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Raises: util.Error: if the cluster is unreachable or not running. """ util.CheckKubectlInstalled() adapter = self.context['api_adapter'] location_get = self.context['location_get'] location = location_get(args) cluster_ref = adapter.ParseCluster(args.name, location) log.status.Print('Fetching cluster endpoint and auth data.') # Call DescribeCluster to get auth info and cache for next time cluster = adapter.GetCluster(cluster_ref) if not adapter.IsRunning(cluster): log.warning(NOT_RUNNING_MSG.format(cluster_ref.clusterId)) util.ClusterConfig.Persist(cluster, cluster_ref.projectId)
def _BaseRun(args, context): """Base operations for `get-credentials` run command.""" util.CheckKubectlInstalled() adapter = context['api_adapter'] location_get = context['location_get'] location = location_get(args) cluster_ref = adapter.ParseCluster(args.name, location) log.status.Print('Fetching cluster endpoint and auth data.') # Call DescribeCluster to get auth info and cache for next time cluster = adapter.GetCluster(cluster_ref) auth = cluster.masterAuth # TODO(b/70856999) Make this consistent with the checks in # api_lib/container/kubeconfig.py. missing_creds = not (auth and auth.clientCertificate and auth.clientKey) if missing_creds and not util.ClusterConfig.UseGCPAuthProvider(): raise util.Error('get-credentials requires edit permission on {0}'.format( cluster_ref.projectId)) if not adapter.IsRunning(cluster): log.warning(NOT_RUNNING_MSG.format(cluster_ref.clusterId)) return cluster, cluster_ref
def DeployConnectAgent(response, args): """Python hook to deploy connect agent. Args: response: response to be returned. args: arguments of the command. Returns: modified response """ if args.agent_deployed: return response # project = properties.VALUES.core.project.GetOrFail() # Exit if kubectl is not installed. if not c_util.CheckKubectlInstalled(): log.warning( 'kubectl not installed, could not install the connect agent. ') return # TODO(b/123907152): implement the manifest after Docker image is ready. return response
def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Raises: util.Error: if the cluster is unreachable or not running. """ util.CheckKubectlInstalled() adapter = self.context['api_adapter'] cluster_ref = adapter.ParseCluster(args.name) log.status.Print('Fetching cluster endpoint and auth data.') # Call DescribeCluster to get auth info and cache for next time cluster = adapter.GetCluster(cluster_ref) if not adapter.IsRunning(cluster): log.error( 'cluster %s is not running. The kubernetes API will probably be ' 'unreachable.' % cluster_ref.clusterId) util.ClusterConfig.Persist(cluster, cluster_ref.projectId, self.cli)
def Run(self, args): """Runs the get-credentials command.""" container_util.CheckKubectlInstalled() cluster_ref = resources.REGISTRY.ParseRelativeName( args.CONCEPTS.cluster.Parse().RelativeName(), collection='edgecontainer.projects.locations.clusters') messages = util.GetMessagesModule(self.ReleaseTrack()) cluster_client = util.GetClientInstance(self.ReleaseTrack()) req = messages.EdgecontainerProjectsLocationsClustersGetRequest( name=cluster_ref.RelativeName()) resp = cluster_client.projects_locations_clusters.Get(req) context = kubeconfig.GenerateContext(cluster_ref.projectsId, cluster_ref.locationsId, cluster_ref.clustersId) cmd_args = kubeconfig.GenerateAuthProviderCmdArgs( self.ReleaseTrack(), cluster_ref.clustersId, cluster_ref.projectsId, cluster_ref.locationsId) kubeconfig.GenerateKubeconfig(resp, context, args.auth_provider_cmd_path, cmd_args)
def Run(self, args): util.CheckKubectlInstalled() # Parse Args: get project_id from flag or default project_id = arg_utils.GetFromNamespace(args, '--project', use_defaults=True) if project_id is None: msg = """\ The required property [project] is not currently set. You may set it for your current workspace by running: \n $ gcloud config set project VALUE""" raise Exception(msg) log.status.Print('Starting to build Gateway kubeconfig...') log.status.Print('Current project_id: ' + project_id) self.RunIamCheck(project_id) self.ReadClusterMembership(project_id, args.MEMBERSHIP) self.GenerateKubeconfig(project_id, args.MEMBERSHIP) msg = 'A new kubeconfig entry \"' + KUBECONTEXT_FORMAT.format( project=project_id, membership=args.MEMBERSHIP ) + '\" has been generated and set as the current context.' log.status.Print(msg)
def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: Cluster message for the successfully created cluster. Raises: util.Error, if creation failed. """ util.CheckKubectlInstalled() if not args.password: args.password = ''.join( random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(16)) adapter = self.context['api_adapter'] if not args.scopes: args.scopes = [] cluster_ref = adapter.ParseCluster(args.name) options = self.ParseCreateOptions(args) operation = None try: operation_ref = adapter.CreateCluster(cluster_ref, options) if flags.GetAsyncValueFromAsyncAndWaitFlags( args. async, args.wait): return adapter.GetCluster(cluster_ref) operation = adapter.WaitForOperation(operation_ref, 'Creating cluster {0}'.format( cluster_ref.clusterId), timeout_s=args.timeout) cluster = adapter.GetCluster(cluster_ref)
def DeployConnectAgent(response, args): """Python hook to deploy connect agent. Args: response: response to be returned. args: arguments of the command. Returns: modified response """ if args.agent_deployed: return response # project = properties.VALUES.core.project.GetOrFail() # Exit if kubectl is not installed. if not c_util.CheckKubectlInstalled(): log.warning( 'kubectl not installed, could not install the connect agent. ') return image = args.docker_image if not image: # Get the SHA for the default image. try: digest = ImageDigestForContainerImage(DEFAULT_CONNECT_AGENT_IMAGE, DEFAULT_CONNECT_AGENT_TAG) image = '{}@{}'.format(DEFAULT_CONNECT_AGENT_IMAGE, digest) except Exception as exp: raise c_util.Error( 'could not determine image digest for {}:{}: {}'.format( DEFAULT_CONNECT_AGENT_IMAGE, DEFAULT_CONNECT_AGENT_TAG, exp)) log.status.Print('The agent image that would be used is {}'.format(image)) # TODO(b/123907152): implement the manifest after Docker image is ready. return response