
私はいくつかのAnsibleプレイブックを持っています:
---
- hosts: servers
gather_facts: false
become: yes
ignore_errors: yes
tasks:
- include_vars: users.yml
- name: Check that user exists
shell: "grep -q {{item.username}} /etc/passwd"
ignore_errors: yes
with_items: "{{ users }}"
register: userexist
- name: Block user
user:
name: "{{ item.username }}"
shell: /bin/false
when: userexist is succeeded
with_items: "{{ userexist.results }}"
プレイブックは正常に動作しますが、ユーザーがファイル /etc/passwd に存在しない場合、プレイブックは "rc": 1 を取得するため、タスク "Block user" をスキップします。ユーザーが存在しない場合に、 "rc": 1 を正しく無視して、タスク "Block user" を実行するにはどうすればよいでしょうか。
答え1
リストのすべてのエントリに対して、両方のタスクが一緒に実行されるようにする必要があります。現在、最初のタスクのユーザー名は 1 つだけが 2 番目のタスクで使用されます。
理論的にはこれは理想的ですブロックただし、ブロックとループを組み合わせることはできません。これを回避するには、実際のタスクを別の .yml ファイルに移動して含めることができます。
プレイブック.yml:
---
- hosts: servers
gather_facts: false
become: yes
vars:
users:
- blah: blubb
username: nagios
- blubb: bleh
username: foobar
tasks:
- name: set shell
include_tasks: set_shell.yml
loop: "{{ users }}"
シェルの設定
---
- name: Check that user exists
shell: "grep -q {{ item.username }} /etc/passwd"
ignore_errors: yes
register: userexist
- name: Block user
user:
name: "{{ item.username }}"
shell: /bin/false
when: userexist is succeeded
これにより、リスト内の各ユーザーに対して両方のタスクが順番に実行されます。