使用Ansible添加多个SSH密钥 [英] Add multiple SSH keys using ansible

查看:189
本文介绍了使用Ansible添加多个SSH密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have written an ansible script to remove SSH keys from remote servers:

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

Adding each file as a different task is preposterous, so I have tried using 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)=> {失败":是的, "item":"/Users/adamatan/ansible/id_rsa_one.pub"} msg:无效的密钥 指定:/Users/adamatan/ansible/id_rsa_one.pub

failed: [www.example.com] => (item=/Users/adamatan/ansible/id_rsa_one.pub) => {"failed": true, "item": "/Users/adamatan/ansible/id_rsa_one.pub"} msg: invalid key specified: /Users/adamatan/ansible/id_rsa_one.pub

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

The same key file is successfully removed using a unique task, but fails when it's a part of a fileglob.

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

推荐答案

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

I believe you are only getting the filenames using with_fileglob, but with_file retrieves the contents of the file. And the authorized_key module requires the actual key.

因此,您仍应使用with_fileglob进行循环,而不是将文件名发送到"key ="参数,而应使用

So you should still loop by using with_fileglob, but instead of sending the filename to the "key=" parameter, you should use the 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

这篇关于使用Ansible添加多个SSH密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