There are two string operators. The first is the concatenation operator (‘.‘), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator (‘.=‘), which appends the argument on the right side to the argument on the left side. Show
Examples : Input : string1: Hello string2 : World! Output : HelloWorld! Input : string1: geeksfor string2: geeks Output : geeksforgeeks Code #1: PHP
HelloWorld!0
HelloWorld!1 HelloWorld!2 = HelloWorld!4 HelloWorld!0
HelloWorld!6 HelloWorld!7 = $a John Carter!0 HelloWorld!2 HelloWorld!0
John Carter!3 John Carter!4 John Carter!5 HelloWorld!0 John Carter!7 Output HelloWorld! Time complexity : O(n) Code #2 : PHP
Hello World!0 = Hello World!2 HelloWorld!0
HelloWorld!1 Hello World!5 = Hello World!7 HelloWorld!0
HelloWorld!6 HelloWorld!7 = Hello World!0 John Carter!0 GeeksforGeeks4 John Carter!0 Hello World!5 HelloWorld!0
John Carter!3 John Carter!4 John Carter!5 HelloWorld!0 John Carter!7 Output John Carter! Time complexity : O(n) Code #3 : PHP
HelloWorld!0
HelloWorld!0
John Carter!4 // First String 6HelloWorld!0 John Carter!7 Output Hello World! Time complexity : O(n) Code #4 : PHP
HelloWorld!0
HelloWorld!1 HelloWorld!2 = $a 8HelloWorld!0
HelloWorld!7 = = 3HelloWorld!0
John Carter!4 John Carter!5 HelloWorld!0 John Carter!7 Output GeeksforGeeks Time complexity : O(n) PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. A Secret is an object that contains a small amount of sensitive data such as a password, a token, or a key. Such information might otherwise be put in a Pod specification or in a . Using a Secret means that you don't need to include confidential data in your application code. Because Secrets can be created independently of the Pods that use them, there is less risk of the Secret (and its data) being exposed during the workflow of creating, viewing, and editing Pods. Kubernetes, and applications that run in your cluster, can also take additional precautions with Secrets, such as avoiding writing secret data to nonvolatile storage. Secrets are similar to ConfigMaps but are specifically intended to hold confidential data. Caution: Kubernetes Secrets are, by default, stored unencrypted in the API server's underlying data store (etcd). Anyone with API access can retrieve or modify a Secret, and so can anyone with access to etcd. Additionally, anyone who is authorized to create a Pod in a namespace can use that access to read any Secret in that namespace; this includes indirect access such as the ability to create a Deployment. In order to safely use Secrets, take at least the following steps: For more guidelines to manage and improve the security of your Secrets, refer to Good practices for Kubernetes Secrets. See for more details. Uses for SecretsThere are three main ways for a Pod to use a Secret: The Kubernetes control plane also uses Secrets; for example, are a mechanism to help automate node registration. Alternatives to SecretsRather than using a Secret to protect confidential data, you can pick from alternatives. Here are some of your options:
You can also combine two or more of those options, including the option to use Secret objects themselves. For example: implement (or deploy) an operator that fetches short-lived session tokens from an external service, and then creates Secrets based on those short-lived session tokens. Pods running in your cluster can make use of the session tokens, and operator ensures they are valid. This separation means that you can run Pods that are unaware of the exact mechanisms for issuing and refreshing those session tokens. Working with SecretsCreating a SecretThere are several options to create a Secret: Constraints on Secret names and dataThe name of a Secret object must be a valid . You can specify the 1 and/or the 2 field when creating a configuration file for a Secret. The 1 and the 2 fields are optional. The values for all keys in the 1 field have to be base64-encoded strings. If the conversion to base64 string is not desirable, you can choose to specify the 2 field instead, which accepts arbitrary strings as values.The keys of 1 and 2 must consist of alphanumeric characters, 9, 0 or 1. All key-value pairs in the 2 field are internally merged into the 1 field. If a key appears in both the 1 and the 2 field, the value specified in the 2 field takes precedence.Size limitIndividual secrets are limited to 1MiB in size. This is to discourage creation of very large secrets that could exhaust the API server and kubelet memory. However, creation of many smaller secrets could also exhaust memory. You can use a resource quota to limit the number of Secrets (or other resources) in a namespace. Editing a SecretYou can edit an existing Secret unless it is . To edit a Secret, use one of the following methods: You can also edit the data in a Secret using the . However, this method creates a new 7 object with the edited data.Depending on how you created the Secret, as well as how the Secret is used in your Pods, updates to existing 7 objects are propagated automatically to Pods that use the data. For more information, refer to .Using a SecretSecrets can be mounted as data volumes or exposed as environment variables to be used by a container in a Pod. Secrets can also be used by other parts of the system, without being directly exposed to the Pod. For example, Secrets can hold credentials that other parts of the system should use to interact with external systems on your behalf. Secret volume sources are validated to ensure that the specified object reference actually points to an object of type Secret. Therefore, a Secret needs to be created before any Pods that depend on it. If the Secret cannot be fetched (perhaps because it does not exist, or due to a temporary lack of connection to the API server) the kubelet periodically retries running that Pod. The kubelet also reports an Event for that Pod, including details of the problem fetching the Secret. Optional SecretsWhen you define a container environment variable based on a Secret, you can mark it as optional. The default is for the Secret to be required. None of a Pod's containers will start until all non-optional Secrets are available. If a Pod references a specific key in a Secret and that Secret does exist, but is missing the named key, the Pod fails during startup. Using Secrets as files from a PodIf you want to access data from a Secret in a Pod, one way to do that is to have Kubernetes make the value of that Secret be available as a file inside the filesystem of one or more of the Pod's containers. To configure that, you:
This is an example of a Pod that mounts a Secret named 6 in a volume:
Each Secret you want to use needs to be referred to in 7.If there are multiple containers in the Pod, then each container needs its own 8 block, but only one 7 is needed per Secret.Note: Versions of Kubernetes before v1.22 automatically created credentials for accessing the Kubernetes API. This older mechanism was based on creating token Secrets that could then be mounted into running Pods. In more recent versions, including Kubernetes v1.26, API credentials are obtained directly by using the TokenRequest API, and are mounted into Pods using a . The tokens obtained using this method have bounded lifetimes, and are automatically invalidated when the Pod they are mounted into is deleted. You can still a service account token Secret; for example, if you need a token that never expires. However, using the TokenRequest subresource to obtain a token to access the API is recommended instead. You can use the command to obtain a token from the 1 API.Projection of Secret keys to specific pathsYou can also control the paths within the volume where Secret keys are projected. You can use the 2 field to change the target path of each key:
What will happen:
If 2 is used, only keys specified in 9 are projected. To consume all keys from the Secret, all of them must be listed in the 9 field.If you list keys explicitly, then all listed keys must exist in the corresponding Secret. Otherwise, the volume is not created. Secret files permissionsYou can set the POSIX file access permission bits for a single Secret key. If you don't specify any permissions, 1 is used by default. You can also set a default mode for the entire Secret volume and override per key if needed.For example, you can specify a default mode like this:
The secret is mounted on 2; all the files created by the secret volume mount have permission 3.Note: If you're defining a Pod or a Pod template using JSON, beware that the JSON specification doesn't support octal notation. You can use the decimal value for the 4 (for example, 0400 in octal is 256 in decimal) instead. If you're writing YAML, you can write the 4 in octal.Consuming Secret values from volumesInside the container that mounts a secret volume, the secret keys appear as files. The secret values are base64 decoded and stored inside these files. This is the result of commands executed inside the container from the example above: The output is similar to:
The output is similar to:
The output is similar to:
The program in a container is responsible for reading the secret data from these files, as needed. When a volume contains data from a Secret, and that Secret is updated, Kubernetes tracks this and updates the data in the volume, using an eventually-consistent approach. Note: A container using a Secret as a volume mount does not receive automated Secret updates. The kubelet keeps a cache of the current keys and values for the Secrets that are used in volumes for pods on that node. You can configure the way that the kubelet detects changes from the cached values. The 6 field in the kubelet configuration controls which strategy the kubelet uses. The default strategy is 7.Updates to Secrets can be either propagated by an API watch mechanism (the default), based on a cache with a defined time-to-live, or polled from the cluster API server on each kubelet synchronisation loop. As a result, the total delay from the moment when the Secret is updated to the moment when new keys are projected to the Pod can be as long as the kubelet sync period + cache propagation delay, where the cache propagation delay depends on the chosen cache type (following the same order listed in the previous paragraph, these are: watch propagation delay, the configured cache TTL, or zero for direct polling). Using Secrets as environment variablesTo use a Secret in an environment variable in a Pod:
This is an example of a Pod that uses a Secret via environment variables:
Invalid environment variablesSecrets used to populate environment variables by the 9 field that have keys that are considered invalid environment variable names will have those keys skipped. The Pod is allowed to start.If you define a Pod with an invalid variable name, the failed Pod startup includes an event with the reason set to 0 and a message that lists the skipped invalid keys. The following example shows a Pod that refers to a Secret named 6, where 6 contains 2 invalid keys: 3 and 4.The output is similar to:
Consuming Secret values from environment variablesInside a container that consumes a Secret using environment variables, the secret keys appear as normal environment variables. The values of those variables are the base64 decoded values of the secret data. This is the result of commands executed inside the container from the example above: The output is similar to:
The output is similar to:
Note: If a container already consumes a Secret in an environment variable, a Secret update will not be seen by the container unless it is restarted. There are third party solutions for triggering restarts when secrets change. Container image pull secretsIf you want to fetch container images from a private repository, you need a way for the kubelet on each node to authenticate to that repository. You can configure image pull secrets to make this possible. These secrets are configured at the Pod level. Using imagePullSecretsThe 5 field is a list of references to secrets in the same namespace. You can use an 5 to pass a secret that contains a Docker (or other) image registry password to the kubelet. The kubelet uses this information to pull a private image on behalf of your Pod. See the for more information about the 5 field.Manually specifying an imagePullSecretYou can learn how to specify 5 from the documentation.Arranging for imagePullSecrets to be automatically attachedYou can manually create 5, and reference these from a ServiceAccount. Any Pods created with that ServiceAccount or created with that ServiceAccount by default, will get their 5 field set to that of the service account. See for a detailed explanation of that process.Using Secrets with static PodsYou cannot use ConfigMaps or Secrets with static Pods. Use casesUse case: As container environment variablesCreate a secret 0Create the Secret: 1Use 9 to define all of the Secret's data as container environment variables. The key from the Secret becomes the environment variable name in the Pod. 2Use case: Pod with SSH keysCreate a Secret containing some SSH keys: 3The output is similar to: 4You can also create a 02 with a 03 field containing ssh keys.Caution: Think carefully before sending your own SSH keys: other users of the cluster may have access to the Secret. You could instead create an SSH private key representing a service identity that you want to be accessible to all the users with whom you share the Kubernetes cluster, and that you can revoke if the credentials are compromised. Now you can create a Pod which references the secret with the SSH key and consumes it in a volume: 5When the container's command runs, the pieces of the key will be available in: 6The container is then free to use the secret data to establish an SSH connection. Use case: Pods with prod / test credentialsThis example illustrates a Pod which consumes a secret containing production credentials and another Pod which consumes a secret with test environment credentials. You can create a 02 with a 03 field or run 06. 7The output is similar to: 8You can also create a secret for test environment credentials. 9The output is similar to: 0Note: Special characters such as 07, 08, 09, 10, and 11 will be interpreted by your shell and require escaping.In most shells, the easiest way to escape the password is to surround it with single quotes ( 12). For example, if your actual password is 13, you should execute the command this way: 1You do not need to escape special characters in passwords from files ( 14).Now make the Pods: 2Add the pods to the same 02: 3Apply all those objects on the API server by running: Both containers will have the following files present on their filesystems with the values for each container's environment: 4Note how the specs for the two Pods differ only in one field; this facilitates creating Pods with different capabilities from a common Pod template. You could further simplify the base Pod specification by using two service accounts:
The Pod specification is shortened to: 5Use case: dotfiles in a secret volumeYou can make your data "hidden" by defining a key that begins with a dot. This key represents a dotfile or "hidden" file. For example, when the following secret is mounted into a volume, 20: 6The volume will contain a single file, called 21, and the 22 will have this file present at the path 23.Note: Files beginning with dot characters are hidden from the output of 24; you must use 25 to see them when listing directory contents.Use case: Secret visible to one container in a PodConsider a program that needs to handle HTTP requests, do some complex business logic, and then sign some messages with an HMAC. Because it has complex application logic, there might be an unnoticed remote file reading exploit in the server, which could expose the private key to an attacker. This could be divided into two processes in two containers: a frontend container which handles user interaction and business logic, but which cannot see the private key; and a signer container that can see the private key, and responds to simple signing requests from the frontend (for example, over localhost networking). With this partitioned approach, an attacker now has to trick the application server into doing something rather arbitrary, which may be harder than getting it to read a file. Types of SecretWhen creating a Secret, you can specify its type using the 26 field of the Secret resource, or certain equivalent 27 command line flags (if available). The Secret type is used to facilitate programmatic handling of the Secret data.Kubernetes provides several built-in types for some common usage scenarios. These types vary in terms of the validations performed and the constraints Kubernetes imposes on them. Built-in TypeUsage 28arbitrary user-defined data 29ServiceAccount token 30serialized 31 file 32serialized 33 file 34credentials for basic authentication 35credentials for SSH authentication 36data for a TLS client or server 37bootstrap token dataYou can define and use your own Secret type by assigning a non-empty string as the 26 value for a Secret object (an empty string is treated as an 28 type).Kubernetes doesn't impose any constraints on the type name. However, if you are using one of the built-in types, you must meet all the requirements defined for that type. If you are defining a type of secret that's for public use, follow the convention and structure the secret type to have your domain name before the name, separated by a 40. For example: 41.Opaque secrets 28 is the default Secret type if omitted from a Secret configuration file. When you create a Secret using 27, you will use the 44 subcommand to indicate an 28 Secret type. For example, the following command creates an empty Secret of type 28. 7The output looks like: 8The 47 column shows the number of data items stored in the Secret. In this case, 48 means you have created an empty Secret.Service account token SecretsA 29 type of Secret is used to store a token credential that identifies a service account.Since 1.22, this type of Secret is no longer used to mount credentials into Pods, and obtaining tokens via the TokenRequest API is recommended instead of using service account token Secret objects. Tokens obtained from the 1 API are more secure than ones stored in Secret objects, because they have a bounded lifetime and are not readable by other API clients. You can use the command to obtain a token from the 1 API.You should only create a service account token Secret object if you can't use the 1 API to obtain a token, and the security exposure of persisting a non-expiring token credential in a readable API object is acceptable to you.When using this Secret type, you need to ensure that the 54 annotation is set to an existing service account name. If you are creating both the ServiceAccount and the Secret objects, you should create the ServiceAccount object first.After the Secret is created, a Kubernetes controller fills in some other fields such as the 55 annotation, and the 56 key in the 1 field, which is populated with an authentication token.The following example configuration declares a service account token Secret: 9After creating the Secret, wait for Kubernetes to populate the 56 key in the 1 field.See the ServiceAccount documentation for more information on how service accounts work. You can also check the 60 field and the 61 field of the for information on referencing service account credentials from within Pods.Docker config SecretsYou can use one of the following 26 values to create a Secret to store the credentials for accessing a container image registry:
The 30 type is reserved to store a serialized 31 which is the legacy format for configuring Docker command line. When using this Secret type, you have to ensure the Secret 1 field contains a 69 key whose value is content of a 31 file encoded in the base64 format.The 32 type is designed for storing a serialized JSON that follows the same format rules as the 33 file which is a new format for 31. When using this Secret type, the 1 field of the Secret object must contain a 75 key, in which the content for the 33 file is provided as a base64 encoded string.Below is an example for a 30 type of Secret: 0Note: If you do not want to perform the base64 encoding, you can choose to use the 2 field instead.When you create these types of Secrets using a manifest, the API server checks whether the expected key exists in the 1 field, and it verifies if the value provided can be parsed as a valid JSON. The API server doesn't validate if the JSON actually is a Docker config file.When you do not have a Docker config file, or you want to use 27 to create a Secret for accessing a container registry, you can do: 1That command creates a Secret of type 32. If you dump the 82 field from that new Secret and then decode it from base64: 2then the output is equivalent to this JSON document (which is also a valid Docker configuration file): 3Note: The 83 value there is base64 encoded; it is obscured but not secret. Anyone who can read that Secret can learn the registry access bearer token.The 34 type is provided for storing credentials needed for basic authentication. When using this Secret type, the 1 field of the Secret must contain one of the following two keys:
Both values for the above two keys are base64 encoded strings. You can, of course, provide the clear text content using the 2 for Secret creation.The following manifest is an example of a basic authentication Secret: 4The basic authentication Secret type is provided only for convenience. You can create an 28 type for credentials used for basic authentication. However, using the defined and public Secret type ( 34) helps other people to understand the purpose of your Secret, and sets a convention for what key names to expect. The Kubernetes API verifies that the required keys are set for a Secret of this type.The builtin type 35 is provided for storing data used in SSH authentication. When using this Secret type, you will have to specify a 92 key-value pair in the 1 (or 2) field as the SSH credential to use.The following manifest is an example of a Secret used for SSH public/private key authentication: 5The SSH authentication Secret type is provided only for user's convenience. You could instead create an 28 type Secret for credentials used for SSH authentication. However, using the defined and public Secret type ( 35) helps other people to understand the purpose of your Secret, and sets a convention for what key names to expect. and the API server does verify if the required keys are provided in a Secret configuration.Caution: SSH private keys do not establish trusted communication between an SSH client and host server on their own. A secondary means of establishing trust is needed to mitigate "man in the middle" attacks, such as a 97 file added to a ConfigMap.TLS secretsKubernetes provides a builtin Secret type 36 for storing a certificate and its associated key that are typically used for TLS.One common use for TLS secrets is to configure encryption in transit for an Ingress, but you can also use it with other resources or directly in your workload. When using this type of Secret, the 99 and the 00 key must be provided in the 1 (or 2) field of the Secret configuration, although the API server doesn't actually validate the values for each key.The following YAML contains an example config for a TLS Secret: 6The TLS Secret type is provided for user's convenience. You can create an 28 for credentials used for TLS server and/or client. However, using the builtin Secret type helps ensure the consistency of Secret format in your project; the API server does verify if the required keys are provided in a Secret configuration.When creating a TLS Secret using 27, you can use the 05 subcommand as shown in the following example: 7The public/private key pair must exist before hand. The public key certificate for 06 must be DER format as per , and must match the given private key for 07 (PKCS #8 in DER format; ).Note: A kubernetes.io/tls Secret stores the Base64-encoded DER data for keys and certificates. If you're familiar with PEM format for private keys and for certificates, the base64 data are the same as that format except that you omit the initial and the last lines that are used in PEM. For example, for a certificate, you do not include 08 and 09.Bootstrap token SecretsA bootstrap token Secret can be created by explicitly specifying the Secret 26 to 37. This type of Secret is designed for tokens used during the node bootstrap process. It stores tokens used to sign well-known ConfigMaps.A bootstrap token Secret is usually created in the 12 namespace and named in the form 13 where 14 is a 6 character string of the token ID.As a Kubernetes manifest, a bootstrap token Secret might look like the following: 8A bootstrap type Secret has the following keys specified under 1:
The above YAML may look confusing because the values are all in base64 encoded strings. In fact, you can create an identical Secret using the following YAML: 9Immutable SecretsFEATURE STATE: 23Kubernetes lets you mark specific Secrets (and ConfigMaps) as immutable. Preventing changes to the data of an existing Secret has the following benefits:
Marking a Secret as immutableYou can create an immutable Secret by setting the 24 field to 25. For example, 0You can also update any existing mutable Secret to make it immutable. Note: Once a Secret or ConfigMap is marked as immutable, it is not possible to revert this change nor to mutate the contents of the 1 field. You can only delete and recreate the Secret. Existing Pods maintain a mount point to the deleted Secret - it is recommended to recreate these pods.Information security for SecretsAlthough ConfigMap and Secret work similarly, Kubernetes applies some additional protection for Secret objects. Secrets often hold values that span a spectrum of importance, many of which can cause escalations within Kubernetes (e.g. service account tokens) and to external systems. Even if an individual app can reason about the power of the Secrets it expects to interact with, other apps within the same namespace can render those assumptions invalid. A Secret is only sent to a node if a Pod on that node requires it. For mounting secrets into Pods, the kubelet stores a copy of the data into a 27 so that the confidential data is not written to durable storage. Once the Pod that depends on the Secret is deleted, the kubelet deletes its local copy of the confidential data from the Secret.There may be several containers in a Pod. By default, containers you define only have access to the default ServiceAccount and its related Secret. You must explicitly define environment variables or map a volume into a container in order to provide access to any other Secret. There may be Secrets for several Pods on the same node. However, only the Secrets that a Pod requests are potentially visible within its containers. Therefore, one Pod does not have access to the Secrets of another Pod. Warning: Any containers that run with 28 on a node can access all Secrets used on that node. |