2016-08-10 43 views
4

我在使用Ansible时相当新,并且一直在阅读here和谷歌,但还没有找到答案。是否可以将Ansible authorized_key与多个键一起使用?

我的方案是我有一个服务器上的用户,但需要放置在它的authorized_keys文件中的2-3个不同的酒吧钥匙。

我可以成功地删除所有密钥,或与此脚本中添加的所有键:

--- 
    - hosts: all 

tasks: 
    - name: update SSH keys 
    authorized_key: 
    user: <user> 
    key: "{{ lookup('file', item) }}" 
    state: present 
    #exclusive: yes 
    with_fileglob: 
     - ../files/pub_keys/*.pub 

随着present标志读取,并增加了所有的按键。通过absent标志,它将删除列出的所有密钥。

问题是我有一个旧密钥,它只在服务器上,我想删除/覆盖它,并为将来的部署覆盖可能在服务器上而不在我的手册中的任何未经授权的密钥。

使用exclusive标志,它只接收最后一个键并添加它。如果它会循环添加所有的键,这将会很棒。如果Ansible有办法做到这一点,我还没有找到它。

有什么办法可以循环发布pub文件并同时使用exclusive选项吗?

回答

7

有没有什么办法可以循环访问pub文件并同时使用独占选项?

号有一个关于环路说明,并独家在docs

独家:无论从authorized_keys文件中删除所有其他非指定的键。通过用换行符分隔单个键字符串值,可以指定多个键。 这个选项不是循环感知的,所以如果你使用with_,它将在循环迭代中是独占的,如果你想在文件中使用多个键,你需要把它们全部传递到上面提到的单个批处理中。

因此,您需要加入所有密钥并一次发送所有密钥。
事情是这样的:

- name: update SSH keys 
    authorized_key: 
    user: <user> 
    key: "{{ lookup('pipe','cat ../files/pub_keys/*.pub') }}" 
    state: present 
    exclusive: yes 

检查这个代码运行在生产之前!

+0

呵呵,你是救命恩人!很棒!我只是发现了“查找”的东西,但试图理解它。非常感谢你! – Valien

1

如果你保持你的用户变量中,你可以使用此:

--- 

- hosts: all 
    vars_files: 
    - roles/users/vars/main.yml 
    tasks: 
    - name: Allow other users to login to the account 
     authorized_key: 
     user: user_name 
     exclusive: yes 
     key: "{{ developers|map(attribute='publish_ssh_key')|join('\n') }}" 

roles/users/vars/main.yml看起来是这样的:

--- 

developers: 
    - name: user1 
    publish_ssh_key: ssh-rsa AAAA... 
    - name: user2 
    publish_ssh_key: ssh-rsa AAAA... 
+0

这只会添加最后一个键,但根据文档,它应该工作“多个键可以在一个键字符串值中用新行分隔来指定”http://docs.ansible.com/ansible/authorized_key_module.html你知道它为什么坏了吗? – goetzc

+0

@goetzc我不知道:-( – czerasz

+0

嘿,这是我的测试密钥,其中相同的,只是一个不同的评论,然后Ansible只增加了最后一个:) – goetzc

0

如果你想避免pipe查找(例如,因为该路径不是相对于角色的),还可以使用filefileglob查找的组合:

- name: update SSH keys 
    authorized_key: 
    user: <user> 
    key: "{% for key in lookup('fileglob', 'pub_keys/*.pub').split(',') %}{{ lookup('file', key) ~ '\n'}}{% endfor %}" 
    state: present 
    exclusive: yes 
相关问题