Search code examples
bashpuppet

Include file conditionally based on a bash script


I have a bash command that will return either 1 or 0. I want to run said command from puppet:

exec { 'Check if Thinkpad':
  command     => 'sudo dmidecode | grep -q ThinkPad && echo 1 || echo 0',
  path        => '/usr/bin/:/bin/bash/',
  environment => "HOME=/root"
}

Is there a way I can include a file using puppet only if my command returned 1?

file { '/etc/i3/config':
  source => 'puppet:///modules/i3/thinkpad',
  owner  => 'root',
  group  => 'root',
  mode   => '0644',
}

Solution

  • You can use an external fact to use the bash script as is. Inside the module's facts.d directory, you could place the script.

    #!/bin/bash
    if [ dmidecode | grep -q ThinkPad ]
      echo 'is_thinkpad=true'
    else
      echo 'is_thinkpad=false'
    fi
    

    You can also use a custom fact inside the lib/facter directory of your module.

    Facter.add(:is_thinkpad) do
      confine kernel: linux
      setcode do 
        `dmidecode | grep -q ThinkPad && echo true || echo false`
      end
    end
    

    In both cases, the fact name of is_thinkpad follows the convention for the nomenclature of boolean facts for types of systems. You can then update the code in your manifest for this boolean.

    if $facts['is_thinkpad'] == true {
      file { '/etc/i3/config':
        source => 'puppet:///modules/i3/thinkpad',
        owner  => 'root',
        group  => 'root',
        mode   => '0644',
      }
    }
    

    This will provide you with the functionality you desire.

    https://docs.puppet.com/facter/3.6/custom_facts.html#adding-custom-facts-to-facter https://docs.puppet.com/facter/3.6/custom_facts.html#external-facts