Автоматизация автоматизации или как мы обеспечили автоустановку не только ОС Astra Linux, но и софта в один «проход»

от автора

Как «раскатать» ось на кучу устройств? Что делать если перед вами стоит задача установить операционную систему семейства linux на большое количество устройств? Ходишь-бродишь среди леса устройств, подключаешь флешку и отвечаешь на одни и те же вопросы при установке системы. Пока не заблудишься…или не сойдёшь с ума в этой рутине…или поймёшь что поседел и зрение уже не то…или…Что-то я увлёкся. Конечно первым делом нужно открывать google! И он ответит: «Парень, не парься, используй preseed». И будет прав, т.к. в linux есть задокументированная возможность использования файла ответов (тот самый preseed.cfg). Если коротко, то вы формируете файл ответов, кладёте его в нужное место и система использует его для ответов на вопросы при установке. А вы в это время пьёте чай и всё такое. Но так ли всё гладко? Конечно нет! Welcome!

Основы. Где брать файл ответов и что с ним делать?

Эту информацию можно взять из документации Debian или wiki астры. Если коротко, то файл ответов можно взять для основы этот:

Пример файла ответов:
#### Contents of the preconfiguration file (for stretch) ### Localization # Preseeding only locale sets language, country and locale. d-i debian-installer/locale string en_US  # The values can also be preseeded individually for greater flexibility. #d-i debian-installer/language string en #d-i debian-installer/country string NL #d-i debian-installer/locale string en_GB.UTF-8 # Optionally specify additional locales to be generated. #d-i localechooser/supported-locales multiselect en_US.UTF-8, nl_NL.UTF-8  # Keyboard selection. d-i keyboard-configuration/xkb-keymap select us # d-i keyboard-configuration/toggle select No toggling  ### Network configuration # Disable network configuration entirely. This is useful for cdrom # installations on non-networked devices where the network questions, # warning and long timeouts are a nuisance. #d-i netcfg/enable boolean false  # netcfg will choose an interface that has link if possible. This makes it # skip displaying a list if there is more than one interface. d-i netcfg/choose_interface select auto  # To pick a particular interface instead: #d-i netcfg/choose_interface select eth1  # To set a different link detection timeout (default is 3 seconds). # Values are interpreted as seconds. #d-i netcfg/link_wait_timeout string 10  # If you have a slow dhcp server and the installer times out waiting for # it, this might be useful. #d-i netcfg/dhcp_timeout string 60 #d-i netcfg/dhcpv6_timeout string 60  # If you prefer to configure the network manually, uncomment this line and # the static network configuration below. #d-i netcfg/disable_autoconfig boolean true  # If you want the preconfiguration file to work on systems both with and # without a dhcp server, uncomment these lines and the static network # configuration below. #d-i netcfg/dhcp_failed note #d-i netcfg/dhcp_options select Configure network manually  # Static network configuration. # # IPv4 example #d-i netcfg/get_ipaddress string 192.168.1.42 #d-i netcfg/get_netmask string 255.255.255.0 #d-i netcfg/get_gateway string 192.168.1.1 #d-i netcfg/get_nameservers string 192.168.1.1 #d-i netcfg/confirm_static boolean true # # IPv6 example #d-i netcfg/get_ipaddress string fc00::2 #d-i netcfg/get_netmask string ffff:ffff:ffff:ffff:: #d-i netcfg/get_gateway string fc00::1 #d-i netcfg/get_nameservers string fc00::1 #d-i netcfg/confirm_static boolean true  # Any hostname and domain names assigned from dhcp take precedence over # values set here. However, setting the values still prevents the questions # from being shown, even if values come from dhcp. d-i netcfg/get_hostname string unassigned-hostname d-i netcfg/get_domain string unassigned-domain  # If you want to force a hostname, regardless of what either the DHCP # server returns or what the reverse DNS entry for the IP is, uncomment # and adjust the following line. #d-i netcfg/hostname string somehost  # Disable that annoying WEP key dialog. d-i netcfg/wireless_wep string # The wacky dhcp hostname that some ISPs use as a password of sorts. #d-i netcfg/dhcp_hostname string radish  # If non-free firmware is needed for the network or other hardware, you can # configure the installer to always try to load it, without prompting. Or # change to false to disable asking. #d-i hw-detect/load_firmware boolean true  ### Network console # Use the following settings if you wish to make use of the network-console # component for remote installation over SSH. This only makes sense if you # intend to perform the remainder of the installation manually. #d-i anna/choose_modules string network-console #d-i network-console/authorized_keys_url string http://10.0.0.1/openssh-key #d-i network-console/password password r00tme #d-i network-console/password-again password r00tme  ### Mirror settings # If you select ftp, the mirror/country string does not need to be set. #d-i mirror/protocol string ftp d-i mirror/country string manual d-i mirror/http/hostname string http.us.debian.org d-i mirror/http/directory string /debian d-i mirror/http/proxy string  # Suite to install. #d-i mirror/suite string testing # Suite to use for loading installer components (optional). #d-i mirror/udeb/suite string testing  ### Account setup # Skip creation of a root account (normal user account will be able to # use sudo). #d-i passwd/root-login boolean false # Alternatively, to skip creation of a normal user account. #d-i passwd/make-user boolean false  # Root password, either in clear text #d-i passwd/root-password password r00tme #d-i passwd/root-password-again password r00tme # or encrypted using a crypt(3)  hash. #d-i passwd/root-password-crypted password [crypt(3) hash]  # To create a normal user account. #d-i passwd/user-fullname string Debian User #d-i passwd/username string debian # Normal user's password, either in clear text #d-i passwd/user-password password insecure #d-i passwd/user-password-again password insecure # or encrypted using a crypt(3) hash. #d-i passwd/user-password-crypted password [crypt(3) hash] # Create the first user with the specified UID instead of the default. #d-i passwd/user-uid string 1010  # The user account will be added to some standard initial groups. To # override that, use this. #d-i passwd/user-default-groups string audio cdrom video  ### Clock and time zone setup # Controls whether or not the hardware clock is set to UTC. d-i clock-setup/utc boolean true  # You may set this to any valid setting for $TZ; see the contents of # /usr/share/zoneinfo/ for valid values. d-i time/zone string US/Eastern  # Controls whether to use NTP to set the clock during the install d-i clock-setup/ntp boolean true # NTP server to use. The default is almost always fine here. #d-i clock-setup/ntp-server string ntp.example.com  ### Partitioning ## Partitioning example # If the system has free space you can choose to only partition that space. # This is only honoured if partman-auto/method (below) is not set. #d-i partman-auto/init_automatically_partition select biggest_free  # Alternatively, you may specify a disk to partition. If the system has only # one disk the installer will default to using that, but otherwise the device # name must be given in traditional, non-devfs format (so e.g. /dev/sda # and not e.g. /dev/discs/disc0/disc). # For example, to use the first SCSI/SATA hard disk: #d-i partman-auto/disk string /dev/sda # In addition, you'll need to specify the method to use. # The presently available methods are: # - regular: use the usual partition types for your architecture # - lvm:     use LVM to partition the disk # - crypto:  use LVM within an encrypted partition d-i partman-auto/method string lvm  # If one of the disks that are going to be automatically partitioned # contains an old LVM configuration, the user will normally receive a # warning. This can be preseeded away... d-i partman-lvm/device_remove_lvm boolean true # The same applies to pre-existing software RAID array: d-i partman-md/device_remove_md boolean true # And the same goes for the confirmation to write the lvm partitions. d-i partman-lvm/confirm boolean true d-i partman-lvm/confirm_nooverwrite boolean true  # You can choose one of the three predefined partitioning recipes: # - atomic: all files in one partition # - home:   separate /home partition # - multi:  separate /home, /var, and /tmp partitions d-i partman-auto/choose_recipe select atomic  # Or provide a recipe of your own... # If you have a way to get a recipe file into the d-i environment, you can # just point at it. #d-i partman-auto/expert_recipe_file string /hd-media/recipe  # If not, you can put an entire recipe into the preconfiguration file in one # (logical) line. This example creates a small /boot partition, suitable # swap, and uses the rest of the space for the root partition: #d-i partman-auto/expert_recipe string                         \ #      boot-root ::                                            \ #              40 50 100 ext3                                  \ #                      $primary{ } $bootable{ }                \ #                      method{ format } format{ }              \ #                      use_filesystem{ } filesystem{ ext3 }    \ #                      mountpoint{ /boot }                     \ #              .                                               \ #              500 10000 1000000000 ext3                       \ #                      method{ format } format{ }              \ #                      use_filesystem{ } filesystem{ ext3 }    \ #                      mountpoint{ / }                         \ #              .                                               \ #              64 512 300% linux-swap                          \ #                      method{ swap } format{ }                \ #              .  # The full recipe format is documented in the file partman-auto-recipe.txt # included in the 'debian-installer' package or available from D-I source # repository. This also documents how to specify settings such as file # system labels, volume group names and which physical devices to include # in a volume group.  # This makes partman automatically partition without confirmation, provided # that you told it what to do using one of the methods above. d-i partman-partitioning/confirm_write_new_label boolean true d-i partman/choose_partition select finish d-i partman/confirm boolean true d-i partman/confirm_nooverwrite boolean true  # When disk encryption is enabled, skip wiping the partitions beforehand. #d-i partman-auto-crypto/erase_disks boolean false  ## Partitioning using RAID # The method should be set to "raid". #d-i partman-auto/method string raid # Specify the disks to be partitioned. They will all get the same layout, # so this will only work if the disks are the same size. #d-i partman-auto/disk string /dev/sda /dev/sdb  # Next you need to specify the physical partitions that will be used.  #d-i partman-auto/expert_recipe string \ #      multiraid ::                                         \ #              1000 5000 4000 raid                          \ #                      $primary{ } method{ raid }           \ #              .                                            \ #              64 512 300% raid                             \ #                      method{ raid }                       \ #              .                                            \ #              500 10000 1000000000 raid                    \ #                      method{ raid }                       \ #              .  # Last you need to specify how the previously defined partitions will be # used in the RAID setup. Remember to use the correct partition numbers # for logical partitions. RAID levels 0, 1, 5, 6 and 10 are supported; # devices are separated using "#". # Parameters are: # <raidtype> <devcount> <sparecount> <fstype> <mountpoint> \ #          <devices> <sparedevices>  #d-i partman-auto-raid/recipe string \ #    1 2 0 ext3 /                    \ #          /dev/sda1#/dev/sdb1       \ #    .                               \ #    1 2 0 swap -                    \ #          /dev/sda5#/dev/sdb5       \ #    .                               \ #    0 2 0 ext3 /home                \ #          /dev/sda6#/dev/sdb6       \ #    .  # For additional information see the file partman-auto-raid-recipe.txt # included in the 'debian-installer' package or available from D-I source # repository.  # This makes partman automatically partition without confirmation. d-i partman-md/confirm boolean true d-i partman-partitioning/confirm_write_new_label boolean true d-i partman/choose_partition select finish d-i partman/confirm boolean true d-i partman/confirm_nooverwrite boolean true  ## Controlling how partitions are mounted # The default is to mount by UUID, but you can also choose "traditional" to # use traditional device names, or "label" to try filesystem labels before # falling back to UUIDs. #d-i partman/mount_style select uuid  ### Base system installation # Configure APT to not install recommended packages by default. Use of this # option can result in an incomplete system and should only be used by very # experienced users. #d-i base-installer/install-recommends boolean false  # The kernel image (meta) package to be installed; "none" can be used if no # kernel is to be installed. #d-i base-installer/kernel/image string linux-image-686  ### Apt setup # You can choose to install non-free and contrib software. #d-i apt-setup/non-free boolean true #d-i apt-setup/contrib boolean true # Uncomment this if you don't want to use a network mirror. #d-i apt-setup/use_mirror boolean false # Select which update services to use; define the mirrors to be used. # Values shown below are the normal defaults. #d-i apt-setup/services-select multiselect security, updates #d-i apt-setup/security_host string security.debian.org  # Additional repositories, local[0-9] available #d-i apt-setup/local0/repository string \ #       http://local.server/debian stable main #d-i apt-setup/local0/comment string local server # Enable deb-src lines #d-i apt-setup/local0/source boolean true # URL to the public key of the local repository; you must provide a key or # apt will complain about the unauthenticated repository and so the # sources.list line will be left commented out #d-i apt-setup/local0/key string http://local.server/key  # By default the installer requires that repositories be authenticated # using a known gpg key. This setting can be used to disable that # authentication. Warning: Insecure, not recommended. #d-i debian-installer/allow_unauthenticated boolean true  # Uncomment this to add multiarch configuration for i386 #d-i apt-setup/multiarch string i386   ### Package selection #tasksel tasksel/first multiselect standard, web-server, kde-desktop  # Individual additional packages to install #d-i pkgsel/include string openssh-server build-essential # Whether to upgrade packages after debootstrap. # Allowed values: none, safe-upgrade, full-upgrade #d-i pkgsel/upgrade select none  # Some versions of the installer can report back on what software you have # installed, and what software you use. The default is not to report back, # but sending reports helps the project determine what software is most # popular and include it on CDs. #popularity-contest popularity-contest/participate boolean false  ### Boot loader installation # Grub is the default boot loader (for x86). If you want lilo installed # instead, uncomment this: #d-i grub-installer/skip boolean true # To also skip installing lilo, and install no bootloader, uncomment this # too: #d-i lilo-installer/skip boolean true   # This is fairly safe to set, it makes grub install automatically to the MBR # if no other operating system is detected on the machine. d-i grub-installer/only_debian boolean true  # This one makes grub-installer install to the MBR if it also finds some other # OS, which is less safe as it might not be able to boot that other OS. d-i grub-installer/with_other_os boolean true  # Due notably to potential USB sticks, the location of the MBR can not be # determined safely in general, so this needs to be specified: #d-i grub-installer/bootdev  string /dev/sda # To install to the first device (assuming it is not a USB stick): #d-i grub-installer/bootdev  string default  # Alternatively, if you want to install to a location other than the mbr, # uncomment and edit these lines: #d-i grub-installer/only_debian boolean false #d-i grub-installer/with_other_os boolean false #d-i grub-installer/bootdev  string (hd0,1) # To install grub to multiple disks: #d-i grub-installer/bootdev  string (hd0,1) (hd1,1) (hd2,1)  # Optional password for grub, either in clear text #d-i grub-installer/password password r00tme #d-i grub-installer/password-again password r00tme # or encrypted using an MD5 hash, see grub-md5-crypt(8). #d-i grub-installer/password-crypted password [MD5 hash]  # Use the following option to add additional boot parameters for the # installed system (if supported by the bootloader installer). # Note: options passed to the installer will be added automatically. #d-i debian-installer/add-kernel-opts string nousb  ### Finishing up the installation # During installations from serial console, the regular virtual consoles # (VT1-VT6) are normally disabled in /etc/inittab. Uncomment the next # line to prevent this. #d-i finish-install/keep-consoles boolean true  # Avoid that last message about the install being complete. d-i finish-install/reboot_in_progress note  # This will prevent the installer from ejecting the CD during the reboot, # which is useful in some situations. #d-i cdrom-detect/eject boolean false  # This is how to make the installer shutdown when finished, but not # reboot into the installed system. #d-i debian-installer/exit/halt boolean true # This will power off the machine instead of just halting it. #d-i debian-installer/exit/poweroff boolean true  ### Preseeding other packages # Depending on what software you choose to install, or if things go wrong # during the installation process, it's possible that other questions may # be asked. You can preseed those too, of course. To get a list of every # possible question that could be asked during an install, do an # installation, and then run these commands: #   debconf-get-selections --installer > file #   debconf-get-selections >> file   #### Advanced options ### Running custom commands during the installation # d-i preseeding is inherently not secure. Nothing in the installer checks # for attempts at buffer overflows or other exploits of the values of a # preconfiguration file like this one. Only use preconfiguration files from # trusted locations! To drive that home, and because it's generally useful, # here's a way to run any shell command you'd like inside the installer, # automatically.  # This first command is run as early as possible, just after # preseeding is read. #d-i preseed/early_command string anna-install some-udeb # This command is run immediately before the partitioner starts. It may be # useful to apply dynamic partitioner preseeding that depends on the state # of the disks (which may not be visible when preseed/early_command runs). #d-i partman/early_command \ #       string debconf-set partman-auto/disk "$(list-devices disk | head -n1)" # This command is run just before the install finishes, but when there is # still a usable /target directory. You can chroot to /target and use it # directly, or use the apt-install and in-target commands to easily install # packages and run commands in the target system. #d-i preseed/late_command string apt-install zsh; in-target chsh -s /bin/zsh  

