Skip to main content
  1. Posts/

[Ansible] ファイルにある行が存在することを保証する

·187 words·1 min
Ansible
  1. ファイルにある行が存在することを保証する
  2. 共通タスクにする

ファイルにある行が存在することを保証する
#

以下の 2 ステップで行います。

  1. ファイルが行に存在するか確認する。
  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
#