Как включить автоматическое обновление ubuntu 20.04

Шаг 3: Включите уведомления по электронной почте

Иногда очень удобно получать уведомления по электронной почте. Чтобы сделать это, прокрутите и найдите строку ниже, а так же раскоментируйте ее.

Обязательно укажите свой адрес электронной почты.

Так же вы можете получать сообщения по электронной почте в случае сбоя обновления. Например при сбое обновлений безопасности.  Чтобы сделать это найдите строку:

Раскомментируйте ее и измените атрибут “on-change” на «only-on-error”

Отправлять письмо только в случае сбоя обновления

После установки обновлений безопасности рекомендуется перезапустить сервер. Вы можете включить автоматическую перезагрузку сервера после обновления. Делается это в строке:

Поменяйте значение «false» на «true“

Включить автоматическую перезагрузку после установки обновлений безопасности

Если есть пользователи, которые находятся в системе, но вы хотите продолжить перезагрузку, несмотря ни на что. Тогда найдите строку:

Раскомментируйте ее как показано ниже:

Включить автоматическую перезагрузку с пользователями в системе

Также можно установить время, когда произойдет перезагрузка. Для этого раскомментируйте строку ниже. По умолчанию это значение равно 4:00 утра.

Мы установим его на 3:00 утра

Установите время автоматической перезагрузки

Есть много других правил, которые вы можете установить в соответствии с вашими потребностями. Просто прокрутите и раскомментируйте директивы.

Как только вы закончите, не забудьте сохранить изменения конфигурационного файла.

Why should I use them?

Well, it all depends on your environment and your patching behaviour and probably your (enterprise) processes. I had some discussions with friends and customers of ours, and this is what I’ve heard so far:

Pros for unattended upgrades

  • You want your systems always to be up-to-date
  • You want your systems always to have the latest security patches
  • You don’t want to patch them regularly by hand
  • Even if you miss the info of a new vulnerability, you want it to be patched

Cons for unattended upgrades

  • You can’t do it, because your enterprise company says you only have a few specific patch windows
  • You know your application breaks if you update it automatically
  • You want to do everything by hand, or at least invoke an automated upgrade process by hand, so you’ve everything under control
  • You’ve a proper vulnerability management and do security upgrades based on this

Never trust a human

I’m more the let’s-do-it-unattended-guy, because IMHO this is the much better option than the rest. I’ve also my issues with the reasons I’ve heard for the cons.

Let me start with the (in my opinion) most obvious problem in refusing unattended upgrades – the human being. We’re bad in doing things properly 100% of the time. We’re humans and this is part of our nature – we’re not perfect and we make mistakes, this is how we learn and evolve. But even more important, we might have bad days, we’re under stress, we’ve a lot of work, we go on vacation and we forget things. Now, what happens if there’s a new vulnerability and you’re just missed or forgot it? What happens if you’re on vacation, or you’ve way too much work to even check into the latest vulnerability? It probably won’t get patched (in time), and I think we all agree that this is really bad! So just having faith in a human operator is a bad decision

Enterprise companies and their policies

As mentioned before, enterprise companies tend to define patch windows, which basically means you can only upgrade a certain server / service in a specific time window. That isn’t very agile, is it? You need to understand the motivation behind this management decisions. A lot of people, especially in management, are afraid of IT issues, such as downtimes. Because of that, they’re scared of changes, and they start to refuse them. Never touch a running system, right?

But what if you can use that fear for your own advantage? What if you show them the downside of this decision? What if you use their fear against them? What if you say them something like:

Just to be clear here, IMHO option A (in general) is the retarded option and only makes sense in some exceptions. You should definitly aim for option B.

Exceptions

Of course, not every environment is as black & white as described here. I just tried to keep it a bit witty. Still, you should try to avoid humans and do it automatically. Regardless of your decision, there might always be some exceptions. But that doesn’t mean you can’t do unattended upgrades for the majority of servers, services or packages.

Getting it up & ready

Installation