Если что-то пойдёт не так (например, появятся дополнительные вопросы), всегда можно сделать на установленной вручную системе что-то вроде:

debconf-get-selections --installer > файл debconf-get-selections >> файл

и получить список всех возможных вопросов при установке.

Допустим, файл ответов у нас есть (назовём его preseed.cfg). Куда его поместить, чтобы всё заработало? Это зависит от того какую установку вы хотите — initrd, файловую или сетевую. Изначально мы использовали метод initrd как самый надёжный (хоть и самый трудоёмкий). Суть его заключается в том, чтобы распаковать initrd исходного дистрибутива, поместить в корень preseed.cfg и запаковать. Выглядит это примерно так:

mkdir mnt irmod cd sudo mount -o loop astra.iso mnt rsync -a -H --exclude=TRANS.TBL mnt cd umount mnt cd irmod sudo gzip -d < ../cd/install.amd/initrd.gz | sudo cpio --extract --make-directories --no-absolute-filenames # Здесь копируем наш preseed.cfg cp -f ../preseed.cfg preseed.cfg find . | sudo cpio -H newc --create | sudo gzip -9 > ../cd/install.amd/initrd.gz cd ../cd md5sum `find -follow -type f` > ./md5sum.txt cd .. genisoimage -o Astra16.iso -r -J -c isolinux/boot.cat -b isolinux/isolinux.bin -no-emul-boot -boot-load-size 4 -boot-info-table -eltorito-alt-boot -e boot/grub/efi.img -no-emul-boot ./cd

