Search code examples
powershellchef-infralwrp

pass environment variables to resource gaurd in powershell_script in LWRP


I have a LWRP with a provider action that looks like this. I want to pass environment variables to a resource guard:

action :create do
  powershell_script 'create file' do
    environment({'fileName' => new_resource.fileName})
    code <<-EOH
      New-Item $env:fileName
      EOH
    guard_interpreter :powershell_script
    not_if '(Test-Path $env:fileName)'
end

In the example above, what I am trying to do is create a new file if one doesn't exist already. When I execute this, the new file is created every time. I expect that the second time around that the guard would execute and the resource would not be recreated. I think what is happening is that I am not able to use the environment variables in the guard like I am in the code block.

Please note that my real-life problem is substantially more complex than this, and I'm not just looking for a way to create a file if it doesn't exist. I need to know how I can use a property specified in the lightweight resource inside the 'not-if' block.


Solution

  • It's buried, but it is in the documentation here. Just do this:

    action :create do
      my_environment = 'fileName' => new_resource.fileName
      powershell_script 'create file' do
        environment my_environment
        code <<-EOH
          New-Item $env:fileName
          EOH
        guard_interpreter :powershell_script
        not_if '(Test-Path $env:fileName)', :environment => my_environment
      end
    end