Debian already has a nice documentation about unattended upgrades. The documentation is nice and I used it to get it up & running. However, this is just for the basic setup and I had to figure out the deets by myself.

So let’s start by installing the required packages:

apt-get install unattended-upgrades apt-listchanges
  • unattended-upgrades is doing the unattended upgrades (obvious, huh?)
  • apt-listchanges shows or mails the changes of a package before installing it

Configuration

The configuration files in question are the following:

/etc/apt/apt.conf.d/20auto-upgrades
/etc/apt/apt.conf.d/50unattended-upgrades
/etc/apt/listchanges.conf

First of all the 20auto-upgrades file:

APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";

This basically says do an apt-get update and apt-get upgrade every day, thus the number 1 (n-days) as value.

Next up, the 50unattended-upgrades file:

Unattended-Upgrade::Origins-Pattern {
        "origin=Debian,codename=${distro_codename},label=Debian-Security";
};

Unattended-Upgrade::Package-Blacklist {
};

Now, in this file you’ve the choice which packages should be upgraded. Debian already explains a lot in the default configuration, which is:

// Lines below have the format format is "keyword=value,...".  A
// package will be upgraded only if the values in its metadata match
// all the supplied keywords in a line.  (In other words, omitted
// keywords are wild cards.) The keywords originate from the Release
// file, but several aliases are accepted.  The accepted keywords are:
//   a,archive,suite (eg, "stable")
//   c,component     (eg, "main", "contrib", "non-free")
//   l,label         (eg, "Debian", "Debian-Security")
//   o,origin        (eg, "Debian", "Unofficial Multimedia Packages")
//   n,codename      (eg, "jessie", "jessie-updates")
//     site          (eg, "http.debian.net")
// The available values on the system are printed by the command
// "apt-cache policy", and can be debugged by running
// "unattended-upgrades -d" and looking at the log file.
//
// Within lines unattended-upgrades allows 2 macros whose values are
// derived from /etc/debian_version:
//   ${distro_id}            Installed origin.
//   ${distro_codename}      Installed codename (eg, "jessie")

Last but not least, the listchanges.conf file:

frontend=pager
confirm=false
email_address=root
save_seen=/var/lib/apt/listchanges.db
which=news

Running it

unattended-ugprades is running automatically and is called via cronjob. You don’t need to install apticron or alike, as mentioned in several other posts.

If you want to debug it, you can easily run it on the CLI via:

unattended-upgrades -d

Logging

If you want to know what was going on, check the logfile located here:

/var/log/unattended-upgrades/

You can also add the following configuration to send you mails when an upgrade occured:

Unattended-Upgrade::Mail "root";
Unattended-Upgrade::MailOnlyOnError "false";

Настройка автоматических обновлений

Пакет может быть настроен путем редактирования файла.

Конфигурация по умолчанию должна работать для большинства пользователей, но вы можете открыть файл и внести изменения при необходимости. Вы можете обновить все пакеты или только обновления безопасности.

/etc/apt/apt.conf.d/50unattended-upgrades
 

Первый раздел определяет, какие типы пакетов будут обновляться автоматически. По умолчанию он устанавливает только обновления безопасности. Если вы хотите включить обновления из других репозиториев, вы можете раскомментировать соответствующий репозиторий, удалив двойную косую черту в начале строки. Все, что находится после, является комментарием и не читается пакетом.

Если по какой-либо причине вы хотите отключить автоматическое обновление определенных пакетов, просто добавьте их в черный список пакетов:

/etc/apt/apt.conf.d/50unattended-upgrades
 

Вы также можете получить электронное письмо, если по какой-либо причине возникла проблема с автоматическим обновлением. Для этого раскомментируйте следующие две строки и введите свой адрес электронной почты. Убедитесь, что у вас есть инструмент, который может отправлять электронные письма, установленный в вашей системе, например или .

/etc/apt/apt.conf.d/50unattended-upgrades
 

Setup

By default unattended-upgrades runs an update every day.

