如何透過 ansible 為使用者更改 shell?

如何透過 ansible 為使用者更改 shell?

我有一些 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。時,任務「阻止用戶」?

答案1

您需要確保清單中的每個條目都同時執行這兩個任務。目前,第二個任務中只會使用第一個任務中的一個使用者名稱。

從理論上講,這對於一個街區,但不能將區塊與循環組合。要解決此問題,您可以將實際任務移至您包含的另一個 .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 }}"

set_shell.yml

---
- 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

這將為清單中的每個使用者順序執行這兩個任務。

相關內容