1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Chef 稼働環境とChef recipe 作成し、RHEL8 のファイル修正操作を実行する

Posted at

はじめに

RHEL on IBM Power で IaC ツールの一つである Chef コード稼働検証の必要があり、Chef 稼働環境の作成、Chef recipe作成と実行を確認したログです。


環境

・RHEL 8.10 ppc64le (on IBM Power S1012)

# cat /etc/os-release
NAME="Red Hat Enterprise Linux"
VERSION="8.10 (Ootpa)"
ID="rhel"
ID_LIKE="fedora"
VERSION_ID="8.10"
PLATFORM_ID="platform:el8"
PRETTY_NAME="Red Hat Enterprise Linux 8.10 (Ootpa)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:redhat:enterprise_linux:8::baseos"
HOME_URL="https://www.redhat.com/"
DOCUMENTATION_URL="https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8"
BUG_REPORT_URL="https://bugzilla.redhat.com/"

REDHAT_BUGZILLA_PRODUCT="Red Hat Enterprise Linux 8"
REDHAT_BUGZILLA_PRODUCT_VERSION=8.10
REDHAT_SUPPORT_PRODUCT="Red Hat Enterprise Linux"
REDHAT_SUPPORT_PRODUCT_VERSION="8.10"

・Chef : chef-13.8.5-1.el7.ppc64le.rpm (既存環境と合わせるためバージョン固定)
     RHEL8.10 でも chef-13.8.5 (el7 用) は動作しました。

Chef Client モジュールはこちら(↓) からダウンロードしています。


dnf の設定

/etc/dnf/dnf.conf を下記の内容で設定しています。

/etc/dnf/dnf.conf
[RHEL-BaseOS]
name=RHEL810_BaseOS
baseurl=file:///media/rhel810dvd/BaseOS/
enabled=1
gpgcheck=0
gpgkey=file:///media/rhel810dvd/RPM-GPG-KEY-redhat-release

[RHEL-AppStream]
name=RHEL810_AppStream
baseurl=file:///media/rhel810dvd/AppStream/
enabled=1
gpgcheck=0
gpgkey=file:///media/rhel810dvd/RPM-GPG-KEY-redhat-release

[RHEL-Supolement]
name=RHEL_Supplement
baseurl=file:///media/rhel810-sup-dvd/
enabled=1
gpgcheck=0
gpgkey=file:///mnt/rhel810-sup-dvd/RPM-GPG-KEY-redhat-release

今回の環境ではLocal環境のため、gpgcheck=0 としていますが、本番環境やインターネットに接続された環境では、セキュリティ上の理由から gpgcheck=1 に設定し、適切な GPG キーをインポートして検証を有効にすることが推奨されます。


続いて、ローカルのisoファイル(rhel-8.10-ppc64le-dvd.iso、supp-supplementary-8.10-rhel-8-ppc64le-dvd.iso)をマウントします。

# mount -t iso9660 -o loop /work/iso/rhel-8.10-ppc64le-dvd.iso /media/rhel810dvd/
[7194760.344385] loop0: detected capacity change from 0 to 11544549376
mount: /media/rhel810dvd: WARNING: device write-protected, mounted read-only.
# mount -t iso9660 -o loop /work/iso/supp-supplementary-8.10-rhel-8-ppc64le-dvd.iso /media/rhel810-sup-dvd/
[7194783.874641] loop1: detected capacity change from 0 to 153292800
mount: /media/rhel810-sup-dvd: WARNING: device write-protected, mounted read-only.

リポジトリーの確認

# dnf repolist
Updating Subscription Management repositories.

repo id                                repo name
RHEL-AppStream                         RHEL810_AppStream
RHEL-BaseOS                            RHEL810_BaseOS
RHEL-Supolement                        RHEL_Supplement
#

dnfリポジトリが使用可能状態になりました。


Chef の導入

# dnf install chef-13.8.5-1.el7.ppc64le.rpm

Dependencies resolved.
================================================================================
 Package      Architecture    Version                Repository            Size
================================================================================
Installing:
 chef         ppc64le         13.8.5-1.el7           @commandline          48 M

Transaction Summary
================================================================================
Install  1 Package

Total size: 48 M
Installed size: 160 M
Is this ok [y/N]: y
Downloading Packages:
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                        1/1
  Installing       : chef-13.8.5-1.el7.ppc64le                              1/1
  Running scriptlet: chef-13.8.5-1.el7.ppc64le                              1/1
Thank you for installing Chef!

  Verifying        : chef-13.8.5-1.el7.ppc64le                              1/1
Installed products updated.

Installed:
  chef-13.8.5-1.el7.ppc64le

Complete!

従属パッケージ導入はありませんでした。

rpm -qi コマンドでパッケージ確認

# rpm -qi chef-13.8.5-1.el7.ppc64le
Name        : chef
Version     : 13.8.5
Release     : 1.el7
Architecture: ppc64le
Install Date: Sun 07 Sep 2025 04:23:24 AM EDT
Group       : default
Size        : 167366607
License     : Apache-2.0
Signature   : DSA/SHA1, Wed 07 Mar 2018 01:58:05 PM EST, Key ID 2940aba983ef826a
Source RPM  : chef-13.8.5-1.el7.src.rpm
Build Date  : Wed 07 Mar 2018 01:57:38 PM EST
Build Host  : chef-rhel-7-power-le-builder-2082de.cd.chef.co
Relocations : /
Packager    : Chef Software, Inc. <maintainers@chef.io>
Vendor      : Omnibus <omnibus@getchef.com>
URL         : https://www.chef.io
Summary     : The full stack of chef
Description :
The full stack of chef

Chef recipe の作成

今回作成するChef recipe は次の要件を実装します。

requirement
RHEL8 の LVM 設定ファイル /etc/lvm/lvm.conf 内で、# filter = [ "a|.*|" ] 行が出てきた次の行に filter = [ "a|/dev/md.*|", "a|/dev/mapper/mpath.*|", "r|.*|" ] を追加

作成したコードおよびディレクトリ構造です。

<chef home>
.
├── client.rb
│
├── cookbooks
│   └── rhel8_os_base
│       │
│       ├── attributes
│       │   └── lvm.rb
│       │
│       ├── metadata.rb
│       │
│       ├── recipes
│       │   └── lvm_filter.rb
│       │
│       └── templates
│
├── environments
│   └── _default.json
│
└── nodes
   └── node1.json

各スクリプト、ファイルの内容です。

  • client.rb
client.rb
cookbook_path ['/work/chef_test/cookbooks']
node_path '/work/chef_test/nodes'
  • cookbooks/rhel8_os_base/attributes/lvm.rb
cookbooks/rhel8_os_base/attributes/lvm.rb
default['rhel8_os_base']['OS_Base']['Other']['LVM'] = {
  'file' => {
    '/etc/lvm/lvm.conf' => {
      'content' => {
        'filter' => '[ "a|/dev/md.*|", "a|/dev/mapper/mpath.*|", "r|.*|" ]'
      }
    }
  }
}

ネストが深いですが、既存のコードに合わせる必要があるため上記の記載です。よりシンプルな記載は可能と思います。


  • cookbooks/rhel8_os_base/metadata.rb
cookbooks/rhel8_os_base/metadata.rb
name 'rhel8_os_base'
maintainer 'Your Name'
version '0.1.0'
  • cookbooks/rhel8_os_base/recipes/lvm_filter.rb
cookbooks/rhel8_os_base/recipes/lvm_filter.rb
hash = node['rhel8_os_base']['OS_Base']['Other']['LVM']

Chef::Log.info("属性確認: #{hash.inspect}")

hash['file'].each do |f_name, f_attr|
  case f_name
  when '/etc/lvm/lvm.conf'
    ruby_block "edit #{f_name}" do
      block do
        require 'tempfile'

        # インデントをタブ1つに変更
        new_line = "\tfilter = #{f_attr['content']['filter']}"
        inserted = false

        temp_file = Tempfile.new('lvm.conf')
        File.open(f_name, 'r') do |file|
          file.each_line do |line|
            temp_file.puts(line)
            if !inserted && line =~ /^\s*#\s*filter\s*=\s*\[.*\]/
              temp_file.puts(new_line)
              inserted = true
            end
          end
        end

        temp_file.close
        FileUtils.mv(temp_file.path, f_name)
      end
      only_if { ::File.exist?(f_name) }
    end
  end
end