Динамическая разметка диска и LVM

Разметкой диска при автоустановке занимается partman. С его синтаксисом и особенностями работы можно ознакомиться в интернете. Пример разметки:

root :: 256 100 256 fat16     $primary{ }     method{ efi }     format{ } .      500 500 500 ext4     method{ format }     format{ }     use_filesystem{ }     filesystem{ ext4 }     mountpoint{ /boot } .      30720 30720 30720 ext4     method{ format }     format{ }     use_filesystem{ }     filesystem{ ext4 }     mountpoint{ / } .      500 1000 -1 ext4     method{ format }     format{ }     use_filesystem{ }     reserved_for_root{ 0 }     filesystem{ ext4 }     mountpoint{ /home } .      30720 30720 30720 ext4     method{ format }     format{ }     use_filesystem{ }     filesystem{ ext4 }     mountpoint{ /var } .

У partman есть несколько недостатков, один из них — негибкость. То есть, чтобы динамически выделить место, надо постараться. Запись 500 1000 -1 ext4 означает, что оставшееся место диска нужно выделить под этот раздел. Если в процентах, то это только проценты от объёма оперативной памяти. Вот и вся гибкость… У нас одной из задач стояло — выделение места в процентах от оставшегося места на диске. Пришлось решать проблему. В preseed есть возможность подключать внешние файлы с ответами:

