使用 ansible 添加多个 SSH 密钥 [英] Add multiple SSH keys using ansible
问题描述
我编写了一个 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) => {"failed": true,"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屋!