【问题标题】:Add multiple SSH keys using ansible使用 ansible 添加多个 SSH 密钥
【发布时间】:2014-11-29 22:51:07
【问题描述】:

我已经编写了一个 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
...

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

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

但这会失败,如下所示:

失败:[www.example.com] => (item=/Users/adamatan/ansible/id_rsa_one.pub) => {"失败": true, "item": "/Users/adamatan/ansible/id_rsa_one.pub"} msg: 无效密钥 指定:/Users/adamatan/ansible/id_rsa_one.pub

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

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

【问题讨论】:

    标签: ssh batch-processing ssh-keys ansible ansible-playbook


    【解决方案1】:

    我相信您只使用with_fileglob 获取文件名,但with_file 检索文件的内容。而authorized_key 模块需要实际的密钥。

    因此,您仍应使用with_fileglob 进行循环,但不应将文件名发送到“key=”参数,而应使用file lookup plugin)。

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

    【讨论】:

    • 所以这个修改非常适合批量更新/删除条目。这是我的问题 - 我在服务器上有来自不再在这里的人的密钥。如何使用我的活动密钥主列表清除和覆盖 authorized_keys 文件?当我运行此脚本时,它会删除(如果不存在)我的活动密钥或添加(如果存在),但它永远不会删除不在我的 *.pub 文件中的密钥。
    • @Valien 用于多个独占密钥,请参阅此 pull request 中的示例。
    • 您还可以为某些主机组中的所有用户创建~/.ssh/ 并复制静态authorized_keys 文件。在这种情况下,您可以完全控制文件内容。
    猜你喜欢
    • 1970-01-01
    • 2014-04-18
    • 2014-05-13
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 2017-06-02
    • 1970-01-01
    相关资源
    最近更新 更多