使用ansible将用户的公钥添加到一个用户的authorized_keys文件中

Bel*_*dez 3 configuration configuration-management ansible

试图将两个人的 Github 公钥添加到用户的授权用户文件中。我能够成功检索 SSH 密钥:

---
- hosts: 127.0.0.1
  connection: local
  vars:
    my_users:
      belminf: "belminf"
      bob: "tmessins"
  tasks:
    - name: Retrieving all keys from GitHub
      shell: /usr/bin/curl https://github.com/{{ item.value }}.keys 2> /dev/null
      register: ssh_keys
      with_dict: my_users

    - debug: var=ssh_keys
Run Code Online (Sandbox Code Playgroud)

但是,我不确定如何遍历ssh_keys结果并使用authorized_keys任务来添加检索到的键。

我荒谬的尝试:

   - name: Adding keys to authorized_keys
      authorized_key: user=belminf key="{{ item }}" path=/home/belminf/test_auth state=present
      with_items: ssh_keys.results
Run Code Online (Sandbox Code Playgroud)

结果在invalid key specified. 可以理解,但我没有想法。任何人?

Jef*_*man 7

从 Ansible 1.9 开始, for 的值key可以是一个 url,从而无需通过shell模块来卷曲 url 。

例子:

- name: Add my SSH key
  authorized_key: user=jeffwidman key=https://github.com/jeffwidman.keys
Run Code Online (Sandbox Code Playgroud)


mas*_*oeh 6

好的,我对你的剧本做了一些调整,这是修订版

---
- hosts: 127.0.0.1
  connection: local
  vars:
    my_users:
      belminf: "belminf"
      bob: "tmessins"
  tasks:
    - name: Retrieving all keys from GitHub
      shell: /usr/bin/curl https://github.com/{{ item.value }}.keys 2> /dev/null
      register: ssh_keys
      with_dict: my_users

   - name: Adding keys to authorized_keys
      authorized_key: user=belminf key="{{ item.stdout }}" path=/home/belminf/test_auth state=present
      with_items: ssh_keys.results
      ignore_errors: yes
Run Code Online (Sandbox Code Playgroud)

一些变化说明:

  • authorized_key模块上,密钥已更改为item.stdout. stdout 是您需要的公钥。
  • authorized_key模块上,我定义ignore_errors: yes在您的 curl 任务无法获取时恢复剧本执行,无论是互联网问题还是 404 未找到(如 tmessins 的密钥)。当然,您可以通过控制定义失败的内容来调整它,以便在发生其他错误时仍然失败。