当木偶中存在文件时失败

fail when a file exist in puppet

我正在尝试编写一个 puppet 脚本,它将通过 un-tar 安装一个模块。如果 Puppet 已经是 un tar,我希望它失败。我尝试执行以下代码,但即使目录不存在也总是失败。

我正在检查 /opt/sk 是否存在然后失败,否则继续安装。

define splunk::fail($target)
{
    $no = 'true'
    case $no {
         default : { notice($no) }#fail('sk is already installed.')}
    }
}

define splunk::forwarder( $filename , $target )
{
    file{"$target/sk":
        ensure => present
    }

    splunk::fail{"NO":
        target => '/opt/',
        require => File[$target],
    }

    file{"$target/A.tgz":
        source => $filename ,
        replace => false ,
    }

    exec{"NO1":
        command => "tar xzvf A.tgz" ,
        cwd => $target ,
        require => File["$target/A.tgz"] ,
    }

    exec{"Clean":
        command => "rm -rf A.tgz" ,
        cwd => target ,
        require => Exec["NO1"],
    }
}

splunk::forwarder {"non":
    filename => 'puppet:///modules/splunk/files/NO.tgz' ,
    target => '/opt/',
}

谢谢

定义 custom_fact and use it combined with fail 资源。

在您的 ruby 目录中,例如 /usr/lib/ruby/vendor_ruby/facter 定义文件 tmp_exist.rb 内容:

# tmp_exist.rb

Facter.add('tmp_exist') do
  setcode do
     File.exist? '/root/tmp'
  end
end

接下来在 Puppet 清单中使用它。例如,我将它与 stdlib 中的 str2bool 函数结合起来:

class test {

  if !str2bool($::tmp_exist) {
    fail('TMP NOT EXIST')
  }

  if !str2bool($::foo_exist) {
    fail('FOO NOT EXIST')
  }
}

include test

/root 中仅创建 tmp 文件。

结果你会得到:

Error: FOO NOT EXIST at /etc/puppet/deploy/tests/test.pp:8 on node dbmaster

更新: 我更新了我的回答。 Chris Pitman 是对的,我之前的解决方案仅适用于 puppet master 或 puppet apply。 我还找到了一篇描述如何在 puppet 中定义自定义函数 file_exists 的文章。这也可能有帮助。

你应该使用exec的"creates"属性,例如:

exec { 'install':
  command => "tar zxf ${package}",
  cwd     => $some_location,
  path    => $path,
  creates => "${some_location}/my_package",
}

如果“${some_location}/my_package”不存在,Puppet 只会执行 'install'。