class Chef::Resource::Sysctl

Public Instance Methods

after_created() click to toggle source
# File lib/chef/resource/sysctl.rb, line 113
def after_created
  raise "The sysctl resource requires Linux as it needs sysctl and the sysctl.d directory functionality." unless node["os"] == "linux"
end
coerce_value(v) click to toggle source
# File lib/chef/resource/sysctl.rb, line 117
def coerce_value(v)
  case v
  when Array
    v.join(" ")
  else
    v.to_s
  end
end
contruct_sysctl_content() click to toggle source

construct a string, joining members of new_resource.comment and new_resource.value

@return [String] The text file content

# File lib/chef/resource/sysctl.rb, line 186
def contruct_sysctl_content
  sysctl_lines = Array(new_resource.comment).map { |c| "# #{c.strip}" }

  sysctl_lines << "#{new_resource.key} = #{new_resource.value}"

  sysctl_lines.join("\n") + "\n"
end
set_sysctl_param(key, value) click to toggle source

Shell out to set the sysctl value

@param [String] key The sysctl key @param [String] value The value of the sysctl key

# File lib/chef/resource/sysctl.rb, line 177
def set_sysctl_param(key, value)
  shell_out!("sysctl #{"-e " if new_resource.ignore_error}-w \"#{key}=#{value}\"")
end

Private Instance Methods

get_sysctl_value(key) click to toggle source

shellout to sysctl to get the current value ignore missing keys by using ā€˜-e’ convert tabs to spaces since sysctl tab deliminates multivalue parameters strip the newline off the end of the output as well

Chef creates a file in sysctld with parameter configuration Thus this config will persists even after rebooting the system User can be in a half configured state, where he has already updated the value which he wants to be configured from the resource Therefore we need an extra check with sysctld to ensure a correct idempotency

# File lib/chef/resource/sysctl.rb, line 208
def get_sysctl_value(key)
  val = shell_out!("sysctl -n -e #{key}").stdout.tr("\t", " ").strip
  raise unless val == get_sysctld_value(key)

  val
end
get_sysctld_value(key) click to toggle source

Check if chef has already configured a value for the given key and return the value. Raise in case this conf file needs to be created or updated

# File lib/chef/resource/sysctl.rb, line 218
def get_sysctld_value(key)
  raise unless ::TargetIO::File.exist?("/etc/sysctl.d/99-chef-#{key.tr("/", ".")}.conf")

  k, v = ::Target_IO::File.read("/etc/sysctl.d/99-chef-#{key.tr("/", ".")}.conf").match(/(.*) = (.*)/).captures
  raise "Unknown sysctl key!" if k.nil?
  raise "Unknown sysctl value!" if v.nil?

  v
end