启用函数的安全性
如果你想在函数上启用安全性,请完成以下步骤。
先决条件
- 如果你想在函数上启用安全性,你需要先在函数工作者上启用安全设置。
第一步:配置函数工作者
要使用上下文中的秘密API,您需要为函数工作者设置以下两个参数。
secretsProviderConfiguratorClassNamesecretsProviderConfiguratorConfig
Pulsar Functions 提供了两种类型的 SecretsProviderConfigurator 实现,两者都可以直接用作 secretsProviderConfiguratorClassName 的值:
org.apache.pulsar.functions.secretsproviderconfigurator.DefaultSecretsProviderConfigurator: 这是一个基本的密钥提供者版本,它将ClearTextSecretsProvider连接到函数实例。org.apache.pulsar.functions.secretsproviderconfigurator.KubernetesSecretsProviderConfigurator: 默认情况下,这是在Kubernetes中运行时使用的,它使用Kubernetes内置的密钥,并将它们作为环境变量(通过EnvironmentBasedSecretsProvider)绑定到函数容器中,以确保在运行时函数可以访问这些密钥。
函数工作者使用org.apache.pulsar.functions.secretsproviderconfigurator.SecretsProviderConfigurator接口在启动函数实例时选择SecretsProvider类名及其相关配置。
函数实例使用org.apache.pulsar.functions.secretsprovider.SecretsProvider接口来获取密钥。SecretsProvider使用的实现由SecretsProviderConfigurator决定。
如果你想为函数实例使用不同的SecretsProvider,你也可以实现你自己的SecretsProviderConfigurator。
note
目前,只有Java和Python运行时支持SecretsProvider。Java和Python运行时有以下两个提供者:
- ClearTextSecretsProvider(
DefaultSecretsProviderConfigurator的默认值) - EnvironmentBasedSecretsProvider(
KubernetesSecretsProviderConfigurator的默认值)
步骤2:获取密钥
一旦设置了SecretsProviderConfigurator,您可以使用Context对象获取密钥,如下所示。
- Java
- Python
import org.apache.pulsar.functions.api.Context;
import org.apache.pulsar.functions.api.Function;
import org.slf4j.Logger;
public class GetSecretValueFunction implements Function<String, Void> {
@Override
public Void process(String input, Context context) throws Exception {
Logger LOG = context.getLogger();
String secretValue = context.getSecret(input);
if (!secretValue.isEmpty()) {
LOG.info("The secret {} has value {}", input, secretValue);
} else {
LOG.warn("No secret with key {}", input);
}
return null;
}
}
from pulsar import Function
class GetSecretValueFunction(Function):
def process(self, input, context):
logger = context.get_logger()
secret_value = context.get_secret(input)
if secret_provider is None:
logger.warn('No secret with key {0} '.format(input))
else:
logger.info("The secret {0} has value {1}".format(input, secret_value))