d-i preseed/include string recipe.cfg

и мы вынесли d-i partman/early_command string (выполнение пользовательских команд перед установкой системы) в файл recipe.cfg. Таким образом появляется возможность гибко оперировать вариантами разметки диска. Содержимое recipe.cfg:

d-i partman/early_command string \     debconf-set partman-auto/disk $(DSIZE_OLD=0; \     parted_devices | cut -f1,2 | { while read DISK DSIZE; do \     if [ $DSIZE -gt $DSIZE_OLD ]; then \     DEV=$DISK; \     DSIZE_OLD=$DSIZE; \     fi; \     done; \     echo "$DEV"; \     }); \     SIZE_OLD=0; \     for SIZE in $(parted_devices | cut -f2); do \         if [ $SIZE -gt $SIZE_OLD ]; then \             SIZE_OLD=$SIZE; \         fi; \     done; \     PERCENT=5; \     SNAP_SIZE=$(($SIZE_OLD/1024/1024*$PERCENT/100)); \     debconf-set partman-auto/method "lvm"; \     debconf-set partman-auto/expert_recipe "root :: \     200 200 200 free \         \$iflabel{ gpt } \         \$reusemethod{ } \         method{ efi } \         format{ } . \     500 500 500 ext4 \         \$defaultignore{ } \         method{ format } \         format{ } \         use_filesystem{ } \         filesystem{ ext2 } \         mountpoint{ /boot } . \     30720 30720 30720 ext4 \         \$lvmok{ } \         lv_name{ root } \         method{ lvm } \         format{ } \         use_filesystem{ } \         filesystem{ ext4 } \         mountpoint{ / } . \     30720 30720 30720 ext4 \         \$lvmok{ } \         lv_name{ var } \         method{ lvm } \         format{ } \         use_filesystem{ } \         filesystem{ ext4 } \         reserved_for_root{ 0 } \         mountpoint{ /var } . \     ${SNAP_SIZE} ${SNAP_SIZE} ${SNAP_SIZE} ext4 \         \$lvmok{ } \         lv_name{ datasnapshots } \         \$defaultignore . \     500 1000 -1 ext4 \         \$lvmok{ } \         lv_name{ home } \         method{ lvm } \         format{ } \         use_filesystem{ } \         reserved_for_root{ 0 } \         filesystem{ ext4 } \         mountpoint{ /home } .";

