14

I am pretty new to setting up remote servers, but I was playing around today and was hoping that I could leverage a Cloud Config file upon setup in order to set a few environment variables as the server spins up.

How can I set my environment variables programmatically when spinning up a machine on Digital Ocean? The key is that I want to automate the setup and avoid interactively defining these variables.

Thanks in advance.

s952163
  • 6,276
  • 4
  • 23
  • 47
Btibert3
  • 38,798
  • 44
  • 129
  • 168

3 Answers3

9

This is what I did with for ubuntu

write_files:
- path: /etc/environment
  content: |
    FOO="BAR"
  append: true
dangel
  • 7,238
  • 7
  • 48
  • 74
3

There's a couple ways to do this, although Cloud Init doesn't support a built-in resource type for environment variables.

  1. Depending on your OS, use a write-files section to output the env vars you want to the appropriate file. For CoreOS, you'd do something like:

    write_files:
        - path: "/etc/profile.env"
          append: true
          content: |
            export MY_VAR="foo"
    

For Ubuntu, use /etc/environment, or a user's profile, etc.

  1. Another way to do it would be to leverage Cloud Init's support for Chef, and use that tool to set the variables when the profile is applied.
Stuck
  • 11,225
  • 11
  • 59
  • 104
Dan1701
  • 447
  • 5
  • 14
  • 5
    not recommended, this will overwrite the environment variable file. use `append: true` to prevent this – dangel Jan 26 '20 at 04:13
0

Do you need the environment variable to be permanent, or just for the execution of a single command/script? If it's for a single command, you can do that:

FOO=${BAR} | sh ./your_script.sh
Jan Siekierski
  • 409
  • 6
  • 14
  • this just doesnt work this does though # BAR="test" # FOO=${BAR} | sh -c 'echo $FOO' # FOO=${BAR} sh -c 'echo $FOO' test # – krad Mar 13 '23 at 15:19