・通常、Chefではファイルの特定行の追加・変更には line resource や template resource を利用しますが、今回は『# filter = [ "a|.*|" ] の次の行に挿入する』という複雑な条件のため、Ruby の柔軟性を活用できる ruby_block を選択しています。(AI推奨コード)

・lvm.conf の既存の行がタブでインデントされていることを考慮し、挿入する行もタブ (\t) でインデントしています。


  • environments/_default.json
environments/_default.json
{
  "name": "_default",
  "description": "Default environment",
  "cookbook_versions": {}
}
  • nodes/node1.json
nodes/node1.json
{
  "name": "testrhel810",
  "chef_environment": "_default",
  "run_list": [
    "recipe[rhel8_os_base::lvm_filter]"
  ]
}

コード実行

  • 変更対象ファイル /etc/lvm/lvm.conf の事前バックアップの取得
# cp -p /etc/lvm/lvm.conf /etc/lvm/lvm.conf_bk
# ls -l /etc/lvm/lvm.conf*
-rw-r--r--. 1 root root 111824 Feb  2  2024 /etc/lvm/lvm.conf
-rw-r--r--. 1 root root 111824 Feb  2  2024 /etc/lvm/lvm.conf_bk
  • chef-client コマンドの実行

Chef Zero モード(Chef Server を使わずにローカル環境だけでレシピを実行可能) で実施します。

# chef-client -z -c /work/chef_test/client.rb -j /work/chef_test/nodes/node1.json

Starting Chef Client, version 13.8.5
resolving cookbooks for run list: ["rhel8_os_base::lvm_filter"]
Synchronizing Cookbooks:
  - rhel8_os_base (0.1.0)
Installing Cookbook Gems:
Compiling Cookbooks...
Converging 1 resources
Recipe: rhel8_os_base::lvm_filter
  * ruby_block[edit /etc/lvm/lvm.conf] action run
    - execute the ruby block edit /etc/lvm/lvm.conf

Running handlers:
Running handlers complete
Chef Client finished, 1/1 resources updated in 03 seconds

3 秒で完了しました。


  • chef-client -z -c /work/chef_test/client.rb -j /work/chef_test/nodes/node1.json の意味
オプション 説明
chef-client Chef クライアントを実行するコマンド。レシピを適用するために使用。
-z Chef Zero モード(ローカルモード)で実行。Chef Server を使わずローカルで完結。
-c /work/chef_test/client.rb Chef の設定ファイル(client.rb)を指定。ログやパスなどの設定を含む。
-j /work/chef_test/nodes/node1.json ノード属性ファイル(JSON形式)を指定。レシピ実行時のノード情報として使用。

反映確認

/etc/lvm/lvm.conf が変更されているかを確認します。

# ls -l /etc/lvm/lvm.conf*
-rw-------. 1 root root 111888 Sep 11 11:04 /etc/lvm/lvm.conf
-rw-r--r--. 1 root root 111824 Feb  2  2024 /etc/lvm/lvm.conf_bk
# diff /etc/lvm/lvm.conf /etc/lvm/lvm.conf_bk
173d172
< 	filter = [ "a|/dev/md.*|", "a|/dev/mapper/mpath.*|", "r|.*|" ]

変更箇所は filter = [ "a|/dev/md.*|", "a|/dev/mapper/mpath.*|", "r|.*|" ] 行のみです。

  • grep コマンドで対象行の前後3行を抜き出す
# grep -C 3 'filter = \[ "a|/dev/md.*|", "a|/dev/mapper/mpath.*|", "r|.*|" \]' /etc/lvm/lvm.conf
	# Example
	# Accept every block device:
	# filter = [ "a|.*|" ]
	filter = [ "a|/dev/md.*|", "a|/dev/mapper/mpath.*|", "r|.*|" ]
	# Reject the cdrom drive:
	# filter = [ "r|/dev/cdrom|" ]
	# Work with just loopback devices, e.g. for testing:

要件通り、# filter = [ "a|.*|" ] の次の行にfilter = [ "a|/dev/md.*|", "a|/dev/mapper/mpath.*|", "r|.*|" ] が追加されています。


おわりに

これまでにすでに作成された Chef コードを動かしたり、軽微な修正は実施したことがありましたが、0 からのChef 環境構築と recipe 作成は今回が初でした。

AI に壁打ちしながら短時間で作成することができ AI の進化も感じられました。


以上です。

1
0
1

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?