重构 ensure_packages 以切换已安装软件包的版本

refactor ensure_packages to switch version of installed packages

我在 Debian linux 上成功地按版本安装了几个 PHP 模块,如下所示:

  $php_version = '7.3'

  ensure_packages([
    "php$php_version-xml",
    "php$php_version-zip",
    "php$php_version-curl",
    "php$php_version-mbstring",
    "libapache2-mod-php$php_version",
  ],
    {
      'ensure' => 'present',
    }
  )

现在我想准备从 PHP 7.3 到 7.4 的更新。这基本上有效,但 7.3 软件包保持安装状态。我想修改代码以删除旧包。我正在寻找一种方法来重用模块包列表以进行卸载。

我在想这样的签名

class profile::software::apache (
  $php_version    = '7.4',
  $php_remove     = ['7.0‘, ‘7.3'],
  #...
) {

$myPackages = [
    "php$php_version-xml",
    "php$php_version-zip",
    "php$php_version-curl",
    "php$php_version-mbstring",
    "libapache2-mod-php$php_version",
  ]

ensure_packages($myPackages,
    {
      'ensure' => 'present',
    }
  )

  $php_remove.each | String $php_version | { 
    ensure_packages($myPackages,
      {
        'ensure' => 'absent',
      }
    )
   }
}

有办法解决吗?

感谢

我能够通过使用 puppet 的迭代函数来解决这个问题。

根据这两个参数,我构建了一个散列,其中包含要处理的版本的键和安装或删除给定版本的值。 现在我可以对每个散列进行迭代,重用结构:

class profile::software::apache (
  $php_version    = '7.4',
  $php_remove     = ['7.0‘, ‘7.3'],
  #...
) {
  # build a hash of PHP Versions with a value of either present or absent
  # and iterate over it with each
  $phpInstallHash = { $php_version => 'present' }
  #notify { "Value of phpRemove: ${php_remove}": }
  if $php_remove {
    # We have the array, use the map function to build remove hash
    $phpRemoveHash = $php_remove.map |$version| {
      { $version => 'absent' }
    }
    $phpFullHash = $phpInstallHash + $phpRemoveHash
  } else {
    $phpFullHash = $phpInstallHash
  }
  #notify { "phpHash to iterate over to install/uninstall: ${phpFullHash}": }

  #iterate over the result installing/uninstalling
  $phpFullHash.each | $php_version, $ensure_value | {
    ensure_packages([
      "php$php_version-xml",
      "php$php_version-zip",
      "php$php_version-curl",
      "php$php_version-mbstring",
      "libapache2-mod-php$php_version",
    ],
      {
        'ensure' => $ensure_value,
        require  => [Class['apt::update'],
          Apt::Source['source_php_sury'],
        ],
        notify   => Class['apache::service'],
      }
    )

  }
}

hth