0
votes

I am trying to set an environment variable from a script added to an instance metadata. I added the metadata from file using the command:

gcloud compute instances add-metadata server-1 --metadata-from-file file=~/meta.sh

and the script is

 #!/bin/sh
 export SERVER="ide"

it seems is doing nothing when I reboot the server

2

2 Answers

0
votes

The --metadata-from-file flag reads the values for the specified metadata keys from the specified files. In your example, you are assigning the contents of ~/meta.sh as the value for the metadata-data key 'file'.

In order to do something with 'file', you need to read its value from the instance (server-1) and act on it. There are some special metadata keys that are used by compute engine during certain times of the instance life-cycle. For example, 'startup-script' is a key that is read and executed during start-up. I think you intended to use this key. So, try this:

gcloud compute instances add-metadata "server-1" --metadata-from-file startup-script=~/meta.sh

For more details on metadata usage, run:

gcloud compute instances add-metadata --help

or go here:

https://cloud.google.com/compute/docs/metadata

0
votes

6 years old question, but for future reference for myself and others:

Setting environment-variables in the startup-script doesn't seem to work, but what you can do is write them to your .bashrc - in my example, I set them like this:

gcloud compute instances add-metadata etl-pipelines --metadata startup-script='#! /bin/bash
echo "
export USER='${USER}'
export PASSWORD='${PASSWORD}'
" >> /home/USERNAME/.bashrc

better would of course be to check if that string is already inserted into the VM, but that wasn't relevant for me as I kill the VMs quite quickly anyway.

Alternatively, in this SO answer, it is described how to user curl to get the env-vars directly from the metadata, but I haven't looked further into it yet.