cron.d
みたいな感じで bash でログインしたときに自動実行されるファイル群が /etc/profile.d/
にあるけど、
これを各ユーザ毎にも実施したい話。
コンセプト
各ユーザごとに ~/.bash.d
配下の実行権限がついてるファイルをログイン時に読み込むようにする。
rootで準備
こんな感じで配置。
/etc/profile.d/bash.d.sh
[ -d ~/.bash.d ] && while read x; do source $x; done < <(find ~/.bash.d/* -type f -executable)
各ユーザで準備の例
~/.bash.d/hoge
export HOGE=123
chmod +x ~/.bash.d/hoge
で実行権限付けておく。
これでログイン時に $HOGE
が設定される。
ハンズオン
Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.box = "centos/7"
# とか
#config.vm.box = "bento/ubuntu-16.04"
end
hosts.yml
servers:
hosts:
default
vars:
ansible_ssh_common_args: -F ssh_config
main.yml
---
- hosts: servers
tasks:
- name: init bash.d
become: yes
become_user: root
shell: >
echo
'[ -d ~/.bash.d ] && while read x; do source $x; done < <(find ~/.bash.d/* -type f -executable)'
> /etc/profile.d/bash.d.sh
args:
creates: /etc/profile.d/bash.d.sh
- name: init user dir
file: path=~/.bash.d
state: directory
- name: sample env
shell: |
echo 'export HOGE=123' > ~/.bash.d/hoge
chmod +x ~/.bash.d/hoge
args:
creates: ~/.bash.d/hoge
構築
vagrant up
してから vagrant ssh-config > ssh_config
しておく。
ansible-playbook -i hosts.yml main.yml
確認
vagrant ssh -c 'echo $HOGE'
その他
何が嬉しいか?
単純に ~/.bash_profile
を分割できるのと、
ansible
の冪等チェックに args.creates
を使うことが多いと思うけど、
タスクごとに ~/.bash.d/{env_for_some_task}
を放り込んでおけば、
それがそのまま環境変数と冪等チェックに両方使えて嬉しい感じ。
二重追記されて汚くなった、みたいなことがなくなる。はず。
あと、副次的に cron 起動する際 ~/.bash_profile
一気読みだと都合が悪い時とかに、必要な環境変数だけ読むようにできたり。
実行権限要る?
on/off の切り替えが楽なのでやってるけど、趣味の範囲。
そのへんはお好みで。