使用ansible添加多个SSH密钥

Ada*_*tan 7 ssh ssh-keys batch-processing ansible ansible-playbook

我编写了一个ansible脚本来从远程服务器中删除SSH密钥:

---
- name: "Add keys to the authorized_keys of the user ubuntu"
  user: ubuntu
  hosts: www
  tasks:
  - name: "Remove key #1"
    authorized_key: user=ubuntu key="{{ item }}" state=absent
    with_file:
     - id_rsa_number_one.pub
  - name: "Remove key #2"
    authorized_key: user=ubuntu key="{{ item }}" state=absent
    with_file:
     - id_rsa_number_two.pub
...
Run Code Online (Sandbox Code Playgroud)

将每个文件添加为不同的任务是荒谬的,所以我尝试使用with_fileglob:

  - name: "Remove all keys at once"
    authorized_key: user=ubuntu key="{{ item }}" state=absent
    with_fileglob:
      - /Users/adamatan/ansible/id_rsa*.pub
Run Code Online (Sandbox Code Playgroud)

但这会失败,如下所示:

失败:[www.example.com] =>(项目= /用户/ adamatan/ansible/id_rsa_one.pub)=> { "失败":真, "项目": "/Users/adamatan/ansible/id_rsa_one.pub" } msg:指定了无效密钥:/Users/adamatan/ansible/id_rsa_one.pub

使用唯一任务成功删除了相同的密钥文件,但当它是a的一部分时失败fileglob.

如何使用ansible批量添加或删除SSH密钥?

Ram*_*nte 12

我相信你只是使用文件名with_fileglob,但with_file检索文件的内容.authorized_key模块需要实际密钥.

所以你仍然应该使用循环with_fileglob,但不是将文件名发送到"key ="参数,你应该使用文件查找插件).

- name: "Remove all keys at once"
    authorized_key: user=ubuntu key="{{ lookup('file', item) }}" state=absent
    with_fileglob:
      - /Users/adamatan/ansible/id_rsa*.pub
Run Code Online (Sandbox Code Playgroud)

  • 因此,此修改适用于批量更新/删除条目.这是我的问题 - 我的服务器上的密钥来自不再在这里的人.如何使用我的主动键主列表清除和覆盖authorized_keys文件?当我运行这个脚本时,它删除(如果没有)我的活动键或添加(如果存在),但它永远不会删除不在我的*.pub文件中的键. (2认同)