Вы могли заметить, что здесь уже логическая разметка lvm. Выделено 5% от свободного места диска следующим образом: вычисляется соответствие проценты/размер и подставляется в разметку.

Автоматизация обновлений Astra Linux

Для Astra Linux регулярно выходят обновления безопасности в виде репозиториев iso. Процесс обновления выглядит так: устанавливаем систему, и по wiki астры обновляем систему с помощью специальной утилиты astra-update. Эту операцию можно автоматизировать, поместив процедуру обновления в d-i preseed/late_command (что-то вроде postinstall — всё что нужно сделать после установки системы, но до выключения). Также нужно будет позаботиться, чтобы образ с обновлениями находился внутри установочного образа (это можно сделать «заодно» с процедурой распаковывания/сборки образа при копировании preseed.cfg в initrd). Таким образом у нас будет установлена сразу обновлённая система. Но дальше ещё круче…

Установка системы вместе с программным обеспечением компании и обновлениями

Здесь мы расскажем, как мы устанавливаем систему (сразу с обновлениями) плюс программное обеспечение компании без особого участия человека. Из-за особенностей реализации проекта было решено использовать usb накопители. Замысел такой: делаем загрузочный usb накопитель (устанавливаем на неё загрузчик grub), конфигурируем grub.cfg (правим параметры ядра и меню загрузки), разворачиваем сетевой репозиторий в закрытом сегменте с программным обеспечением компании.