The main way to specify which packages will be auto-upgraded is by
means of their «origin» and «archive». These are taken respectively
from the Origin and Suite fields of the repository’s Release file,
or can be found in the output of:

in the «o» and «a» fields for the given repository.

The default setup auto-updates packages in the main and security
archives, which means that only stable and security updates are
applied.

This can be changed either with the
«Unattended-Upgrade::Allowed-Origins» or the
«Unattended-Upgrade::Origins-Pattern» apt configuration lists, which
are listed in /etc/apt/apt.conf.d/50unattended-upgrades.
Also in this file are a range of other options that can be configured.

To override the configuration it is recommended to create an other APT
configuration file fragment which overrides the shipped default
value because updates to to shipped configuration file may conflict
with the local changes blocking updating unattended-upgrades itself.
The new file should sort later than 50unattended-upgrades to be
parsed later than the one shipping the default values, it can
be e.g. 52unattended-upgrades-local.

Allowed-Origins is a simple list of patterns of the form
«origin:archive».

Origins-Pattern allows you to give a list of
(glob-style) patterns to match against. For example:

If you already configure what to install via apt pinning, you can
simply use «origin=*», e.g.:

All operations are logged in /var/log/unattended-upgrades/. This
includes the dpkg output as well. The file
/etc/logrotate.d/unattended-upgrades controls how long logfiles are
kept, and how often they are rotated. See the manpage for
details.

If you want mail support you need to have a mail-transport-agent (e.g
postfix) or mailx installed.

Origins Patterns

Origins Pattern is a more powerful alternative to the Allowed Origins option used in previous versions of unattended-upgrade.

Pattern is composed from specific keywords:

  • ,, – e.g. , ()
  • , – e.g. , , ()
  • , – e.g. , ,
  • , – e.g. , ,
  • , – e.g. , , (this is only supported with >= 0.80)
  • – e.g.

You can review the available repositories using and debug your choice using command on a target system.

Additionally unattended-upgrades support two macros (variables), derived from :

  • – Installed distribution name, e.g. or .
  • – Installed codename, e.g. or .

Using should be preferred over using or as a selected, as once moves to , no security updates will be installed at all, or worse, package from a newer distro release will be installed by accident. The same goes for upgrading your installation from to , if you forget to change this in your origin patterns, you may not receive the security updates for your newer distro release. With , both cases can never happen.

Tips

Although unattended-upgrades helps with simplifying patch management, some remaining actions are left. Some tips while setting it up:

Monitor for reboot

Configure your monitoring tool (e.g. Nagios) to monitor for the presence of /var/run/reboot-required.pkgs. If the file is available, then send out an alert. This way the system administrators know a reboot is needed and downtime can be planned.

Additionally, monitor also for uptime. While Unix based systems are stable, it is not wise to let them run for a year. At least patch regularly and when a reboot is needed, to schedule it. It is better to “plan for failure” and ensure systems can be rebooted easily, knowing other systems take over functionality.

Audit system on a regular basis

Automation can fail. In other words: trust, but verify. Regularly auditing the configuration and proper functioning of the tool, is advised. Tools like Lynis can help with automating this audit process.

Subscribe to the mailing lists

Even if software is simplifying the patch management process for you, the key is in knowing what actual threats endanger your systems. Subscribe to the security mailing lists:

  • Debian: Debian security list
  • Ubuntu: Ubuntu security list

Happy updating!

How to Enable and Set up Automatic Unattended Security Updates on Ubuntu 18.04

23 Февраля 2021
|

Ubuntu

Регулярное обновление вашей системы Ubuntu — один из наиболее важных аспектов общей безопасности системы. Если вы не обновите пакеты своей операционной системы последними исправлениями безопасности, вы сделаете свой компьютер уязвимым для атак.

При управлении несколькими машинами Ubuntu обновление системных пакетов вручную может занять много времени

Даже если вы управляете одной системой, иногда вы можете пропустить важное обновление. Здесь пригодятся автоматические автоматические обновления.
 

Установка пакета

