MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Chef Tutorials: How to set environment variable in Chef recipe

How you set an environment variable in a Chef recipe depends on who needs to see it. It might be the running chef-client process, a single execute command, every login shell, a systemd service, or Windows system-wide. This guide explains when to use each method shown above and when its timing matters. It also gives tested replacements for the outdated magic_shell and Chef::Util::FileEdit examples.


Method #1


If you need an env var set strictly within the Chef process, you can use ENV['foo'] = 'bar' since it's a ruby process.

Method #2
If you need to set one for an execute provider, Chef exposes an environment hash:

execute 'Bootstrap the database' do 
  cwd "#{app_dir}/current"
  command "#{env_cmd} rake db:drop db:create db:schema:load RAILS_ENV=#{rails_env}"
  environment 'HOME' => "/home/#{app_user}"
  user app_user
  action :run
  not_if %[psql -U postgres -c "\\l" | grep #{db_name}]
endCode language: PHP (php)


Choose the method by scope and persistence

Chef recipes are Ruby, so an environment variable can live in several places. Before you write any code, answer two questions. Which processes must see the variable? Must it still be there after the Chef run ends? The table maps the methods above (including the extra ones from the embedded gist) to those answers.

MethodWho sees the variablePersists after the run?
ENV['FOO'] = 'bar'The chef-client process and every child process it starts later in the runNo
environment property on execute, bash, scriptOnly that one commandNo
File in /etc/profile.d/New login shells (SSH sessions, bash -l)Yes
/etc/environmentNew PAM sessions (logins, su -, many desktop sessions)Yes
systemd Environment=Only that serviceYes
windows_envNew Windows processes (machine or user scope)Yes

Note: No method changes the environment of a shell that is already open. You must log in again, start a new shell, or restart the service before the new value shows up.

Setting variables for the Chef run with ENV

Method #1 assigns to Ruby's ENV hash. Every child process that chef-client starts after the assignment inherits the variable. That covers execute commands, guards and package managers. The catch is timing. Chef compiles all recipes first and converges resources afterwards. A bare ENV[...] = ... at the top level of a recipe runs during compile, before any resource has run. That is usually fine. If the value depends on something a resource creates, set it at converge time inside a ruby_block instead.

# Compile time: set as soon as the recipe file is loaded
ENV['APP_ENV'] = 'production'

# Converge time: set when this resource is reached in the run
ruby_block 'export JAVA_HOME for the rest of the run' do
  block do
    ENV['JAVA_HOME'] = ::File.realpath('/usr/lib/jvm/default-java')
  end
end

execute 'show inherited variables' do
  command 'env | grep -E "APP_ENV|JAVA_HOME" > /tmp/chef-env-check.txt'
endCode language: PHP (php)

ENV changes are global to the process and last until chef-client exits. They can leak into unrelated resources, so use them only for values the whole run needs, such as proxy settings.

Passing variables to execute, bash and script resources

For most cases, the environment property (alias env) from Method #2 is the cleanest option. It takes a Ruby hash and applies only to that command. The example below is a self-contained version of the database bootstrap above. The variables are defined, and RAILS_ENV is passed through the environment instead of as a rake argument.

app_user = 'deploy'
app_dir  = '/srv/myapp'
db_name  = 'myapp_production'

execute 'Bootstrap the database' do
  cwd "#{app_dir}/current"
  command 'bundle exec rake db:create db:schema:load'
  user app_user
  environment(
    'HOME'      => "/home/#{app_user}",
    'RAILS_ENV' => 'production',
    'PATH'      => "/usr/local/bin:#{ENV['PATH']}"
  )
  not_if "psql -U postgres -Atc \"SELECT 1 FROM pg_database WHERE datname='#{db_name}'\" | grep -q 1"
  action :run
endCode language: PHP (php)
  • Setting user does not reset HOME. Without the environment entry, tools such as Bundler or Git can try to write into root's home directory and fail with permission errors.
  • If you set PATH in the hash, it replaces the inherited value completely. Append ENV['PATH'] as shown so that system binaries can still be found.
  • The db:drop from the original was removed. Even with the guard, a destructive drop does not belong in a bootstrap step that runs repeatedly.
  • A string guard can take its own options, for example not_if 'some-check', environment: { 'PGPASSWORD' => pw }, user: 'postgres'. Pass them explicitly when the guard needs the same variables as the command.

The bash, script, powershell_script and batch resources accept the same environment property.

Persistent variables on Linux: profile.d, /etc/environment and systemd

Method #3 suggests writing to /etc/profile.d. You can do that with Chef's built-in file resource. The resource is idempotent and reports changes correctly, and it replaces the community magic_shell cookbook from Method #4, which is old and no longer necessary.

file '/etc/profile.d/myapp.sh' do
  content <<~EOS
    export APP_ENV=production
    export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
  EOS
  owner 'root'
  group 'root'
  mode  '0644'
endCode language: JavaScript (javascript)

Only login shells source /etc/profile.d. Cron jobs, Ruby system() calls, the Chef run itself and systemd services do not read it, which is the gotcha the gist mentions. For a long-running service, set the variable in the service's unit file instead.

systemd_unit 'myapp.service' do
  content(
    Unit:    { Description: 'My application', After: 'network.target' },
    Service: {
      User: 'deploy',
      Environment: 'APP_ENV=production RAILS_ENV=production',
      ExecStart: '/srv/myapp/current/bin/start'
    },
    Install: { WantedBy: 'multi-user.target' }
  )
  action [:create, :enable]
endCode language: JavaScript (javascript)

Note: /etc/environment is not a shell script. pam_env reads it as plain NAME=value lines, so export, $VAR expansion and command substitution do not work there.

Corrected /etc/environment example

Method #5 has several problems. It runs Chef::Util::FileEdit directly in the recipe body, so the file is edited at compile time and Chef never reports the change. It calls write_file on every pass through the loop. insert_line_if_no_match never updates a variable that already exists with an old value. The Java 7 path is also out of date. The version below runs at converge time, updates or inserts each line, writes the file once, and skips the work when the file is already correct.

env_vars = {
  'JAVA_HOME' => '/usr/lib/jvm/java-17-openjdk-amd64'
}

ruby_block 'manage variables in /etc/environment' do
  block do
    fe = Chef::Util::FileEdit.new('/etc/environment')
    env_vars.each do |name, val|
      line = "#{name}=\"#{val}\""
      fe.search_file_replace_line(/^#{name}=/, line)
      fe.insert_line_if_no_match(/^#{name}=/, line)
    end
    fe.write_file
  end
  not_if do
    current = ::File.read('/etc/environment')
    env_vars.all? { |n, v| current.include?("#{n}=\"#{v}\"") }
  end
endCode language: PHP (php)

The original also set LD_LIBRARY_PATH to the JDK library directory. The Java launcher finds its own libraries, so this is not needed. Setting it system-wide can also make unrelated programs load the wrong shared libraries, so it has been left out.

Setting variables on Windows with windows_env

windows_env is built into Chef Infra Client. By default it writes a machine-level variable. Set the user property to target a specific account, and use delim to add an entry to a list-style variable such as PATH without overwriting it.

windows_env 'APP_ENV' do
  value 'production'
  action :create
end

windows_env 'PATH' do
  value 'C:\\tools\\bin'
  delim ';'
  action :modify
endCode language: JavaScript (javascript)

Note: The gist uses CHEF_LICENSE as its example, but a recipe cannot accept the license for the run that is executing it. Accept the license before the first run with chef-client --chef-license accept or by setting CHEF_LICENSE=accept in the bootstrap environment.

Verifying the result and common errors

# Run a single recipe locally
sudo chef-client -z -o 'recipe[myapp::env]'

# Check a new login shell picks up profile.d
bash -lc 'echo $APP_ENV'

# Check a systemd service
systemctl show myapp.service -p Environment

# Windows (PowerShell): machine-level value
[Environment]::GetEnvironmentVariable('APP_ENV', 'Machine')Code language: PHP (php)
SymptomCauseFix
Variable is empty in your current SSH sessionExisting shells never reload their environmentLog out and back in, or start bash -l
Service does not see the variable from profile.dsystemd does not source shell profilesUse Environment= in the unit and restart the service
execute with user fails writing to /rootHOME is still root's home directorySet HOME in the environment hash
Command not found after setting environmentPATH in the hash replaced the inherited valueAppend ENV['PATH'] to your value
ENV value is missing or stale in a later resourceThe variable was set at compile time from data that only exists at converge timeMove the assignment into a ruby_block

Frequently asked questions

Does ENV['VAR'] = 'value' in a Chef recipe persist after chef-client finishes?

No. It changes only the environment of the running chef-client process and its child processes. To make a variable persistent, write it to /etc/profile.d, /etc/environment, a systemd unit or, on Windows, use windows_env.

What is the difference between environment and env on the execute resource?

There is no difference. env is an alias for environment, and both take a hash of variable names and values that applies only to that command.

Why does my systemd service not see a variable I added to /etc/profile.d?

Only login shells read /etc/profile.d. Services started by systemd do not, so set the variable with Environment= or EnvironmentFile= in the unit file and restart the service.

How do I add a directory to PATH on Windows with Chef?

Use the windows_env resource with key_name PATH, the directory as value, delim ';' and action :modify. This appends the entry instead of replacing the whole PATH.

Do I still need the magic_shell cookbook to set environment variables?

No. A built-in file or template resource that writes a script to /etc/profile.d does the same job without an external cookbook dependency.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Chef Tutorials: Common Resource Functionality in chef Cookbook recipe

Common resource properties are settings that every Chef Infra resource accepts, whatever the resource type: action, ignore_failure, retries, retry_delay, sensitive, guards such as not_if and only_if, and…

Read More

Chef Tutorials: How to looping and iterative in Chef Cookbook recipe?

Chef recipes are Ruby, so you loop with ordinary Ruby iterators such as each, and each pass declares one Chef resource. This page explains how the loop…

Read More

Chef Tutorials: How to set Conditions in Chef Cookbooks recipe using Guard?

Chef guards are the not_if and only_if properties, which decide during the converge phase whether a resource runs. A guard can be a shell command string or…

Read More

Chef Tutorials: template Resource with example

The Chef template resource renders an Embedded Ruby (ERB) file from a cookbook's templates/ directory and writes the result to a path on the node. This page…

Read More

Chef Tutorials: Create multiple resources in Chef recipe

A Chef recipe is Ruby, so you can create many resources of the same type by looping over an array with .each and declaring one resource per…

Read More

Chef Tutorials: How to write and test a chef recipe?

The quickest way to write and test a Chef recipe is to put Chef resources in a single Ruby file and run it with chef-apply, which ships…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x