Пример создания загрузочного usb накопителя (установки grub):

echo "###########################################" echo "  Разметка usb накопителя для загрузчика..." echo "###########################################" sudo parted -s /dev/sdb mklabel msdos sudo parted -s /dev/sdb mkpart primary 1MiB 551MiB sudo parted -s /dev/sdb set 1 esp on sudo parted -s /dev/sdb set 1 boot on sudo mkfs.fat -F32 /dev/sdb1 sudo parted -s /dev/sdb mkpart primary 551MiB 100% sudo mkfs.ext4 /dev/sdb2 sudo mkdir /media/{efi,data} sudo mount /dev/sdb1 /media/efi sudo mount /dev/sdb2 /media/data echo "##############################" echo "  Установка загрузчика grub..." echo "##############################" sudo grub-install \   --target=i386-pc \   --recheck \   --boot-directory="/media/data/boot" /dev/sdb sleep 1 sudo grub-install \   --target=x86_64-efi \   --recheck \   --removable \   --efi-directory="/media/efi" \   --boot-directory="/media/data/boot"

и конфигурируем grub.cfg (меню загрузки), например:

menuentry "USER_SOFT_V1" {           load_video           insmod gzio           if [ x = xxen ]; then insmod xzio; insmod lzopio; fi           insmod part_msdos           insmod ext2           set root='hd0,msdos2'           set isofile="/iso/astra16.iso"           echo    'Загружается Linux 4.15.3-1 …'           linux /iso/vmlinuz iso-scan/filename=\isofile live-media=$isofile preseed/file=/hd-media/preseed/preseed_fly_lvm_update.cfg soft_hwtype=USER_SOFT_V1 quiet debian-installer/locale=ru debian-installer/language=ru keyboard-configuration/toggle=Ctrl+Shift keyboard-configuration/xkb-keymap=ru console-keymaps-at/keymap=ru astra-license/license=true           echo    'Загружается начальный виртуальный диск …'           initrd /iso/initrd.gz   } menuentry "USER_SOFT_V2" {           ...............   } menuentry "USER_SOFT_V3" {           ...............   } 