Пакет включает в себя инструменты , которые могут автоматически загрузить и установить обновленные пакеты.

Скорее всего, этот пакет уже установлен в вашей системе Ubuntu. Если нет, вы можете установить его, введя следующую команду в своем терминале:
 

После завершения установки служба автоматического обновления запустится автоматически. Вы можете проверить это, набрав:
 

Настройка автоматических обновлений

Пакет может быть настроен путем редактирования файла.

Конфигурация по умолчанию должна работать для большинства пользователей, но вы можете открыть файл и внести изменения при необходимости. Вы можете обновить все пакеты или только обновления безопасности.

/etc/apt/apt.conf.d/50unattended-upgrades
 

Первый раздел определяет, какие типы пакетов будут обновляться автоматически. По умолчанию он устанавливает только обновления безопасности. Если вы хотите включить обновления из других репозиториев, вы можете раскомментировать соответствующий репозиторий, удалив двойную косую черту в начале строки. Все, что находится после, является комментарием и не читается пакетом.

Если по какой-либо причине вы хотите отключить автоматическое обновление определенных пакетов, просто добавьте их в черный список пакетов:

/etc/apt/apt.conf.d/50unattended-upgrades
 

Вы также можете получить электронное письмо, если по какой-либо причине возникла проблема с автоматическим обновлением. Для этого раскомментируйте следующие две строки и введите свой адрес электронной почты. Убедитесь, что у вас есть инструмент, который может отправлять электронные письма, установленный в вашей системе, например или .

/etc/apt/apt.conf.d/50unattended-upgrades
 

Включение автоматического обновления

Чтобы включить автоматическое обновление, вам необходимо убедиться, что файл конфигурации apt содержит как минимум две следующие строки, которые должны быть включены по умолчанию:

/etc/apt/apt.conf.d/20auto-upgrades
 

Приведенная выше конфигурация обновляет список пакетов и устанавливает доступные обновления каждый день.

Вы также можете добавить следующую строку, которая очищает локальный архив загрузки каждые 7 дней.

/etc/apt/apt.conf.d/20auto-upgrades
 

Другой способ включить / отключить автоматические обновления — выполнить следующую команду, которая изменит (или создаст, если не существует) файл .

Тестирование

Чтобы проверить, работает ли автоматическое обновление, выполните пробный запуск:

   Результат должен выглядеть примерно так:

История автоматических автоматических обновлений записывается в файл.

В этом руководстве вы узнали, как настроить автоматические автоматические обновления и поддерживать свою систему в актуальном состоянии.

Configure Unattended Upgrades on Debian 10

For managing the unattended-upgrades in Debian 10, you will need to perform the following steps:

First of all, you will need to launch the terminal in Debian 10. After launching the terminal successfully, the next thing that you are advised to do is to update your system before installing any new packages. For doing that, type the following command in your terminal and then press the Enter key:

sudo apt update

This command is shown in the image below:

As soon as this command will execute successfully, you will be able to see the message shown in the following image in your terminal:

Now you will need to install the unattended-upgrades package. All you have to do in this regard is to type the following command in your terminal and then press the Enter key:

sudo apt install unattended-upgrades

This command is shown in the image below:

After the successful execution of this command, you will be able to see the following message on your terminal:

The next thing that you need to do is to configure the unattended-upgrades by modifying the /etc/apt/apt.conf.d file. You can open this file with any of the text editors of your choice. However, in this example, we have opened this file with the help of the nano editor. For doing that, you will need to type the following command in your terminal and then press the Enter key:Advertisement

sudo nano /etc/apt/apt.conf.d/50unattended-upgrades

You need to pay special attention to the syntax of this command as an error or mistake while typing this command can lead to incorrect results. This command is also shown in the image below:

As soon as this command will execute successfully, the /etc/apt/apt.conf.d file will open up in the nano editor. Now you need to scroll down to the lines shown in the following image and uncomment them by removing the “//” (two forward slashes) before these lines:

Once you have uncommented these lines, press Ctrl+ X to save the newly made changes and exit from the nano editor. Now when the configuration of the unattended-upgrades is done, the next thing that you need to do is to enable the unattended-upgrades. For doing that, type the following command in your terminal and then press the Enter key:

sudo dpkg-reconfigure --priority=low unattended-upgrades

This command is also shown in the image below:

The successful execution of this command will display a dialogue box on your terminal. Select the Yes option from this dialogue box by pressing the Enter key as shown in the following image:

By now, the unattended-upgrades have been enabled on your Debian 10. However, you also need to ensure whether the above-mentioned process has worked correctly or not. For doing that, you need to check the status of your unattended-upgrades. Type the following command in your terminal and then press the Enter key:

sudo systemctl status unattended-upgrades.service

This command is also shown in the image below:

As soon as this command will execute successfully, you will be able to see the status of your unattended-upgrades. The Active (Running) status means that your unattended-upgrades have been enabled successfully as highlighted in the following image:

Now if you want to disable the unattended-upgrades, then type the very same command in your terminal that you have typed for enabling these upgrades and then press the Enter key. As soon as you will do this, a dialogue box will appear on your terminal. This time, select the No option from this dialogue box and then press the Enter key to disable the unattended-upgrades as highlighted in the image shown below:

As soon as this command will execute successfully, you will be able to see the message shown in the following image on your terminal:

Configuration

After installing, it is time to configure the package. Although there aren’t many things to configure, the configuration file is named /etc/apt/apt.conf.d/50unattended-upgrades. By default, only security upgrades will be installed, which is what most people want.

Next step is to configure the package:

Select that you want to have stable packages installed.

Interactive usage

First time when testing the package, use the -v parameter. This will the actions on screen.

Unattended-upgrade in action

Logging

By default all actions are logged to /var/log/unattended-upgrades/unattended-upgrades.log. Information is also available per day, when actual upgrades are found and installed. In this case data is logged to the /var/log/unattended-upgrades directory, with a name similar to unattended-upgrades-dpkg_2015-03-09_18:17:39.573099.log.

Log rotation

Log are rotated via the logrotate service. Usually no action is needed to ensure that the files are rotated as well. It is still advised to check /etc/logrotate.d/unattended-upgrades for more details and confirm things are properly configured.

Rebooting

Although software packages are maintained this way, we still need to reboot systems. The package does actually enable the possibility to reboot the system for you:

If you rather do it manually, use the file /var/run/reboot-required, to determine if a reboot is needed.

Or if you want to know why a reboot is needed, check /var/run/reboot-required.pkgs. Often a reboot is needed due to updates to the Linux kernel, functions (libraries) or other software, which is integrated closely with the kernel.

See our related blog post: how to check for a required reboot for Debian, Ubuntu, and others.

Role Variables

  • : array of origins patterns to determine whether the package can be automatically installed, for more details see below.
    • Default for Debian:
    • Default for Ubuntu:
  • : packages which won’t be automatically upgraded
  • : whether on unclean dpkg exit to run
  • : split the upgrade into the smallest possible chunks so that they can be interrupted with SIGUSR1.
  • : install all unattended-upgrades when the machine is shuting down.
  • : e-mail address to send information about upgrades or problems with unattended upgrades
  • : send e-mail only on errors, otherwise e-mail will be sent every time there’s a package upgrade.
  • : do automatic removal of all unused dependencies after the upgrade.
  • : do automatic removal of new unused dependencies after the upgrade.
  • : Automatically reboot system if any upgraded package requires it, immediately after the upgrade.
  • : Automatically reboot system if any upgraded package requires it, at the specific time (HH:MM

    Default: false

    ) instead of immediately after the upgrade.

  • : Set the days of the week that updates should be applied. The days can be specified as localized abbreviated or full names. Or as integers where «0» is Sunday, «1» is Monday etc. Example:
  • : unattended-upgrades won’t automatically upgrade some critical packages requiring restart after an upgrade (i.e. there is directive in their debian/control file). With this option set to , unattended-upgrades will upgrade these packages regardless of the directive.
  • : Write events to syslog, which is useful in environments where syslog messages are sent to a central store.
  • : Write events to the specified syslog facility, or the daemon facility if not specified. Will only have affect if is set to .
  • : Define verbosity level of APT for periodic runs. The output will be sent to root.

    • Possible options:
      • : no report
      • : progress report
      • : + command outputs
      • : + trace on
    • Default: (no report)
  • : Do «apt-get update» automatically every n-days (0=disable)
  • : Do «apt-get upgrade —download-only» every n-days (0=disable)
  • : Do «apt-get autoclean» every n-days (0=disable)
  • : Do «apt-get clean» every n-days (0=disable)
  • : Define maximum for a random interval in seconds after which the apt job starts (only for systems without systemd)
  • : Array of dpkg command-line options used during unattended-upgrades runs, e.g. ,
  • : Limit the download speed in kb/sec using apt bandwidth limit feature.
  • : Download and install upgrades only on AC power. It will also install the debian package .

Automatic call via /etc/apt/apt.conf.d/02periodic

Alternatively, you can also create the apt configuration file /etc/apt/apt.conf.d/02periodic to activate unattended-upgrades:

# editor /etc/apt/apt.conf.d/02periodic

Below is an example /etc/apt/apt.conf.d/02periodic:

// Control parameters for cron jobs by /etc/cron.daily/apt-compat //

// Enable the update/upgrade script (0=disable)
APT::Periodic::Enable «1»;

// Do «apt-get update» automatically every n-days (0=disable)
APT::Periodic::Update-Package-Lists «1»;

// Do «apt-get upgrade —download-only» every n-days (0=disable)
APT::Periodic::Download-Upgradeable-Packages «1»;

// Run the «unattended-upgrade» security upgrade script
// every n-days (0=disabled)
// Requires the package «unattended-upgrades» and will write
// a log in /var/log/unattended-upgrades
APT::Periodic::Unattended-Upgrade «1»;

// Do «apt-get autoclean» every n-days (0=disable)
APT::Periodic::AutocleanInterval «21»;

// Send report mail to root
// 0: no report (or null string)
// 1: progress report (actually any string)
// 2: + command outputs (remove -qq, remove 2>/dev/null, add -d)
// 3: + trace on
APT::Periodic::Verbose «2»;

See Also

  • /usr/share/doc/unattended-upgrades/README.md.gz

  • /usr/share/doc/apt/examples/configure-index.gz

  • /etc/cron.daily/apt

Modifying download and upgrade schedules (on systemd)

Because Debian is using the  systemd  system, it has timers defined for APT use, these files are provided by the apt package.The relevant files are:

  • Used for downloads: /lib/systemd/system/apt-daily.timer

    gets overridden by /etc/systemd/system/apt-daily.timer.d/override.conf

  • Used for upgrades: /lib/systemd/system/apt-daily-upgrade.timer

    gets overridden by /etc/systemd/system/apt-daily-upgrade.timer.d/override.conf

The canonical steps to create and edit these overrides for these settings are for downloads

# sudo systemctl edit apt-daily.timer
# sudo systemctl restart apt-daily.timer
# sudo systemctl status apt-daily.timer (optional, you can check the next trigger time with this)
or for upgrades
# sudo systemctl edit apt-daily-upgrade.timer
# sudo systemctl restart apt-daily-upgrade.timer
# sudo systemctl status apt-daily-upgrade.timer (optional, you can check the next trigger time with this)

Here is an example of how to override the download time to 1AM by adding the following via sudo systemctl edit apt-daily.timer :

OnCalendar=
OnCalendar=01:00
RandomizedDelaySec=

Line #2 above is needed to reset (empty) the default value shown below in line #5.Line #4 above is needed to prevent any random delays coming from the defaults.

The current default values for downloads are /lib/systemd/system/apt-daily.timer is (at moment of this writing):

Description=Daily apt download activities


OnCalendar=*-*-* 6,18:00
RandomizedDelaySec=12h
Persistent=true


