ansible 剧本 public 键问题

ansible playbook public keys issue

我有这个基本的剧本,它将 public_keys 文件夹中的所有 public 键附加到 .ssh/authorized_keys:

中的用户文件夹
- hosts: default

vars:
  user: user1

tasks:
- name: Set up authorized_keys for the user
  authorized_key: user={{ user }} key="{{ item }}"
  with_fileglob:
  - public_keys/*.pub

当我 运行 它在 ansible 上时,它给了我这个错误,我几乎被它困住了:

TASK [Set up authorized_keys for the user] ************************
failed: [default] => (item=/Users/trax/Git/ansible-keys/public_keys/test.pub) => {"failed": true, "item": "/Users/trax/Git/ansible-keys/public_keys/test.pub", "msg": "invalid key specified: /Users/trax/Git/ansible-keys/public_keys/test.pub"}

public 密钥文件是完全有效的,因为我目前正在使用它并且它运行良好。它里面没有评论,我实际上会把它贴在这里让你看到它:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC4e+RLnQAqo3azuFzbynD9n6L7Qc2NjEwNLQRqKOd17532rHAhGOxz9ZV7ca5J6y9Z8QyV2EP9oXXpXd7I9oG1ybiU2cOmMQ7mIMFnMgy90dgVmF4X4Rj3fPch271TIQhvBH36L1eagk98Tlj32zepHNmC7ECFiAUihxXsuGAcFK4l9Y3s0HZe913E1ewUxXjUZAaqmzEQwW621hWDDTU1zUCnPPqEe6DFy6PUP8YL8mLbbKuSL2W6bD7rzm1axZANvoYeD5egvzwSMeZ8f+XF3MbuyhiJhGEFjwDfDkibP4bwQqZm5IdI1c0Ot2X67OHFsHx04gbs6ZzBkD39Z6Jr trax@M.local

有什么建议吗?非常感谢...

key 参数的参数需要是 key(不是文件路径,而是实际的 contents) 或 url。来自文档:

key The SSH public key(s), as a string or (since 1.9) url (https://github.com/username.keys)

因此您可以添加一个任务,将密钥读入已注册的变量,然后遍历该变量以安装密钥:

- hosts: all
  tasks:
    - name: read keys

      # This needs to run on localhost, because that's where
      # the keys are stored.
      delegate_to: localhost

      command: cat {{item}}

      # Register the results of this task in a variable called
      # "keys"
      register: keys

      with_fileglob:
        - "public-keys/*.pub"

    - name: show what was stored in the keys variable
      debug:
        var: keys

    - authorized_key:
        user: fedora
        key: "{{item.stdout}}"
      with_items: "{{keys.results}}"

请参阅 Ansible 文档,了解如何使用 register 循环 了解详情。

假设密钥文件在控制机本地,使用file lookup获取密钥内容很容易,例如:

- hosts: default
  tasks:
  - authorized_key:
      user: '{{ user }}'
      key: '{{ lookup('file', item) }}'
    with_fileglob: public_keys/*.pub

由于其中大部分都是旧版本,我有一个适合我的更新版本。

      - name: Set authorized key taken from file
        authorized_key:
          user: yourtargetusername
          state: present
          key: "{{ lookup('file', 'yourtargetkey.pub') }}"