Здесь по-порядку:

  • /iso/astra16.iso, /iso/initrd.gz и /iso/vmlinuz это образ системы, образ initrd и образ ядра, которые мы заранее положили на usb накопитель;

  • /hd-media/preseed/preseed_fly_lvm_update.cfg — один из сконфигурированных файлов автоответов, который тоже находится на usb накопителе (да, здесь мы используем файловую установку, т.е. файл автоответов лежит не в initrd). Файлы разметки диска (recipe) тоже находятся на флешке и подключаются в preseed c указанием полного пути. Например,

    d-i partman-auto/expert_recipe_file string /hd-media/recipe/recipe

  • soft_hwtype=USER_SOFT_V1 — переменная, которую можно использовать в d-i preseed/late_command, например, вот так:

    echo $soft_hwtype > /target/tmp/soft_hwtype;

    чтобы потом использовать в своих скриптах, например, для выбора варианта установки ПО (грубо говоря, чтобы связать выбранный пункт меню загрузчика с вариантом установки ПО);

  • debian-installer/locale=ru debian-installer/language=ru keyboard-configuration/toggle=Ctrl+Shift keyboard-configuration/xkb-keymap=ru console-keymaps-at/keymap=ru astra-license/license=true — это необходимо, чтобы не было вопросов до загрузки initrd (в случае, когда preseed.cfg находится внутри initrd необходимости в этом нет);

Примерная структура каталогов на загрузочном usb накопителе выглядит так:

Итак, у нас есть накопитель, с которого мы можем загрузиться и выбрать меню grub с нужной нам вариацией софта. Но откуда брать сам софт? Мы организовали закрытый сегмент сети. На сервере установлены и настроены dhcp сервер, apache ну и сам локальный репозиторий с софтом компании (этот процесс досаточно подробно описан в интернете). Репозиторий на этапе установки системы можно подключить в preseed.cfg следующим образом:

d-i apt-setup/local0/repository string http://192.168.1.1/my_soft/ ./ d-i apt-setup/local0/key string http://192.168.1.1/repo_key.gpg d-i apt-setup/local0/comment string my_soft_repo

Таким образом общая картина выглядит так: подготавливается установочный usb накопитель, загружаемся с него, в меню grub выбираем, с каким софтом будет установлена система, и всё… Занимаемся другими задачами. В итоге получим обновлённую систему с нужным программным обеспечением.

Автоматизация сборки образов Astra Linux в Jenkins

В рамках задачи потребовалось собрать несколько вариантов автоустановочных образов. Например, с fly и без него, с различной разметкой диска или с выводом изображения в последовательный порт rs-232. Решили всё это дело собирать в jenkins c использованием pipeline и jenkinsfile. Вот что получилось:

Для удобства создаём папки проектов fly и nofly (внутри каждой сама сборка):

внутри директории Fly сборки:

Пример stage jenkinsfile:

