大厨 bash 执行 not_if 一些命令 returns 1

Chef bash execute not_if some command returns 1

我需要检查 git 存储库中的代码,并且仅当存储库目录中的代码包含错误分支时才执行 mvn clean package。在厨师食谱中使用(或不使用)not_if 如何做到这一点?

bash "checkout_and_compile_if_wrong_version" do
  user "develop"
  group "develop"
  cwd "/var/www/"
  environment 'HOME' => "/home/develop"
  code <<-EOH
            cd /var/www/code_repo/
            git checkout #{node['last_version']}
            git pull
            mvn clean package
  EOH
  not_if { ...condition... }
end

也许我可以使用类似检查的条件(在 code_repo 目录中):

[ "$(git branch |grep "*" |awk '{print }')" == #{node['last_version']} ] && echo 1

提前致谢。

Chef 有一个 git resource,显然最适合您的用例。

我会做这样的事情(未经测试的代码):

execute "clean package" do
  cwd "/var/www/code_repo/"
  command "mvn clean package"
  user "develop"
  group "develop"
  action :nothing
end

git "/var/www/code_repo/" do
  repository "you_repo_url"
  revision node['last_version']
  user "develop"
  group "develop"
  action :sync
  notifies :run,"execute[clean package]", :immediately
end

如果完成新的提交或如果 node['last_version'] 更改并且 运行 mvn clean 仅当有更改时才会同步。 HOME 环境变量由 git 资源设置,因此不需要提供。


根据评论编辑:

在任何事情之前引用 not_ifonly_if 守卫文档:

A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard attribute is not applied

食谱代码:

bash "whatever" do
  command "test"
   only_if %Q{git branch | awk '/^[*] / { exit =="#{node['last_version']}"}'}, :cwd => "/var/www/code_repo"

end

棘手的部分: bash 仅当版本不等于 node['last_version'] 时才有效(通过 awk 中的相等性测试保护打印 0)

我简化了单个 awk 脚本中的 grep/awk/test 部分,该脚本以 */ / 内的正则表达式)开始,然后告诉 awk 退出,结果为第二个字段(实际 git 分支)和 chef 属性版本之间的比较。 %Q{ code and "quote test indide" } 是一种 ruby 形式,允许使用引号而不必转义它们。

如果比较为真,什么也不做,如果为假,运行 bash 脚本。

我强烈建议尽可能使用 chef 资源,并尽可能用 chef 资源替换 bash 脚本代码。 (更容易维护,及时保持幂等)