Mikyjpeg Mikyjpeg - 1 year ago 62
Ruby Question

How can I conditionally run a block of resources or a recipe in chef?

I've the following recipe used to create some users, add them to a group and set the password to expire at the first login.

search(:users, '*:*').each do |user|
userPassword = "$1$scmdevop$ZDTyqia9RXSrpHGK75FjN/"
user user['id'] do
comment user['comment']
home user['home']
shell user['shell']
manage_home true
password "#{userPassword}"

if user['sudo'] then
group "#{node.default["sudogroup"]}" do
action :modify
members user['id']
append true
if (user['resetPassword'] == nil) || (user['resetPassword']) then
bash 'setExporation' do
code 'chage -d 0 ' + user['id']
user 'root'

The problem is that in this way it will continue to reset the password and set the espiration at every run so I was trying to find how to make it conditionally. I would like to use the following command to check if the user exist

grep -qs #{user["id"]} /etc/passwd

The problem is that I can use the not_if clause only in the first resource because after that the user has been clearly created. Is there a way to get the entire block of three resources being conditional to a shell exit code?


Answer Source

What you probably want is a notification from the user resource, but this might be a little hard because that would trigger on any change, not just creation. The underlying problem here is that the desired behavior you stated is expressed in procedural terms, not in terms of convergent state. Best approach is probably to build a custom resource to hide some of this logic, but at heart what you want is an if statement like you already have.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download