stage('AstraLinux-1.6-Fly-LVM-Base-Update'){             when { equals expected: "${fly}", actual: currentBuild.projectName }             environment {                 SOURCE_PATH = "${env.WORKSPACE}"                 PARTED = 'base'                 UPD_FLG = 'true'             }             steps {                 echo "===== Build AstraLinux-1.6-Fly-LVM-Base-Update ====="                 sh './Astra16-Fly.sh'                 script {                    currentBuild.displayName = "AstraLinux-1.6-Fly"                    currentBuild.description = "Build AutoInstall Distributive AstraLinux 1.6 Fly"                 }             }         }  stage('AstraLinux-1.6-NoFly-Base-Update'){            .........         }

здесь:

  • PARTED = ‘base’ — вариант разметки диска (передаётся в скрипт Astra16-Fly.sh);

  • UPD_FLG = ‘true’ — флаг, что нужен дистрибутив с обновлением.

    При необходимости можно добавлять любые флаги и обрабатывать их в Astra16-Fly.sh (например, RS232 = ‘true’ и т.п.).

В Astra16-Fly.sh делается всё то, о чём писалось выше: загружается исходный образ системы -> распаковывается -> распаковывается initrd -> копируется нужный preseed.cfg (c нужной разметкой, например, в нашем случае ‘base‘) -> запаковывается initrd -> запаковывается образ системы. Названия артефактов (разных вариантов образов) генерируются с помощью переменных примерно вот так:

sudo genisoimage -o Astra16-NoFly-$PARTED$UPDATE$SWAP$RELEASE$LVM$RS.iso -r -J -c isolinux/boot.cat -b isolinux/isolinux.bin -no-emul-boot -boot-load-size 4 -boot-info-table -eltorito-alt-boot -e boot/grub/efi.img -no-emul-boot ./cd

где переменные $PARTED, $UPDATE, $SWAP и т.д. показывают, какую конфигурацию включает дистрибутив.

Организация релизных сборок

Мы решили, что неплохо бы было собрать стабильные проверенные сборки в одно место, где любой желающий мог бы без труда найти то, что ему нужно. Поэтому для каждой из сборок была создана дополнительная (release), которая запускалась после основной:

Дополнительная сборка собирает всю информацию об артефактах остальных сборок, собранных с флагом release.

И формирует таблицу в виде html разметки с ссылками на релизные артефакты.

Затем для удобства пользователей создали финальную сборку релизов, которая собирала все релизные дистрибутивы со всех сборок.

И уже здесь пользователь может найти все релизные дистрибутивы в виде таблицы html. Также в планах сделать рассылку пользователям о сборке нового релизного дистрибутива.

Нюансы, с которыми мы столкнулись

В целях безопасности изначально использовали usb накопители для установки систем. Образ записывается посредством dd на usb накопитель. Здесь обнаружили особенность. Дело в том что в preseed файле есть ответ, на какой диск ставить систему:

string debconf-set partman-auto/disk /dev/sda

и при установке, названия дисков менялись местами (т.е. назывались по-разному). Поэтому решили «детектить» жёсткий диск по размеру из соображений, что жёсткий диск целевого устройства всегда больше usb накопителя. Вычисляли таким образом:

d-i partman/early_command string \ DISK=$(DSIZE_OLD=0; \ parted_devices | cut -f1,2 | { while read DISK DSIZE; do \ if [ $DSIZE -gt $DSIZE_OLD ]; then \ DEV=$DISK; \ DSIZE_OLD=$DSIZE; \ fi; \ done; \ echo "$DEV"; \ }); \ debconf-set partman-auto/disk "$DISK"; \ debconf-set grub-installer/bootdev $DISK;

Что в итоге

Таким образом в нашей компании была построена автоматизация создания автоустановочных дистрибутивов для автоматизации подготовки устройств. Да, некоторые из вас навярняка скажут, что есть более эффективные способы и технологии массовой установки операционных систем. Действительно, зачем изобретать велосипед? Но мы решали задачу опираясь на конкретные требования (в том числе безопасности) и результат нас вполне устроил. В итоге мы избавились от массы рутинных задач и действий. И это прекрасно! Ведь сколько будет сэкономлено времени и нервов!


ссылка на оригинал статьи https://habr.com/ru/company/protei/blog/651431/


Комментарии

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *