ファイルにある行が存在することを保証する #
以下の 2 ステップで行います。
- ファイルが行に存在するか確認する。
- 存在しなければ行を追加する
今回は行をファイルのどの位置に追加するかは制御していません。必要が出てきたらまた調べます。
これで /etc/bar に "foooooo" という文字列が存在しなければ追加するという処理を行います。
---
- name: foooooo がファイル内に存在するか確認
shell: grep -c "foooooo" /etc/bar
register: lines_count
ignore_errors: yes
- name: foooooo がファイル内に存在しなければ追加する
lineinfile:
path: "foooooo"
line: "/etc/bar"
when: lines_count.stdout == "0"
共通タスクにする #
構成は ansible の best practice{:target="_blank"} を参考に以下のようにします。
必要なパスだけ書いています。
roles
|--common
| `--tasks
| `--ensure_a_line_exists.yml
|
`--k8s
`--tasks
`--main.yml
以下のようにすると、roles/k8s/tasks/main.ymlのタスクを実行すると.bashrcにある行が存在する状態にできます。
roles/common/tasks/ensure_a_line_exists.yml
---
- name: Test if {{ item.line }} exists in {{ item.path }}
shell: grep -c "{{ item.line }}" {{ item.path }}
register: lines_count
ignore_errors: yes # if shell returns 0, it fails. So you need to write this line.
- name: Set {{ item.line }} in {{ item.path }} if not exists
lineinfile:
path: "{{ item.path }}"
line: "{{ item.line }}"
when: lines_count.stdout == "0"
roles/k8s/tasks/main.yml
- name: ensure_lines_in_bashrc
with_items:
- {
path: "{{ ansible_env.HOME }}/.bashrc",
line: "source <(kubectl completion bash)",
}
- { path: "{{ ansible_env.HOME }}/.bashrc", line: "alias k=kubectl" }
- {
path: "{{ ansible_env.HOME }}/.bashrc",
line: "complete -F __start_kubectl k",
}
include_role:
name: common
tasks_from: ensure_a_line_exists
Reference #
- Ansible best practice https://docs.ansible.com/ansible/2.8/user_guide/playbooks_best_practices.html#directory-layout{:target="_blank"}
- role のタスクを共通化する https://stackoverflow.com/questions/30192490/include-tasks-from-another-role-in-ansible-playbook{:target="_blank"}
- with_items の要素を dict にする https://www.kabegiwablog.com/entry/2018/04/24/110000{:target="_blank"}