とあるシステムの中の人

プログラミング、育児、武道、3Dグラフィック、ゲーム開発

ufwのログについての基本

ufwのログについての基本

ufwとは

  • ubuntuのファイアーウォール構成ツール
  • iptablesの構成を容易にする。確かにかなり簡単に設定できる。

基本的なコマンド

ufw enable
  • status
ufw status verbose

設定

  • デフォルトでは、受信に対して拒否が適用される
  • /etc/ufw 内のルール ファイル (名前が .rules で終わるファイル) を読み取ることもできるらしい。

allow

ufw allow <port>/<optional: protocol>

deny

ufw deny <port>/<optional: protocol>

Logging

  • logging 有効化
sudo ufw logging on
  • logging 無効化
sudo ufw logging off

そのほか

  • IPアドレスやレンジでも指定可能。
  • デフォルトでは、UFWping リクエストを許可。
  • ping (icmp) リクエストを無効にするには、/etc/ufw/before.rulesを編集する必要がある。

本題のログについて

  • 以下のコマンドで現在の設定が確認できる
root@ttmp:~# ufw status verbose
Status: inactive
root@ttmp:~# 
  • デフォルトでは、非アクティブ。
  • 有効化する。
root@ttmp:~# ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup
root@ttmp:~#
  • 再度、現在の状況を確認
root@ttmp:~# ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip
root@ttmp:~# 
  • 起動時の警告にあった通り、デフォルトでは外部からの接続については全て拒否となっているため、このままではssh接続もできなくなってしまう。

  • ssh接続を切断して再接続しようとすると、見事に弾かれます。

  • sshを許可してみます。
root@ttmp:~# ufw allow 22
Rule updated
Rule updated (v6)
root@ttmp:~# 
  • これで接続できるようになります。
  • 検証用にssh以外のポートを許可しておきます。
root@ttmp:~# ufw allow 8888
Rule added
Rule added (v6)
root@ttmp:~#
  • 検証のために以下のようなコマンドを別のVMから打ちます。
root@ttmp-virtual-machine:~# nc -vz -w 5 192.168.11.23 8888
nc: connect to 192.168.11.23 port 8888 (tcp) failed: Connection refused
root@ttmp-virtual-machine:~# nc -vz -w 5 192.168.11.23 9999
nc: connect to 192.168.11.23 port 9999 (tcp) timed out: Operation now in progress
root@ttmp-virtual-machine:~# 
  • 現在のログはどうなっているのでしょうか。
  • ログは/var/log/syslog/var/log/ufw.logに出ます。
Mar  5 15:10:15 ttmp kernel: [ 2406.404914] [UFW BLOCK] IN=ens160 OUT= MAC=00:0c:29:48:83:5c:00:0c:29:71:f5:17:08:00 SRC=192.168.11.2 DST=192.168.11.23 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=51853 DF PROTO=TCP SPT=35674 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0 
Mar  5 15:10:16 ttmp kernel: [ 2407.434874] [UFW BLOCK] IN=ens160 OUT= MAC=00:0c:29:48:83:5c:00:0c:29:71:f5:17:08:00 SRC=192.168.11.2 DST=192.168.11.23 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=51854 DF PROTO=TCP SPT=35674 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0 
Mar  5 15:10:17 ttmp kernel: [ 2408.458888] [UFW BLOCK] IN=ens160 OUT= MAC=00:0c:29:48:83:5c:00:0c:29:71:f5:17:08:00 SRC=192.168.11.2 DST=192.168.11.23 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=51855 DF PROTO=TCP SPT=35674 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0 
Mar  5 15:10:18 ttmp kernel: [ 2409.482848] [UFW BLOCK] IN=ens160 OUT= MAC=00:0c:29:48:83:5c:00:0c:29:71:f5:17:08:00 SRC=192.168.11.2 DST=192.168.11.23 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=51856 DF PROTO=TCP SPT=35674 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0 
Mar  5 15:10:19 ttmp kernel: [ 2410.506857] [UFW BLOCK] IN=ens160 OUT= MAC=00:0c:29:48:83:5c:00:0c:29:71:f5:17:08:00 SRC=192.168.11.2 DST=192.168.11.23 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=51857 DF PROTO=TCP SPT=35674 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0 
  • UFW BLOCKというような接続が拒否された旨のログが出力されています。
  • ログレベルは以下のような感じです。
    • off: 完全に無効
    • low: default 以外のルールによりブロックされる通信を記録する。
    • medium: allow / deny に合致する通信、不正なパケット、新しい接続を記録する。
    • high: allow / deny に合致する通信、不正なパケット、新しい接続を記録する。medium よりも詳細な記録を出力する。
    • full: 全てのログを記録する
  • ログレベルを再設定します。
root@ttmp:~# ufw logging medium
Logging enabled
root@ttmp:~#
root@ttmp:~# ufw status verbose
Status: active
Logging: on (medium)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
22                         ALLOW IN    Anywhere                  
22 (v6)                    ALLOW IN    Anywhere (v6)             

root@ttmp:~# 
  • 同じようにコマンドを打つとどうなるでしょうか。
Mar  5 15:11:26 ttmp kernel: [ 2477.120604] [UFW AUDIT] IN=ens160 OUT= MAC=00:0c:29:48:83:5c:00:0c:29:71:f5:17:08:00 SRC=192.168.11.2 DST=192.168.11.23 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=60743 DF PROTO=TCP SPT=53350 DPT=8888 WINDOW=64240 RES=0x00 SYN URGP=0 
Mar  5 15:11:28 ttmp kernel: [ 2479.001243] [UFW AUDIT] IN=ens160 OUT= MAC=00:0c:29:48:83:5c:00:0c:29:71:f5:17:08:00 SRC=192.168.11.2 DST=192.168.11.23 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=40714 DF PROTO=TCP SPT=47286 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0 
Mar  5 15:11:28 ttmp kernel: [ 2479.001271] [UFW BLOCK] IN=ens160 OUT= MAC=00:0c:29:48:83:5c:00:0c:29:71:f5:17:08:00 SRC=192.168.11.2 DST=192.168.11.23 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=40714 DF PROTO=TCP SPT=47286 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0 
Mar  5 15:11:29 ttmp kernel: [ 2480.010076] [UFW AUDIT] IN=ens160 OUT= MAC=00:0c:29:48:83:5c:00:0c:29:71:f5:17:08:00 SRC=192.168.11.2 DST=192.168.11.23 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=40715 DF PROTO=TCP SPT=47286 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0 
Mar  5 15:11:29 ttmp kernel: [ 2480.010104] [UFW BLOCK] IN=ens160 OUT= MAC=00:0c:29:48:83:5c:00:0c:29:71:f5:17:08:00 SRC=192.168.11.2 DST=192.168.11.23 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=40715 DF PROTO=TCP SPT=47286 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0 
Mar  5 15:11:30 ttmp kernel: [ 2481.034053] [UFW AUDIT] IN=ens160 OUT= MAC=00:0c:29:48:83:5c:00:0c:29:71:f5:17:08:00 SRC=192.168.11.2 DST=192.168.11.23 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=40716 DF PROTO=TCP SPT=47286 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0 
Mar  5 15:11:30 ttmp kernel: [ 2481.034081] [UFW BLOCK] IN=ens160 OUT= MAC=00:0c:29:48:83:5c:00:0c:29:71:f5:17:08:00 SRC=192.168.11.2 DST=192.168.11.23 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=40716 DF PROTO=TCP SPT=47286 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0 
Mar  5 15:11:31 ttmp kernel: [ 2482.058042] [UFW AUDIT] IN=ens160 OUT= MAC=00:0c:29:48:83:5c:00:0c:29:71:f5:17:08:00 SRC=192.168.11.2 DST=192.168.11.23 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=40717 DF PROTO=TCP SPT=47286 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0 
Mar  5 15:11:31 ttmp kernel: [ 2482.058068] [UFW BLOCK] IN=ens160 OUT= MAC=00:0c:29:48:83:5c:00:0c:29:71:f5:17:08:00 SRC=192.168.11.2 DST=192.168.11.23 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=40717 DF PROTO=TCP SPT=47286 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0 
Mar  5 15:11:32 ttmp kernel: [ 2483.082029] [UFW AUDIT] IN=ens160 OUT= MAC=00:0c:29:48:83:5c:00:0c:29:71:f5:17:08:00 SRC=192.168.11.2 DST=192.168.11.23 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=40718 DF PROTO=TCP SPT=47286 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0 
Mar  5 15:11:32 ttmp kernel: [ 2483.082062] [UFW BLOCK] IN=ens160 OUT= MAC=00:0c:29:48:83:5c:00:0c:29:71:f5:17:08:00 SRC=192.168.11.2 DST=192.168.11.23 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=40718 DF PROTO=TCP SPT=47286 DPT=9999 WINDOW=64240 RES=0x00 SYN URGP=0 
  • UFW AUDITというキーワードが増えています。ポートも8888なので、許可された通信と一致します。
  • これはufwが操作しているiptablesでログを取得するように指定したもの以外を記録したもののようです。てっきりALLOWとなる想定でしたが、異なるようです。
  • ちなみにiptablesのログが出力される/var/log/kern.logにも同様のログが出ます。
  • また、ALLOWはアウトバウンド通信の時は出力されます。これはデフォルト設定はiptable上でログが出る設定になっているためと思われます。
root@ttmp:~# cat /var/log/ufw.log | grep 'UFW ALLOW'
Mar  5 14:38:46 ttmp kernel: [  516.799737] [UFW ALLOW] IN= OUT=ens160 SRC=192.168.11.23 DST=185.125.190.57 LEN=76 TOS=0x10 PREC=0x00 TTL=64 ID=39923 DF PROTO=UDP SPT=43427 DPT=123 LEN=56 
Mar  5 14:47:18 ttmp kernel: [ 1029.032850] [UFW ALLOW] IN= OUT=ens160 SRC=192.168.11.23 DST=185.125.190.57 LEN=76 TOS=0x10 PREC=0x00 TTL=64 ID=58284 DF PROTO=UDP SPT=44131 DPT=123 LEN=56 
Mar  5 14:54:37 ttmp kernel: [ 1468.277685] [UFW ALLOW] IN= OUT=ens160 SRC=192.168.11.23 DST=192.168.11.1 LEN=81 TOS=0x00 PREC=0x00 TTL=64 ID=15411 PROTO=UDP SPT=49607 DPT=53 LEN=61 
Mar  5 14:54:37 ttmp kernel: [ 1468.279877] [UFW ALLOW] IN= OUT=ens160 SRC=192.168.11.23 DST=192.168.11.1 LEN=85 TOS=0x00 PREC=0x00 TTL=64 ID=11838 PROTO=UDP SPT=41563 DPT=53 LEN=65 
Mar  5 14:54:48 ttmp kernel: [ 1478.987495] [UFW ALLOW] IN= OUT=ens160 SRC=192.168.11.23 DST=192.168.11.1 LEN=85 TOS=0x00 PREC=0x00 TTL=64 ID=11717 PROTO=UDP SPT=47213 DPT=53 LEN=65 
Mar  5 14:54:54 ttmp kernel: [ 1484.837811] [UFW ALLOW] IN= OUT=ens160 SRC=192.168.11.23 DST=192.168.11.1 LEN=85 TOS=0x00 PREC=0x00 TTL=64 ID=19735 PROTO=UDP SPT=56343 DPT=53 LEN=65 
Mar  5 15:04:22 ttmp kernel: [ 2053.249653] [UFW ALLOW] IN= OUT=ens160 SRC=192.168.11.23 DST=185.125.190.57 LEN=76 TOS=0x10 PREC=0x00 TTL=64 ID=57710 DF PROTO=UDP SPT=57812 DPT=123 LEN=56 
root@ttmp:~# 
  • おそらくiptableの箇所は、以下。
Chain ufw-after-logging-output (1 references)
target     prot opt source               destination         
LOG        all  --  anywhere             anywhere             LOG level warning prefix "[UFW ALLOW] "
  • 逆にいうと、ログの制御をするならば、iptablesを設定する必要があるということだと思います。
  • このあたりはもう少し検証してみたいですが、今回はここまで。

ubuntuのネットワーク関連でハマったのでメモ

ubuntuのネットワーク関連でハマったのでメモ

  • とあるシステムで使用したOVAのネットワーク設定でハマってしまったのでメモ。

経緯

  • てっきりcentosで用意されているものだと思い込み、nmcliで固定IPを設定してしまったのがはじまり。
  • static routeを設定しようと、今の設定を確認するためにNetPlanのyamlを覗くと固定IPの設定がない・・・
  • なぜ!?
  • この時、そもそもNetPlanの理解が浅かった。(nmcliで設定した内容がファイルとかに吐き出される、程度の理解)
  • ということで、まずは、NetPlan is 何?

NetPlan is 何?

  • ネットワークの設定ツールをymlで設定できる。
  • インストーラーで指定したネットワーク設定をNetplanの設定として書き出し、インストール後も引き継ぐという仕様になっている。
  • つまり、複数のネットワークツールがあるものを、共通のフォーマットで使えるやつ、と理解した。
  • では、nmcliで設定した内容はどうなるの?

nmcli is 何?

  • nmcli は NetworkManager に含まれるツールの一つです
  • つまり、nmcliでは、NetworkManagerの設定がされていた。
  • ちなみにUbuntu 17.10からsystemd-networkdが標準装備。でも、該当のOVAではNetworkManagerを指定していた。(ゆえにnmcliで設定できた。)

実際にubuntu 22.04をデプロイして見てみる。

  • 構築直後のNetPlanの設定
root@ttmp:~# cat /etc/netplan/00-installer-config.yaml
# This is the network config written by 'subiquity'
network:
  ethernets:
    ens160:
      dhcp4: true
    ens192:
      dhcp4: true
  version: 2
root@ttmp:~# 
  • ちなみに、nmcliは入っていない。
root@ttmp:~# nmcli
-bash: nmcli: command not found
root@ttmp:~#
  • さらにちなみにsystemd-networkdはせっせと動いている。
root@ttmp:~# systemctl status systemd-networkd
● systemd-networkd.service - Network Configuration
     Loaded: loaded (/lib/systemd/system/systemd-networkd.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2024-02-26 13:53:15 UTC; 10min ago
TriggeredBy: ● systemd-networkd.socket
       Docs: man:systemd-networkd.service(8)
   Main PID: 655 (systemd-network)
     Status: "Processing requests..."
      Tasks: 1 (limit: 4558)
     Memory: 2.7M
        CPU: 41ms
     CGroup: /system.slice/systemd-networkd.service
             └─655 /lib/systemd/systemd-networkd

Feb 26 13:53:15 ttmp systemd-networkd[655]: lo: Gained carrier
Feb 26 13:53:15 ttmp systemd-networkd[655]: Enumeration completed
Feb 26 13:53:15 ttmp systemd[1]: Started Network Configuration.
Feb 26 13:53:15 ttmp systemd-networkd[655]: ens192: Link UP
Feb 26 13:53:15 ttmp systemd-networkd[655]: ens192: Gained carrier
Feb 26 13:53:15 ttmp systemd-networkd[655]: ens160: Link UP
Feb 26 13:53:15 ttmp systemd-networkd[655]: ens160: Gained carrier
Feb 26 13:53:15 ttmp systemd-networkd[655]: ens160: DHCPv4 address 192.168.11.13/24 via 192.168.11.1
Feb 26 13:53:16 ttmp systemd-networkd[655]: ens192: Gained IPv6LL
Feb 26 13:53:16 ttmp systemd-networkd[655]: ens160: Gained IPv6LL
root@ttmp:~# 
  • 同じ状況を再現するために、network-managerをインストールする。
apt install network-manager
  • インストールするだけではnetwork-managerでは管理してくれない。デバイスのステータスがunmanagedとなっている。
root@ttmp:~# nmcli device status
DEVICE  TYPE      STATE      CONNECTION 
ens160  ethernet  unmanaged  --         
ens192  ethernet  unmanaged  --         
lo      loopback  unmanaged  --         
root@ttmp:~# 
  • ちなみにインストールで/etc/NetworkManager配下にいろいろと作成された。
root@ttmp:~# ll /etc/NetworkManager
total 32
drwxr-xr-x  7 root root 4096 Feb 26 14:09 ./
drwxr-xr-x 87 root root 4096 Feb 26 14:09 ../
-rw-r--r--  1 root root   98 Jun  9  2022 NetworkManager.conf
drwxr-xr-x  2 root root 4096 Feb 26 14:09 conf.d/
drwxr-xr-x  5 root root 4096 Feb 26 14:09 dispatcher.d/
drwxr-xr-x  2 root root 4096 Jun  9  2022 dnsmasq-shared.d/
drwxr-xr-x  2 root root 4096 Jun  9  2022 dnsmasq.d/
drwxr-xr-x  2 root root 4096 Jun  9  2022 system-connections/
root@ttmp:~# 
  • network managerを使うにはnetplanの設定ファイルにrenderer: NetworkManagerと記述するだけで良い模様。
root@ttmp:~# cat /etc/netplan/00-installer-config.yaml
# This is the network config written by 'subiquity'
network:
  version: 2
  renderer: NetworkManager
  ethernets:
    ens160:
      dhcp4: true
    ens192:
      dhcp4: true
  version: 2
root@ttmp:~# 
  • 設定したらnetplan apply。
root@ttmp:~# netplan apply
WARNING:root:Cannot call Open vSwitch: ovsdb-server.service is not running.
root@ttmp:~# 
  • 使えるようになった
root@ttmp:~# nmcli
ens160: connected to netplan-ens160
    "VMware VMXNET3"
    ethernet (vmxnet3), 00:0C:29:D1:6E:72, hw, mtu 1500
    ip4 default
    inet4 192.168.11.13/24
    route4 192.168.11.0/24 metric 100
    route4 default via 192.168.11.1 metric 100
    inet6 fe80::20c:29ff:fed1:6e72/64
    route6 fe80::/64 metric 256

ens192: connecting (getting IP configuration) to netplan-ens192
    "VMware VMXNET3"
    ethernet (vmxnet3), 00:0C:29:D1:6E:7C, hw, mtu 1500

lo: unmanaged
    "lo"
    loopback (unknown), 00:00:00:00:00:00, sw, mtu 65536

DNS configuration:
    servers: 192.168.11.1
    interface: ens160

Use "nmcli device show" to get complete information about known devices and
"nmcli connection show" to get an overview on active connection profiles.

Consult nmcli(1) and nmcli-examples(7) manual pages for complete usage details.
root@ttmp:~# 
  • 管理された。
root@ttmp:~# nmcli device status
DEVICE  TYPE      STATE                                  CONNECTION     
ens160  ethernet  connected                              netplan-ens160 
ens192  ethernet  connecting (getting IP configuration)  netplan-ens192 
lo      loopback  unmanaged                              --             
root@ttmp:~# 
  • IP設定してみる。
  • まずはデバイス名の確認。
root@ttmp:~# nmcli connection show
NAME            UUID                                  TYPE      DEVICE 
netplan-ens160  febc54dc-e29c-3939-a911-8a11855bd1c8  ethernet  ens160
 
netplan-ens192  bc9a68c9-4f66-3ff4-b4b3-cf1b373d9b02  ethernet  --     
root@ttmp:~# 
nmcli connection modify netplan-ens192 ipv4.address 192.168.0.10/24
  • 固定IPが設定されたことを観測。
root@ttmp:~# nmcli device show  ens192
GENERAL.DEVICE:                         ens192
GENERAL.TYPE:                           ethernet
GENERAL.HWADDR:                         00:0C:29:D1:6E:7C
GENERAL.MTU:                            1500
GENERAL.STATE:                          70 (connecting (getting IP configuration))
GENERAL.CONNECTION:                     netplan-ens192
GENERAL.CON-PATH:                       /org/freedesktop/NetworkManager/ActiveConnection/6
WIRED-PROPERTIES.CARRIER:               on
IP4.ADDRESS[1]:                         192.168.0.10/24
IP4.GATEWAY:                            --
IP4.ROUTE[1]:                           dst = 192.168.0.0/24, nh = 0.0.0.0, mt = 101
IP6.ADDRESS[1]:                         fe80::20c:29ff:fed1:6e7c/64
IP6.GATEWAY:                            --
IP6.ROUTE[1]:                           dst = fe80::/64, nh = ::, mt = 256
root@ttmp:~# 
  • IP設定されたことを ip aコマンドで確認
root@ttmp:~# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:d1:6e:72 brd ff:ff:ff:ff:ff:ff
    altname enp3s0
    inet 192.168.11.13/24 brd 192.168.11.255 scope global dynamic noprefixroute ens160
       valid_lft 172443sec preferred_lft 172443sec
    inet6 fe80::20c:29ff:fed1:6e72/64 scope link 
       valid_lft forever preferred_lft forever
3: ens192: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:d1:6e:7c brd ff:ff:ff:ff:ff:ff
    altname enp11s0
    inet 192.168.0.10/24 brd 192.168.0.255 scope global noprefixroute ens192
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fed1:6e7c/64 scope link 
       valid_lft forever preferred_lft forever
root@ttmp:~# 
  • しかし、netplan側は変わらず。
root@ttmp:~# cat /etc/netplan/00-installer-config.yaml
# This is the network config written by 'subiquity'
network:
  version: 2
  renderer: NetworkManager
  ethernets:
    ens160:
      dhcp4: true
    ens192:
      dhcp4: true
  version: 2
root@ttmp:~# 

netplanとどっちが優先されるのだろう?

  • こうしてみる
root@ttmp:~# cat /etc/netplan/00-installer-config.yaml
# This is the network config written by 'subiquity'
network:
  version: 2
  renderer: NetworkManager
  ethernets:
    ens160:
      dhcp4: true
    ens192:
      dhcp4: false
      addresses: [192.168.0.30/24]
  version: 2
root@ttmp:~# 
  • apply
root@ttmp:~# netplan apply
root@ttmp:~# 
  • netplanの設定が有効っぽい
root@ttmp:~# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:d1:6e:72 brd ff:ff:ff:ff:ff:ff
    altname enp3s0
    inet 192.168.11.13/24 brd 192.168.11.255 scope global dynamic noprefixroute ens160
       valid_lft 172784sec preferred_lft 172784sec
    inet6 fe80::20c:29ff:fed1:6e72/64 scope link 
       valid_lft forever preferred_lft forever
3: ens192: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:d1:6e:7c brd ff:ff:ff:ff:ff:ff
    altname enp11s0
    inet 192.168.0.30/24 brd 192.168.0.255 scope global noprefixroute ens192
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fed1:6e7c/64 scope link 
       valid_lft forever preferred_lft forever
root@ttmp:~# 
  • nmcliの設定も上書きされたっぽい
root@ttmp:~# nmcli device show  ens192
GENERAL.DEVICE:                         ens192
GENERAL.TYPE:                           ethernet
GENERAL.HWADDR:                         00:0C:29:D1:6E:7C
GENERAL.MTU:                            1500
GENERAL.STATE:                          100 (connected)
GENERAL.CONNECTION:                     netplan-ens192
GENERAL.CON-PATH:                       /org/freedesktop/NetworkManager/ActiveConnection/2
WIRED-PROPERTIES.CARRIER:               on
IP4.ADDRESS[1]:                         192.168.0.30/24
IP4.GATEWAY:                            --
IP4.ROUTE[1]:                           dst = 192.168.0.0/24, nh = 0.0.0.0, mt = 101
IP6.ADDRESS[1]:                         fe80::20c:29ff:fed1:6e7c/64
IP6.GATEWAY:                            --
IP6.ROUTE[1]:                           dst = fe80::/64, nh = ::, mt = 256
root@ttmp:~# 

教訓とか

  • 設定と環境はちゃんと確認しようという話。OSのネットワーク関連は知識が微妙だったがこれにて深まったので、わりと良かったかも。

Elasticsearch + Logstash + kafka + Filebeatでログ転送し、Kibanaで見る

Elasticsearch + Logstash + kafka + Filebeatでログ転送し、Kibanaで見る

Elasticsearchの構築

  • apt-transport-httpsをインストールします。
apt-get install apt-transport-https
  • Elasticsearchの PGP Keyを追加します。
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo gpg --dearmor -o /usr/share/keyrings/elasticsearch-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/elasticsearch-keyring.gpg] https://artifacts.elastic.co/packages/8.x/apt stable main" | sudo tee /etc/apt/sources.list.d/elastic-8.x.list
  • パッケージのインストールをします。
apt-get update
apt-get install elasticsearch
  • インストールすると以下のように情報が出力されます。今回使用するのはパスワードとトークン生成のコマンドです。
--------------------------- Security autoconfiguration information ------------------------------

Authentication and authorization are enabled.
TLS for the transport and HTTP layers is enabled and configured.

The generated password for the elastic built-in superuser is : 9x5Yi6NsOXW+iwUOkr21

If this node should join an existing cluster, you can reconfigure this with
'/usr/share/elasticsearch/bin/elasticsearch-reconfigure-node --enrollment-token <token-here>'
after creating an enrollment token on your existing cluster.

You can complete the following actions at any time:

Reset the password of the elastic built-in superuser with 
'/usr/share/elasticsearch/bin/elasticsearch-reset-password -u elastic'.

Generate an enrollment token for Kibana instances with 
 '/usr/share/elasticsearch/bin/elasticsearch-create-enrollment-token -s kibana'.

Generate an enrollment token for Elasticsearch nodes with 
'/usr/share/elasticsearch/bin/elasticsearch-create-enrollment-token -s node'.

### NOT starting on installation, please execute the following statements to configure elasticsearch service to start automatically using systemd
 sudo systemctl daemon-reload
 sudo systemctl enable elasticsearch.service
### You can start elasticsearch service by executing
 sudo systemctl start elasticsearch.service
root@ttmp-virtual-machine:~# 
  • OS起動時に起動するように設定しておきます。
root@ttmp-virtual-machine:~# systemctl enable elasticsearch.service
Created symlink /etc/systemd/system/multi-user.target.wants/elasticsearch.service → /lib/systemd/system/elasticsearch.service.
root@ttmp-virtual-machine:~#
  • 動作確認します。
curl --cacert /etc/elasticsearch/certs/http_ca.crt -u elastic https://localhost:9200 
  • json形式の応答が返ってこれば成功です。
root@ttmp-virtual-machine:~/logstash/logstash-8.12.0# curl --cacert /etc/elasticsearch/certs/http_ca.crt -u elastic https://localhost:9200 
Enter host password for user 'elastic':
{
  "name" : "ttmp-virtual-machine",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "-3HRShG-RP2ZJcQ2e-tNdw",
  "version" : {
    "number" : "8.12.0",
    "build_flavor" : "default",
    "build_type" : "deb",
    "build_hash" : "1665f706fd9354802c02146c1e6b5c0fbcddfbc9",
    "build_date" : "2024-01-11T10:05:27.953830042Z",
    "build_snapshot" : false,
    "lucene_version" : "9.9.1",
    "minimum_wire_compatibility_version" : "7.17.0",
    "minimum_index_compatibility_version" : "7.0.0"
  },
  "tagline" : "You Know, for Search"
}
root@ttmp-virtual-machine:~/logstash/logstash-8.12.0# 
  • indexを作成するには、以下のように実行します。
