Usar variáveis de ambiente com os Serviços Cognitivos
Artigo
Este guia mostra como definir e recuperar variáveis de ambiente para lidar com suas credenciais de assinatura dos Serviços Cognitivos de maneira mais segura ao testar aplicativos.
Definir uma variável de ambiente
Para definir variáveis de ambiente, use um dos comandos a seguir, em que ENVIRONMENT_VARIABLE_KEY é a chave nomeada e value é o valor armazenado na variável de ambiente.
Use o comando a seguir para criar e atribuir uma variável de ambiente persistente, considerando o valor de entrada.
:: Assigns the env var to the value
setx ENVIRONMENT_VARIABLE_KEY "value"
Em uma nova instância do prompt de comando, use o comando a seguir para ler a variável de ambiente.
:: Prints the env var value
echo %ENVIRONMENT_VARIABLE_KEY%
Use o comando a seguir para criar e atribuir uma variável de ambiente persistente, considerando o valor de entrada.
# Assigns the env var to the value
[System.Environment]::SetEnvironmentVariable('ENVIRONMENT_VARIABLE_KEY', 'value', 'User')
Em uma nova instância do Windows PowerShell, use o comando a seguir para ler a variável de ambiente.
# Prints the env var value
[System.Environment]::GetEnvironmentVariable('ENVIRONMENT_VARIABLE_KEY')
Use o comando a seguir para criar e atribuir uma variável de ambiente persistente, considerando o valor de entrada.
# Assigns the env var to the value
echo export ENVIRONMENT_VARIABLE_KEY="value" >> /etc/environment && source /etc/environment
Em uma nova instância do Bash, use o comando a seguir para ler a variável de ambiente.
# Prints the env var value
echo "${ENVIRONMENT_VARIABLE_KEY}"
# Or use printenv:
# printenv ENVIRONMENT_VARIABLE_KEY
Dica
Após definir uma variável de ambiente, reinicie o IDE (ambiente de desenvolvimento integrado) para garantir que as variáveis de ambiente adicionadas recentemente estejam disponíveis.
Recuperar variável de ambiente
Para usar uma variável de ambiente em seu código, ela deve ser lida na memória. Use um dos snippets de código a seguir, dependendo de qual linguagem você está usando. Esses snippets de código demonstram como obter uma variável de ambiente com base em ENVIRONMENT_VARIABLE_KEY e atribuir o valor a uma variável de programa chamada value.
using static System.Environment;
class Program
{
static void Main()
{
// Get the named env var, and assign it to the value variable
var value =
GetEnvironmentVariable(
"ENVIRONMENT_VARIABLE_KEY");
}
}
Para obter mais informações, consulte getenv_s e getenv.
#include <iostream>
#include <stdlib.h>
std::string GetEnvironmentVariable(const char* name);
int main()
{
// Get the named env var, and assign it to the value variable
auto value = GetEnvironmentVariable("ENVIRONMENT_VARIABLE_KEY");
}
std::string GetEnvironmentVariable(const char* name)
{
#if defined(_MSC_VER)
size_t requiredSize = 0;
(void)getenv_s(&requiredSize, nullptr, 0, name);
if (requiredSize == 0)
{
return "";
}
auto buffer = std::make_unique<char[]>(requiredSize);
(void)getenv_s(&requiredSize, buffer.get(), requiredSize, name);
return buffer.get();
#else
auto value = getenv(name);
return value ? value : "";
#endif
}
Para obter mais informações, consulte System.getenv.
import java.lang.*;
public class Program {
public static void main(String[] args) throws Exception {
// Get the named env var, and assign it to the value variable
String value =
System.getenv(
"ENVIRONMENT_VARIABLE_KEY")
}
}
Para obter mais informações, consulte process.env.
// Get the named env var, and assign it to the value variable
const value =
process.env.ENVIRONMENT_VARIABLE_KEY;
import os
# Get the named env var, and assign it to the value variable
value = os.environ['ENVIRONMENT_VARIABLE_KEY']
Para obter mais informações, consulte environment.
// Get the named env var, and assign it to the value variable
NSString* value =
[[[NSProcessInfo processInfo]environment]objectForKey:@"ENVIRONMENT_VARIABLE_KEY"];