WantedBy=timers.target

CategoryPackageManagement CategorySystemAdministration

Requirements

The role requires unattended-upgrades version 0.70 and newer, which is available since Debian Wheezy and Ubuntu 12.04 respectively. This is due to usage; if this is not available on your system, you may use the first version of the role.

Automatic Reboot

If you enable automatic reboot feature (), the role will attempt to install package, which is required on some systems for detecting and executing reboot after the upgrade. You may optionally define a specific time for rebooting ().

This feature was broken in Debian Jessie, but eventually was rolled into the unattended-upgrades package; see the discussion in #6 for more details.

Применение для репозитория/PPA

Перейдём к практике. У нас была следующая проблема: один пакет устанавливался на все серверы, но не в родной его версии, а с определенными модификациями. Что делать? Очевидные варианты:

  • «Давайте проклянём на несколько часов одного из стажёров и пусть себе выкатывает!» — возможно, это и окажется полезным для стажёра, но только на этапе обучения работы с системой и при условии, что он совсем не умеет работать apt. Дальше это действительно превратится в проклятие. Вдобавок, получаемый результат будет больше зависим от человеческого фактора, чем хотелось бы.
  • «Выкатить везде с Chef/Puppet/Ansible/…!» — отличная мысль, но не наш случай на тот момент и в той ситуации. Ради одного пакета пришлось бы победить дракона, т.е. завести множество машин в выбранную систему управления конфигурациями.
  • Поскольку статья посвящена unattended upgrades, легко догадаться, что именно этот механизм и предлагает иной способ решить задачу, не потратив на неё множество человекочасов…

Действительно: конфигурация unattended upgrades позволяет активировать автоматическое получение всех обновлений какого-либо пакета для выбранного репозитория — например, вашего собственного или PPA, которому вы имеете основания очень доверять. Чтобы вся эта автомагия заработала на минимальном уровне, достаточно на целевой машине создать конфиг , в котором будут всего три строки:

Если у вас свой репозиторий, то слова и должны как минимум вызывать ассоциации из разряда «Где-то я уже это видел…». Подскажу, что такие параметры можно увидеть у репозитория на самой машине, где должен обновляться пакет, в файле . Иллюстрация для хорошо известной :

Видим два параметра:

  • — «происхождение» репозитория, что может указывать на имя мейнтейнера или самого репозитория;
  • — ветка дистрибутива; например, stable, testing для Debian или trusty, xenial для Ubuntu.

Таким образом, если у вас свой репозиторий пакетов, нужно добавить эти параметры. В результате, для данного примера с PPA конфигурация, разрешающая unattended upgrades для всех пакетов из него, будет выглядеть следующим образом:

Эти настройки логично автоматизировать (тем методом, который вам наиболее близок и/или уже используется), создавая все необходимые конфигурационные файлы при разворачивании новых инсталляций ОС. А проверить, как себя поведёт очередной запуск unattended upgrades, можно следующим образом:

Флаги здесь простые: — быть более многословным, а — не применять изменения. При пробном запуске мы сразу увидим, что у этого решения могут быть обратные стороны:

  • Если установка пакета требует интерактивности, т.е. вмешательства пользователя (особенно актуально, если вы делаете масштабное обновление системы, поскольку уже давно не этого не делали) — unattended upgrades просто ничего не будут делать.

Ещё один «обратный» пример, который даже не относится к добавлению специфичных PPA в unattended upgrades, но с которым мы не раз сталкивались на практике, — это обновления безопасности для PostgreSQL. В стандартной конфигурации Ubuntu Server (т.е. установки только обновлений безопасности через unattended upgrades) автоматическое обновление критичных уязвимостей в этой СУБД приводило к её рестарту в то время, когда не все этого ожидали. Если такое поведение может оказаться неожиданным (нежелательным) и для вашего случая — см. опцию ниже.

Рейтинг
( Пока оценок нет )
Понравилась статья? Поделиться с друзьями:
Мой редактор ОС
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: