シェルスクリプトとAnsibleの冪等性作りこみの例
プロセスの起動の冪等性
例: nginxのプロセス起動の冪等性
code:shell
PROCESS_NAME="nginx"
SERVICE_NAME="nginx"
# プロセスの存在確認
if ps aux | grep -v grep | grep "$PROCESS_NAME" > /dev/null
then
echo "$PROCESS_NAME is already running."
else
echo "$PROCESS_NAME is not running. Starting $SERVICE_NAME."
systemctl start "$SERVICE_NAME"
echo "$SERVICE_NAME started."
fi
code:yaml
---
- name: Ensure nginx is running
hosts: localhost
become: true
tasks:
- name: Check if nginx is running
ansible.builtin.service:
name: nginx
state: started
ユーザーの作成
例:
code:shell
FILE_PATH="/path/to/file.txt"
# ファイルが存在しない場合のみ作成する
touch "$FILE_PATH"
echo "File created."
else
echo "File already exists."
fi
code:yaml
---
- name: Ensure the file exists
hosts: localhost
tasks:
- name: Create file if it doesn't exist
ansible.builtin.file:
path: /path/to/file.txt
state: touch
パッケージのインストール
code:shell
PACKAGE_NAME="git"
# パッケージがインストールされているかを確認し、未インストールならインストール
if dpkg -l | grep -q "$PACKAGE_NAME"; then
echo "$PACKAGE_NAME is already installed."
else
sudo apt-get install -y "$PACKAGE_NAME"
echo "$PACKAGE_NAME installed."
fi
code:yaml
---
- name: Ensure the package is installed
hosts: localhost
become: true
tasks:
- name: Install git package if not installed
ansible.builtin.apt:
name: git
state: present
設定ファイルの修正
code:shell
CONFIG_FILE="/etc/sysctl.conf"
SETTING="net.ipv4.ip_forward=1"
# 設定がファイルに存在しない場合のみ追記する
if grep -q "$SETTING" "$CONFIG_FILE"; then
echo "Setting already exists."
else
echo "$SETTING" >> "$CONFIG_FILE"
sysctl -p
echo "Setting applied."
fi
code:yaml
---
- name: Ensure the setting is present in the config file
hosts: localhost
become: true
tasks:
- name: Add setting if not present
ansible.builtin.lineinfile:
path: /etc/sysctl.conf
line: "net.ipv4.ip_forward=1"
- name: Apply sysctl settings
ansible.builtin.command:
cmd: sysctl -p