简体   繁体   中英

refactor ensure_packages to switch version of installed packages

I am successfully installing several PHP modules by version with puppet on Debian linux like this:

  $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',
    }
  )

now I want to prepare for an update from PHP 7.3 to 7.4. This basically works, but the 7.3 packages stay installed. I would like to adapt the code to remove the old packages. I am looking for a way to reuse the list of packages of modules for uninstalling.

I am thinking of a signature like this

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',
      }
    )
   }
}

Is there a way to solve this?

thx

I was able to solve this by using iteration functions of puppet.

From the two parameters I build a hash with keys of versions to work on and values to either install or remove the given version. Now I can iterate over this hash with each, reusing the structure:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM