簡體   English   中英

Ansible - 禁用 ssh 密碼驗證

[英]Ansible - disable ssh password authentication

我正在嘗試制作正確處理sshd_config的 ansible 任務。 我從其他問題中找到了類似的正則表達式,但它們什么也沒做。

name: Disable SSH password authentication
      become: true
      lineinfile:
        dest: /etc/ssh/sshd_config
        regexp: '^#?\s*PasswordAuthentication\s'
        line: 'PasswordAuthentication no'
        state: present

問題是它應該處理重復的車道和評論。 例如:

  • 可能有:
PasswordAuthentication no
PasswordAuthentication yes

或者

PasswordAuthentication no
PasswordAuthentication no

或者

PasswordAuthentication yes
PasswordAuthentication yes

或者

PasswordAuthentication no
#PasswordAuthentication no

或者

PasswordAuthentication no
# PasswordAuthentication no

或者

# PasswordAuthentication no
# PasswordAuthentication no

等等這么多的組合。 但我只想有一個未注釋的行PasswordAuthentication no

這可能嗎?

問: 處理重復的行以及注釋......有一個未注釋的行PasswordAuthentication no

A:給定文件列表

    my_files:
      - sshd_config.0
      - sshd_config.1
      - sshd_config.2
      - sshd_config.3
      - sshd_config.4
      - sshd_config.5

和內容

shell> for f in files-17/*; do printf "\n%s\n" $f; cat $f; done

files-17/sshd_config.0
PasswordAuthentication no
PasswordAuthentication yes

files-17/sshd_config.1
PasswordAuthentication no
PasswordAuthentication no

files-17/sshd_config.2
PasswordAuthentication yes
PasswordAuthentication yes

files-17/sshd_config.3
PasswordAuthentication no
#PasswordAuthentication no

files-17/sshd_config.4
PasswordAuthentication no
# PasswordAuthentication no

files-17/sshd_config.5
# PasswordAuthentication no
# PasswordAuthentication no

下面的任務刪除了除第一行之外的所有內容,其中包括PasswordAuthentication

    - replace:
        path: 'files-17/{{ item }}'
        after: 'PasswordAuthentication'
        regexp: '^(.*)PasswordAuthentication(.*)$'
        replace: ''
      loop: "{{ my_files }}"

shell> for f in files-17/*; do printf "\n%s\n" $f; cat $f; done

files-17/sshd_config.0
PasswordAuthentication no


files-17/sshd_config.1
PasswordAuthentication no


files-17/sshd_config.2
PasswordAuthentication yes


files-17/sshd_config.3
PasswordAuthentication no


files-17/sshd_config.4
PasswordAuthentication no


files-17/sshd_config.5
# PasswordAuthentication no

下一個任務將行替換為PasswordAuthentication no

    - lineinfile:
        path: 'files-17/{{ item }}'
        regexp: '^(.*)PasswordAuthentication(.*)$'
        line: 'PasswordAuthentication no'
      loop: "{{ my_files }}"

shell> for f in files-17/*; do printf "\n%s\n" $f; cat $f; done

files-17/sshd_config.0
PasswordAuthentication no


files-17/sshd_config.1
PasswordAuthentication no


files-17/sshd_config.2
PasswordAuthentication no


files-17/sshd_config.3
PasswordAuthentication no


files-17/sshd_config.4
PasswordAuthentication no


files-17/sshd_config.5
PasswordAuthentication no

任務的順序是冪等的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM