我的 ansible_host 上有 ssh 密钥对,我想将其复制到目标主机上的多个用户的授权密钥。
我正在尝试 with-item 构造,但它抱怨 .pub key 不是无效的密钥,这就是我正在尝试的。
- authorized_key:
user: "{{ item.user }}"
key: "{{ item.key }}"
with_items:
- { user: "user1", key: "~/.ssh/id_rsa.pub" }
- { user: "user2", key: "~/.ssh/id_rsa.pub" }
错误:"msg": "invalid key specified: ~/.ssh/id_rsa.pub"}
答案1
这是因为您要将密钥作为字符串插入到密钥字段中。
您应该使用文件查找插件。
在你的情况下,它应该看起来像这样(未经测试,不完全确定括号):
- authorized_key:
user: "{{ item.user }}"
key: "{{ item.key }}"
with_items:
- { user: "user1", key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}" }
- { user: "user2", key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}" }
答案2
如果您只需将密钥复制给多个用户,您可以这样做:
- authorized_key:
user: "{{ item.user }}"
key: "{{ lookup('file', lookup('env','HOME') + '/.ssh/id_rsa.pub') }}"
with_items:
- { user: "user1" }
- { user: "user2" }