root@ttmp-virtual-machine:~# export index_name="test"
root@ttmp-virtual-machine:~# curl -X PUT --cacert /etc/elasticsearch/certs/http_ca.crt -u elastic "https://localhost:9200/${index_name}?pretty"
Enter host password for user 'elastic':
{
  "acknowledged" : true,
  "shards_acknowledged" : true,
  "index" : "test"
}
root@ttmp-virtual-machine:~# 

Kibanaの構築

  • パッケージのインストールをします。
apt install kibana
  • KibanaをOS起動時に起動するようにします。
systemctl daemon-reload
systemctl enable kibana.service
  • http://${IP}:5601/にアクセスして、以下のような画面が出ればOKです。
  • tokenを生成します。ここで出力された文字列を先ほど表示された画面に貼り付けて、Configure Elasticを押下します。
/usr/share/elasticsearch/bin/elasticsearch-create-enrollment-token -s kibana
  • すると数字を入力するように促されます。また、以下のコマンドを実行するように促されるので、実行し、数字を取得します。取得した数字を画面に入力すればOKです。
/usr/share/kibana/bin/kibana-verification-code
  • Kibanaの画面が表示されました。

Logstash構築

  • モジュールをダウンロードし、解凍します。
wget https://artifacts.elastic.co/downloads/logstash/logstash-8.12.0-linux-x86_64.tar.gz
tar -xzf logstash-8.12.0-linux-x86_64.tar.gz
cd logstash-8.12.0
  • 設定ファイルを編集します。事前にindexを作成しておきます。たとえばCSVファイルを取得する時は以下のようにします。
root@ttmp-virtual-machine:~/logstash/logstash-8.12.0# cat config/logstash.conf
input {
    file {
        mode => "tail"
        path => ["/root/logstash/logstash-8.12.0/log/*_log.csv"]
        sincedb_path => "/root/logstash/logstash-8.12.0/log/sincedb"
        start_position => "beginning"
        codec => plain { 
            charset => "UTF-8"
        }
    }
}

filter {
    csv {
        columns => ["Date", "Level", "ErrorMessage","UserId"]
        convert => {
            "UserId" => "integer"
        }
        skip_header => true
    }
    date {
        match => ["Date", "yyyy-MM-dd HH:mm:ss"]
    }
}

output {
    elasticsearch {
        hosts => ["https://localhost:9200"]
        index => "log"
        ssl_certificate_verification => false
        user => "elastic"
        password => "elastic"
    }
    stdout {
        codec => rubydebug
    }
}
root@ttmp-virtual-machine:~/logstash/logstash-8.12.0# 
  • kafka連携する場合は、以下のようにします。まだkafkaが構築できていないので、いったんここまでです。
root@ttmp-virtual-machine:~/logstash/logstash-8.12.0# cat config/kafka.conf 
input {
    kafka {
        bootstrap_servers => "localhost:9092"
        topics => ["quickstart-events"]
    }
}

output {
    elasticsearch {
        hosts => ["https://localhost:9200"]
        index => "log2"
        ssl_certificate_verification => false
        user => "elastic"
        password => "elastic"
    }
    stdout {
        codec => rubydebug
    }
}
root@ttmp-virtual-machine:~/logstash/logstash-8.12.0# 

kafka構築

  • インストールし、解凍、設定します。
wget https://downloads.apache.org/kafka/3.5.1/kafka_2.12-3.5.1.tgz
tar xzf kafka_2.12-3.5.1.tgz
mv kafka_2.12-3.5.1 /usr/local/kafka
apt install openjdk-8-jre-headless
  • kafkaの起動は以下のサービスを起動します。
sudo systemctl restart zookeeper
sudo systemctl restart kafka
  • 動作確認をします。ディレクトリを移動しましょう。(内容はkafkaのクイックスタートの内容です。)
cd /usr/local/kafka
  • topicの作成
bin/kafka-topics.sh --create --topic quickstart-events --bootstrap-server localhost:9092
  • topicへの書き込み
bin/kafka-console-producer.sh --topic quickstart-events --bootstrap-server localhost:9092
  • topicからの読み込み
bin/kafka-console-consumer.sh --topic quickstart-events --from-beginning --bootstrap-server localhost:9092

filebeats構築

  • Filebeat をインストールします。
apt -y install filebeat
  • /etc/filebeat/filebeat.ymlを構成します。kafkaのアドレス等をしていします。
root@ttmp-virtual-machine:~/logstash/logstash-8.12.0# cat /etc/filebeat/filebeat.yml
filebeat.inputs:

- type: filestream

  id: my-filestream-id

  enabled: true

  paths:
    - /var/log/*.log

filebeat.config.modules:
  path: ${path.config}/modules.d/*.yml

  reload.enabled: false

setup.template.settings:
  index.number_of_shards: 1

setup.kibana:
output.kafka:
  hosts: ["localhost:9092"]
  topic: "quickstart-events"
  partition.round_robin:
    reachable_only: false
  required_acks: 1
  compression: gzip
  max_message_bytes: 1000000

processors:
  - add_host_metadata:
      when.not.contains.tags: forwarded
  - add_cloud_metadata: ~
  - add_docker_metadata: ~
  - add_kubernetes_metadata: ~

root@ttmp-virtual-machine:~/logstash/logstash-8.12.0# 
  • /etc/filebeat/filebeat.reference.ymlを構成します。かなり長いファイルなので、抜粋です。
 1 ######################## Filebeat Configuration ############################
   2 
   3 # This file is a full configuration example documenting all non-deprecated
   4 # options in comments. For a shorter configuration example, that contains only
   5 # the most common options, please see filebeat.yml in the same directory.
   6 #
   7 # You can find the full configuration reference here:
   8 # https://www.elastic.co/guide/en/beats/filebeat/index.html
   9 
  10 
  11 #==========================  Modules configuration =============================
  12 filebeat.modules:
  13 
  14 #-------------------------------- System Module --------------------------------
  15 - module: system
  16    Syslog
  17   syslog:
  18     enabled: true

実行

  • Elasticsearchはサービスとして起動しています。またkafkaも同様です。なので、LogstashとFilebeatを起動します。
  • Logstashを起動します
bin/logstash -f config/kafka.conf 
  • Filebeatsを起動します。
systemctl enable --now filebeat
  • Logstash側には取得したデータが出力されます。
{
         "event" => {
        "original" => "{\"@timestamp\":\"2024-01-30T13:30:04.537Z\",\"@metadata\":{\"beat\":\"filebeat\",\"type\":\"_doc\",\"version\":\"8.12.0\"},\"log\":{\"offset\":23898,\"file\":{\"device_id\":\"2051\",\"inode\":\"538374\",\"path\":\"/var/log/auth.log\"}},\"message\":\"Jan 30 22:30:01 ttmp-virtual-machine CRON[5123]: pam_unix(cron:session): session closed for user root\",\"input\":{\"type\":\"filestream\"},\"ecs\":{\"version\":\"8.0.0\"},\"host\":{\"containerized\":false,\"ip\":[\"192.168.11.11\",\"fe80::e996:c5c2:2a4d:604c\"],\"mac\":[\"00-0C-29-2A-D6-DD\"],\"name\":\"ttmp-virtual-machine\",\"hostname\":\"ttmp-virtual-machine\",\"architecture\":\"x86_64\",\"os\":{\"version\":\"22.04.3 LTS (Jammy Jellyfish)\",\"family\":\"debian\",\"name\":\"Ubuntu\",\"kernel\":\"6.5.0-15-generic\",\"codename\":\"jammy\",\"type\":\"linux\",\"platform\":\"ubuntu\"},\"id\":\"57212799f4764d7694dd1596f388870b\"},\"agent\":{\"version\":\"8.12.0\",\"ephemeral_id\":\"282a73ce-7ae7-4b70-a951-6afb4d2a673f\",\"id\":\"8494c139-c901-4048-bd69-3ca6a2c519fe\",\"name\":\"ttmp-virtual-machine\",\"type\":\"filebeat\"}}"
    },
    "@timestamp" => 2024-01-30T13:30:16.036577925Z,
      "@version" => "1",
       "message" => "{\"@timestamp\":\"2024-01-30T13:30:04.537Z\",\"@metadata\":{\"beat\":\"filebeat\",\"type\":\"_doc\",\"version\":\"8.12.0\"},\"log\":{\"offset\":23898,\"file\":{\"device_id\":\"2051\",\"inode\":\"538374\",\"path\":\"/var/log/auth.log\"}},\"message\":\"Jan 30 22:30:01 ttmp-virtual-machine CRON[5123]: pam_unix(cron:session): session closed for user root\",\"input\":{\"type\":\"filestream\"},\"ecs\":{\"version\":\"8.0.0\"},\"host\":{\"containerized\":false,\"ip\":[\"192.168.11.11\",\"fe80::e996:c5c2:2a4d:604c\"],\"mac\":[\"00-0C-29-2A-D6-DD\"],\"name\":\"ttmp-virtual-machine\",\"hostname\":\"ttmp-virtual-machine\",\"architecture\":\"x86_64\",\"os\":{\"version\":\"22.04.3 LTS (Jammy Jellyfish)\",\"family\":\"debian\",\"name\":\"Ubuntu\",\"kernel\":\"6.5.0-15-generic\",\"codename\":\"jammy\",\"type\":\"linux\",\"platform\":\"ubuntu\"},\"id\":\"57212799f4764d7694dd1596f388870b\"},\"agent\":{\"version\":\"8.12.0\",\"ephemeral_id\":\"282a73ce-7ae7-4b70-a951-6afb4d2a673f\",\"id\":\"8494c139-c901-4048-bd69-3ca6a2c519fe\",\"name\":\"ttmp-virtual-machine\",\"type\":\"filebeat\"}}"
}
  • kibanaで取り込まれているかを確認します。
  • 取り込まれていることが確認できました。

vyosでプライベートLAN内のVMをインターネット接続し、名前解決可能にする

vyosでプライベートLAN内のVMをインターネット接続し、名前解決可能にする

  • LAB用にEsxi上に開発LANというプライベートLAN環境を引きました。
  • そこに配置したVMからインターネットに接続し、名前解決可能な状態にします。

構成

  • 以下のような構成を考え、VM2から配置したvyosから家庭内LANを通してインターネット接続可能なように設定します。
  • VM1
    • 家庭内LAN側:192.168.11.41
    • 開発LAN側:172.16.1.2
  • VM2
    • 開発LAN側:172.16.1.3
  • vyos
    • 家庭内LAN側:192.168.11.7
    • 開発LAN側:172.16.1.1

SNATの設定

  • 今回設定するのはSNATの設定だけです。
  • 以下はvyosのIP構成です。
vyos@vyos:~$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:33:0d:58 brd ff:ff:ff:ff:ff:ff
    inet 192.168.11.7/24 brd 192.168.11.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe33:d58/64 scope link 
       valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 00:0c:29:33:0d:62 brd ff:ff:ff:ff:ff:ff
    inet 172.16.1.1/24 brd 172.16.1.255 scope global eth1
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe33:d62/64 scope link 
       valid_lft forever preferred_lft forever
vyos@vyos:~$ 
  • インターネット(家庭内LAN)に面しているインターフェースにSNATの設定を行います。
  • 設定前だと以下のように名前解決ができません。
root@ttmp-virtual-machine:~# dig @8.8.8.8 google.com
;; communications error to 8.8.8.8#53: timed out
^Croot@ttmp-virtual-machine:~#
  • 以下のようにSNATを設定してみます。
vyos@vyos# set nat source rule 108 outbound-interface eth0
[edit]
vyos@vyos# set nat source rule 108 source address 172.16.1.0/24
[edit]
vyos@vyos# set nat source rule 108 translation address 192.168.11.7
[edit]
vyos@vyos# commit
[edit]
vyos@vyos# save
Saving configuration to '/config/config.boot'...
Done
[edit]
vyos@vyos# 
  • インターネット接続ができるようになり、外部のNAME_SERVER_IPに接続できるようになったため、名前解決できるようになりました。
root@ttmp-virtual-machine:~# dig @8.8.8.8 google.com

; <<>> DiG 9.18.18-0ubuntu0.22.04.1-Ubuntu <<>> @8.8.8.8 google.com
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 58886
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;google.com.            IN  A

;; ANSWER SECTION:
google.com.     171 IN  A   172.217.26.238

;; Query time: 4 msec
;; SERVER: 8.8.8.8#53(8.8.8.8) (UDP)
;; WHEN: Sun Jan 14 08:32:11 JST 2024
;; MSG SIZE  rcvd: 55

root@ttmp-virtual-machine:~# 

zabbixをansibleで設定する(2) - mail発報する -

zabbixをansibleで設定する(2) - mail発報する -

  • zabbixを使った監視でmail発報させるまでの手順をまとめます。
  • 設定はansibleで実装します。
  • zabbixはインストール直後、初期設定はすませているものとします。

設定の段取り

  • 設定としては、以下のような感じになります。
  • 監視内容を決定します。今回はpingによる生死監視とします。
  • 監視の内容をitemとして定義します。
  • 発報の条件をtrigerとして定義します。
  • itemtrigerの内容でtemplateを定義します。
  • templateをansibleでzabbixに適用します。
  • host_groupを登録します。
  • 監視対象をhostとして、ansibleでzabbixに適用します。この時、事前に設定したhost_groupに所属させます。
  • Media typesをansibleでzabbixに適用します。この時、送信メールアドレスのSMTPサーバー等を設定します。
  • 監視時に発報するUsersをansibleで適用します。この時、メール発報するMedia typesを指定します。
  • trigerで検知した際に発報するユーザーをTrigger actionsで登録します。

監視の内容をitemとして、発報の条件をtrigerとして定義

  • 以下のように定義します。
  • 手作業でjsonファイルを記述するのは大変なので、WEBインターフェースで定義したものをエクスポートし、雛形とすると楽です。
                "items": [                        
                    {                                     
                        "uuid": "49d5b82ce05446439dda6a1319b9f357",
                        "name": "ping",                                                            
                        "type": "SIMPLE",                              
                        "key": "icmpping",                               
                        "delay": "3s",                                    
                        "triggers": [                                 
                            {                                        
                                "uuid": "c57b2a8f635b41439a0fa3669a803a75",
                                "expression": "last(/testtest/icmpping,#1)=0",                             
                                "name": "pingcheck",                                                          
                                "priority": "HIGH"                                  
                            }                                                     
                        ]                                    
                    }                                    
                ]

itemtrigerの内容でtemplateを定義

  • 以下のように定義します。
{
    "zabbix_export": {
        "version": "6.0",
        "date": "2024-01-07T02:05:29Z",
        "groups": [
            {
                "uuid": "846977d1dfed4968bc5f8bdb363285bc",
                "name": "Templates/Operating systems"
            }
        ],
        "templates": [
            {
                "uuid": "f8f7908280354f2abeed07dc788c3747",
                "template": "testtest",
                "name": "test",
                "description": "Official Linux template. Requires agent of Zabbix 6.0 or newer.\n      \nYou can discuss this template or leave feedback on our forum https://www.zabbix.com/forum/zabbix-suggestions-and-feedback/387225-discussion-thread-for-official-zabbix-template-for-linux\n\nGenerated by official Zabbix template tool \"Templator\"",
                "groups": [
                    {
                        "name": "Templates/Operating systems"
                    }
                ],
                "items": [
            {
                        "uuid": "49d5b82ce05446439dda6a1319b9f357",
                        "name": "ping",
                        "type": "SIMPLE",
                        "key": "icmpping",
                        "delay": "3s",
                        "triggers": [
                            {
                                "uuid": "c57b2a8f635b41439a0fa3669a803a75",
                                "expression": "last(/testtest/icmpping,#1)=0",
                                "name": "pingcheck",
                                "priority": "HIGH"
                            }
                        ]
                    }
                ]
            }
        ]
    }
}
  • これをansibleで適用するには以下のようにtaskを構成して適用します。
  • community.zabbix.zabbix_templateモジュールを使います。lookupを使用してjsonファイルを探します。
- name: Import templates from JSON
  community.zabbix.zabbix_template:
    template_json: "{{ lookup('file', 'template.json') }}"
    state: present
  • 以下のplaybookで適用します。
---
- hosts: all
  gather_facts: no
  roles:
    - zabbix_setting
  • 実行します
(zabbix_setting) ttmp@ttmp-virtual-machine:~/dev/zabbix_setting$ ansible-playbook -i hosts pb.yml --limit kanshi2 -K
BECOME password: 

PLAY [all] **************************************************************************************************************************

TASK [zabbix_setting : Import templates from JSON] **********************************************************************************
changed: [kanshi2]

PLAY RECAP **************************************************************************************************************************
kanshi2                    : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

(zabbix_setting) ttmp@ttmp-virtual-machine:~/dev/zabbix_setting$ 
  • 適用されました。

host_groupの登録

  • host_groupcommunity.zabbix.zabbix_groupを使います。
  • 以下にコードを記載します。
- name: add_hostgroup                                
  community.zabbix.zabbix_group:
    state: present
    host_groups: "testgrp"
  • 実行します。
(zabbix_setting) ttmp@ttmp-virtual-machine:~/dev/zabbix_setting$ ansible-playbook -i hosts pb.yml --limit kanshi2 -K
BECOME password: 

PLAY [all] **************************************************************************************************************************

TASK [zabbix_setting : Import templates from JSON] **********************************************************************************
changed: [kanshi2]

TASK [zabbix_setting : add_hostgroup] ***********************************************************************************************
changed: [kanshi2]

PLAY RECAP **************************************************************************************************************************
kanshi2                    : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

(zabbix_setting) ttmp@ttmp-virtual-machine:~/dev/zabbix_setting$ 
  • 適用されました。

監視対象をhostを登録

  • 事前に設定したhost_groupに所属させます。
  • また事前に作成したtenmplateをリンクさせます。
- name: Create a new host or rewrite an existing host's info
  community.zabbix.zabbix_host:
    host_name: ExampleHost
    visible_name: ExampleName
    description: My ExampleHost Description
    host_groups:
      - "testgrp"  
    link_templates:
      - "testtest"
    status: enabled
    state: present
    interfaces:
      - type: 1
        main: 1
        useip: 1
        ip: 192.168.11.47
        dns: ""
        port: "10050"
  • 適用します。
(zabbix_setting) ttmp@ttmp-virtual-machine:~/dev/zabbix_setting$ ansible-playbook -i hosts pb.yml --limit kanshi2 -K
BECOME password: 

PLAY [all] **************************************************************************************************************************

TASK [zabbix_setting : Import templates from JSON] **********************************************************************************
changed: [kanshi2]

TASK [zabbix_setting : add_hostgroup] ***********************************************************************************************
ok: [kanshi2]

TASK [zabbix_setting : Create a new host or rewrite an existing host's info] ********************************************************
changed: [kanshi2]

PLAY RECAP **************************************************************************************************************************
kanshi2                    : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

(zabbix_setting) ttmp@ttmp-virtual-machine:~/dev/zabbix_setting$ 
  • 登録されました。

Media typesの適用

  • 送信メールアドレスのSMTPサーバー等を設定します。
- name: "Create an email mediatype with SMTP authentication"
  # set task level variables as we change ansible_connection plugin here
  community.zabbix.zabbix_mediatype:
    name: "Ops email"
    type: "email"
    smtp_server: "example.com"
    smtp_server_port: 2000
    smtp_email: "ops@example.com"
    smtp_authentication: true
      smtp_security: STARTTLS
    username: "smtp_user"
    password: "smtp_pass"
  • 上記は適当な値を入れていますが、実際にはメール送信可能な情報を記述します。また、パスワードなどの情報はvaultに保存すべきです。
  • 実行します。
(zabbix_setting) ttmp@ttmp-virtual-machine:~/dev/zabbix_setting$ ansible-playbook -i hosts pb.yml --limit kanshi2 -K
BECOME password: 

PLAY [all] **************************************************************************************************************************

TASK [zabbix_setting : Import templates from JSON] **********************************************************************************
changed: [kanshi2]

TASK [zabbix_setting : add_hostgroup] ***********************************************************************************************
ok: [kanshi2]

TASK [zabbix_setting : Create a new host or rewrite an existing host's info] ********************************************************
ok: [kanshi2]

TASK [zabbix_setting : Create an email mediatype with SMTP authentication] **********************************************************
changed: [kanshi2]

PLAY RECAP **************************************************************************************************************************
kanshi2                    : ok=4    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

(zabbix_setting) ttmp@ttmp-virtual-machine:~/dev/zabbix_setting$ 
  • 適用されました。
  • テストしてみると良いでしょう。メール送信の単体確認ができます。

監視時に発報するUsersを適用

  • メール発報するMedia typesを指定します。
  • community.zabbix.zabbix_userを使用します。
- name: create a new zabbix user.
  community.zabbix.zabbix_user:
    username: Admin2
    name: Zabbix2
    surname: Administrator2
    usrgrps:
      - Zabbix administrators
    passwd: zabbixzabbix
    lang: default
    theme: default
    autologin: "1"
    autologout: "0"
    refresh: "30s"
    rows_per_page: "200"
    user_medias:
      - mediatype: Ops email
        sendto:
          - example@example.com
          - example1@example.com
        period: 1-7,00:00-24:00
        severity:
          not_classified: no
          information: yes
          warning: yes
          average: yes
          high: yes
          disaster: yes
        active: yes
    state: present
  • 実行します。
(zabbix_setting) ttmp@ttmp-virtual-machine:~/dev/zabbix_setting$ ansible-playbook -i hosts pb.yml --limit kanshi2 -K
BECOME password: 

PLAY [all] **************************************************************************************************************************

TASK [zabbix_setting : Import templates from JSON] **********************************************************************************
changed: [kanshi2]

TASK [zabbix_setting : add_hostgroup] ***********************************************************************************************
ok: [kanshi2]

TASK [zabbix_setting : Create a new host or rewrite an existing host's info] ********************************************************
ok: [kanshi2]

TASK [zabbix_setting : Create an email mediatype with SMTP authentication] **********************************************************
ok: [kanshi2]

TASK [zabbix_setting : create a new zabbix user.] ***********************************************************************************
changed: [kanshi2]

PLAY RECAP **************************************************************************************************************************
kanshi2                    : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

(zabbix_setting) ttmp@ttmp-virtual-machine:~/dev/zabbix_setting$ 
  • 適用されました。
  • media typeも設定されました。

trigerで検知した際に発報するユーザーをTrigger actionsで登録

  • 以下のようにtrigger_severityhighの時に発砲するようにしてみます。
- name: Deploy trigger action
  community.zabbix.zabbix_action:
    name: "Send alerts to Admin"
    event_source: "trigger"
    state: present
    status: enabled
    esc_period: 60
    conditions:
      - type: "trigger_severity"
        operator: "equals"        
        value: "high"              
    operations:
      - type: send_message
        subject: "Something bad is happening"
        op_message: "Come on, guys do something"
        media_type: "Ops email"
        send_to_users:
          - "Admin2"
  • 実行します
(zabbix_setting) ttmp@ttmp-virtual-machine:~/dev/zabbix_setting$ ansible-playbook -i hosts pb.yml --limit kanshi2 -K
BECOME password: 

PLAY [all] **************************************************************************************************************************

TASK [zabbix_setting : Import templates from JSON] **********************************************************************************
changed: [kanshi2]

TASK [zabbix_setting : add_hostgroup] ***********************************************************************************************
ok: [kanshi2]

TASK [zabbix_setting : Create a new host or rewrite an existing host's info] ********************************************************
ok: [kanshi2]

TASK [zabbix_setting : Create an email mediatype with SMTP authentication] **********************************************************
ok: [kanshi2]

TASK [zabbix_setting : create a new zabbix user.] ***********************************************************************************
ok: [kanshi2]

TASK [zabbix_setting : Deploy trigger action] ***************************************************************************************
changed: [kanshi2]

PLAY RECAP **************************************************************************************************************************
kanshi2                    : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

(zabbix_setting) ttmp@ttmp-virtual-machine:~/dev/zabbix_setting$ 
  • 適用されました。
  • 発報してみます。
  • actionが起動しました。
  • メールも送信されました。

zabbixをansibleで設定する(1) - host_groupの追加 -

zabbixをansibleで設定する(1) - host_groupの追加 -

  • まったり少しづつ、ansibleを使ってzabbixの設定をする記事を書いていこうと思います。
  • 今回はhost_groupの追加です。

前提

  • ansible [core 2.16.2]で実施しています。

準備

  • 必要なモジュールをインストールします。ansibleで各種設定を行うにはzabbix-apiが必要です。
pip install zabbix-api

ansibleで構築するには

  • ainsbleで構築するにはansible_connectionhttpapiにする必要があります。
  • ansible_connectionはデフォルトではssh接続するようです。
  • 以下はgroup_varsへ記述した場合の設定例です。
---                                                  
ansible_port: 22                                                                                
ansible_user: Admin                                                               
ansible_httpapi_pass: zabbix                                          
ansible_network_os: community.zabbix.zabbix                                
ansible_connection: httpapi                                
ansible_httpapi_port: 80                                
http_login_user: Admin                                
http_login_password: zabbix                                
target_groups:                                
  - "test group1"                                
  - "test group2"

host_groupの登録

  • community.zabbix.zabbix_groupを使います。
  • 以下はroleとして記述した場合の例です。
- name: add_hostgroup
  community.zabbix.zabbix_group:
    state: present
    host_groups: "{{ target_groups }}"   
  • 実行してみます。
(zabbix_setting) ttmp@ttmp-virtual-machine:~/dev/zabbix_setting$ ansible-playbook pb.yml -i hosts --limit kanshi

PLAY [all] ****************************************************************************************************************************

TASK [zabbix_setting : add_hostgroup] *************************************************************************************************
changed: [kanshi]

PLAY RECAP ****************************************************************************************************************************
kanshi                     : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

(zabbix_setting) ttmp@ttmp-virtual-machine:~/dev/zabbix_setting$ 
  • 追加されました。

NSX-Tでオーバーレイネットワークを試してみる - NSX-Tデプロイ編

NSX-Tでオーバーレイネットワークを試してみる - NSX-Tデプロイ編

  • 次ににNSX-Tをデプロイしてみます。
  • ovaファイルからデプロイします。ovaVMWareのサイトからダウンロードしてきます。
  • https://customerconnect.vmware.com/evalcenter?p=nsx-t-eval
  • 新規仮想マシンovaから展開します。
  • 名前をつけ、ovaファイルを選択します。
  • ストレージを選択し、デプロイオプションを指定します。今回は検証用なのでsmallを指定します。
  • ちなみにsmallは検証用途として使うのが適切であり、本番環境では推奨されていないようです。
  • その他の設定をします。最低限に必要なパスワードの設定くらいをしておきます。(SSHの有効化は検証環境では便利なので設定しています。)
  • ちなみにroot または admin ユーザーのパスワードが複雑さの要件を満たしていない場合には、root または admin として SSH 経由またはコンソール経由で NSX Manager にログインし、設定する必要があります。(デフォルトのパスワードが設定されているので、ログインにて変更する形式のようです。)
  • 完了ボタンを押して、デプロイを開始します。
  • smallの場合、インストールに時間がかかるようです。(CPUコア数が少ないための模様。)
  • まだ準備ができていない状態で管理画面にアクセスすると、こんな感じになったりします。
  • デプロイが完了すると管理画面にアクセスできるようになります。
  • デプロイ完了しました。
  • つづく。