簡體   English   中英

如何使用人偶模塊評論文件中所有未注釋的行

[英]How to comment all the uncommented lines in a file using puppet module

我有一個 sshd_config 配置文件,其中包含注釋行和未注釋行。 我想使用 puppet 注釋該文件中所有未注釋的行。 有什么最佳/簡單的方法可以做到這一點嗎? 或者有沒有辦法通過 puppet 運行 bash 命令(也許 sed 來替換)? 我不確定使用 bash 命令是否正確。

如果有人指導我,這將非常有幫助。 提前致謝!

有什么最佳/簡單的方法可以做到這一點嗎?

沒有內置資源類型或眾所周知的模塊專門確保文件的非空行以#字符開頭。

或者有沒有辦法通過 puppet 運行 bash 命令(也許 sed 來替換)?

是的, Exec資源類型。 這是除了編寫自定義資源類型之外的最佳選擇。

我不確定使用 bash 命令是否正確。

從一般意義上講,它不是。 適當的、特定的資源類型優於Exec 但是,當您沒有合適的並且懶得制作時,可以使用Exec

它可能看起來像這樣:

# The file to work with, so that we don't have to repeat ourselves
$target_file = '/etc/ssh/sshd_config'

exec { "Comment uncommented ${target_file} lines":
  # Specifying the command in array form avoids complicated quoting or any
  # risk of Puppet word-splitting the command incorrectly
  command  => ['sed', '-i', '-e', '/^[[:space:]]*[^#]/ s/^/# /', $target_file],

  # If we didn't specify a search path then we would need to use fully-qualified
  # command names in 'command' above and 'onlyif' below
  path     => ['/bin', '/usr/bin', '/sbin', '/usr/sbin'],

  # The file needs to be modified only if it contains any non-blank, uncommented
  # lines.  Testing that via an 'onlyif' ensures that Puppet will not
  # run 'sed' or (more importantly) report the file changed when it does
  # not initially contain any lines that need to be commented
  onlyif   => [['grep', '-q', '^[[:space:]]*[^#]', $target_file]],

  # This is the default provider for any target node where the rest of this
  # resource would work anyway.  Specifying it explicitly will lead to a more
  # informative diagnostic if there is an attempt to apply this resource to
  # a system to which it is unsuited.
  provider => 'posix',
}

這不依賴於 bash 或任何其他 shell 來運行命令,但它確實依賴於sedgrep在指定目錄之一中可用。 事實上,它特別依賴於 GNU sed或支持具有相同語義的-i選項的 GNU sed。 值得注意的是,這不包括 BSD 風格的sed ,例如您將在 macOS 上找到的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM