LoginSignup
0
0

More than 5 years have passed since last update.

Puppet4.xではじめるサーバ設定自動化 11(条件分岐)

Posted at

Puppet4.xではじめるサーバ設定自動化の、条件分岐についてです。
全体的な目次は、ここを参照してください。
主にCentOS 7を例に紹介しているので、その他OSについては読み替えてください。

Puppetでの条件分岐

Puppetでの条件分岐は、次の4つがあります。

  • if
  • unless
  • case
  • selectors

if、unless、caseは、他のプログラミング言語と同様です。selectorsは、条件ごとに設定する値を変えたい場合に使います。caseとの違いは、caseは条件を満たす場合の処理を書けますが、selectorsは条件を満たす場合の値のみ書けます。

OSごとにパッケージ名が異なる、httpdとapache2を例に紹介します。
なお、$operatingsystemは、OSの種類を表す変数です。

if

  • OSがCentOSの場合、httpdインストール。
  • OSがCentOS以外でUbuntuの場合、apache2インストール。
  • その他、ワーニング。
if.pp
if $operatingsystem == "CentOS" {
  package { "httpd" :
    ensure  => "installed",
  }
}
elsif $operatingsystem == "Ubuntu" {
  package { "apache2" :
    ensure  => "installed",
  }
}
else {
  warning('This manifest supports only CentOS and Ubuntu.')
}

unless

unlessは条件を満たさない場合です。
参考資料からの引用で、システムメモリサイズが、1073741824バイトより大きくない場合、maxclientを500にする例です。

unless.pp
unless $facts['memory']['system']['total_bytes'] > 1073741824 {
  $maxclient = 500
}

$facts['memory']['system']['total_bytes']は、システムメモリサイズ(byte)です。
なお、unlessの場合、elseは使えますが、elsifは使えません。

case

  • OSがCentOSの場合、httpdインストール。
  • OSがUbuntuの場合、apache2インストール。
  • その他、ワーニング。
case.pp
case $operatingsystem {
  "CentOS": { 
    package { "httpd" :
      ensure  => "installed",
    }
  }
  "Ubuntu": {
    package { "apache2" :
      ensure  => "installed",
    }
  }
  default:  {
    warning('This manifest supports only CentOS and Ubuntu.')
  }
}

selectors

  • OSがCentOSの場合、httpdインストール。
  • OSがUbuntuの場合、apache2インストール。
selectors.pp
$httpd = $operatingsystem ? {
  "CentOS" => "httpd",
  "Ubuntu" => "apache2",
}

package { "httpd" :
  name    => $httpd,
  ensure  => "installed",
}

【おまけ】比較演算子in

条件分岐ではないですが、複数候補に一致する場合などにはin演算子が便利です。
Pythonぽい比較です(Rubyでいうinclude?メソッド)。

in.pp
if $operatingsystem in ["CentOS", "RedHat"] {
  package { "httpd" :
    ensure  => "installed",
  }
}

参考

条件分岐については、下記参照です。

条件に使える比較演算子などは、下記参照です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0