为计算引擎VM设置环境变量

问题描述 投票:1回答:3

我需要在Google Compute Engine上的虚拟机中设置环境变量。我需要设置的变量称为"GOOGLE_APPLICATION_CREDENTIALS"and,根据Google文档,我需要将其值设置为json文件的路径。我有两个问题:

1:我可以在GCP上的Google Compute Engine界面中设置此变量吗?

2:我可以使用System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Resources.googlecredentials.credentials);吗?每当我尝试在我的本地机器上设置此变量时,我使用此技术,但我将值设置为文件的路径(本地目录)。但是,因为我现在正在使用虚拟机,我想知道,我可以将环境变量设置为资源文件的实际内容吗?有利地,这允许我将凭证嵌入到实际的app本身中。

干杯

google-cloud-platform environment-variables virtual-machine google-compute-engine embedded-resource
3个回答
1
投票

暂时将凭据存储在文件中

$HOME/example/g-credentials.json

{
  "foo": "bar"
}

然后将其作为字符串上传到您的GCE项目元数据

gcloud compute project-info add-metadata \
    --metadata-from-file g-credentials=$HOME/example/g-credentials.json

您可以通过搜索metadata在云控制台上查看GCE项目元数据,也可以使用gcloud查看它

gcloud compute project-info describe

然后在VMs启动脚本中设置env var / load配置

$HOME/example/startup.txt

#! /bin/bash

# gce project metadata key where the config json is stored as a string
meta_key=g-credentials
env_key=GOOGLE_APPLICATION_CREDENTIALS
config_file=/opt/g-credentials.json
env_file=/etc/profile

# command to set env variable
temp_cmd="export $env_key=$config_file"

# command to write $temp_cmd to file if $temp_cmd doesnt exist w/in it
perm_cmd="grep -q -F '$temp_cmd' $env_file || echo '$temp_cmd' >> $env_file"

# set the env var for only for the duration of this script.
# can delete this if you don't start processes at the end of
# this script that utilize the env var.
eval $temp_cmd

# set the env var permanently for any SUBSEQUENT shell logins
eval $perm_cmd

# load the config from the projects metadata
config=`curl -f http://metadata.google.internal/computeMetadata/v1/project/attributes/$meta_key -H "Metadata-Flavor: Google" 2>/dev/null`

# write it to file
echo $config > $config_file

# start other processes below ...

example instance

gcloud compute instances create vm-1 \
    --metadata-from-file startup-script=$HOME/example/startup.txt \
    --zone=us-west1-a

1
投票

你也可以编辑用户的个人资料:

nano ~/.bashrc

甚至全系统的/etc/profile/etc/bash.bashrc/etc/environment

然后添加:

export GOOGLE_APPLICATION_CREDENTIALS=...

也可以使用Custom Metadata,这是GCE特定的。


0
投票
  1. 是的,你可以在你的RDP/SSH session中设置它。
  2. 不,您应该根据documentation在变量中设置路径,或者,有一些代码示例可以收集变量中的服务帐户路径以使用应用程序中的凭据。
© www.soinside.com 2019 - 2024. All rights reserved.