将多个公钥与Ansible结合使用

时间:2019-01-07 16:57:22

标签: ansible

如何结合使用多个ssh公钥与Ansible的authorized_key模块一起使用?

我有包含用户和密钥的变量文件:

ssh_users:
  - name: peter
    keys:
      - 'ssh-rsa AAAAB3NzaC1yc2EAAA peter@key1'
      - 'ssh-rsa AAAABsgsdfgyc2EAAA peter@key2'
    root: yes

  - name: paul
    keys:
      - 'ssh-rsa AAAAB3Nzaafac2EAAA paul@key1'
    root: no

我想遍历此列表,挑选出具有“ root:yes”的用户(及其密钥),并将其组合以更新root用户的authorized_keys文件。

这不起作用:

- name: lookup keys
  set_fact:
    keylist: "{{ item.keys }}"
  with_items: "{{ ssh_users }}"
  when: item.root == true
  register: result

 - name: make a list
   set_fact:
     splitlist: "{{ result.results | 
  selectattr('ansible_facts','defined') | map(attribute='ansible_facts.keylist') | list | join('\n') }}"

 - name: update SSH authorized_keys
   authorized_key:
     user: root
     key: "{{ splitlist }}"
     state: present
     exclusive: yes

2 个答案:

答案 0 :(得分:0)

您可以使用Jinja \nselectattr过滤器来获得所需的内容,如下所示:

map

--- - hosts: localhost gather_facts: false vars: # Here's our data: two users with 'root' access, # one without. We expect to see three public keys in # the resulting authorized_keys file. # # Note that I've renamed the "keys" key to "pubkeys", because # otherwise it conflicts with the "keys" method of dictionary # objects (leading to errors when you try to access something # like item.keys). ssh_users: - name: alice pubkeys: - 'ssh-rsa alice-key-1 alice@key1' root: true - name: peter pubkeys: - 'ssh-rsa peter-key-1 peter@key1' - 'ssh-rsa peter-key-2 peter@key2' root: true - name: paul pubkeys: - 'ssh-rsa paul-key-1 paul@key1' root: false tasks: - become: true authorized_key: user: root key: "{{ '\n'.join(ssh_users|selectattr('root')|map(attribute='pubkeys')|flatten) }}" state: present exclusive: true 任务中,我们首先使用authorized_key过滤器提取具有selectattr访问权限的用户。我们将其传递给root过滤器以仅提取map属性,这将给我们两个列表(一个带有一个键,另一个带有两个键)。最后,我们将其传递给pubkeys过滤器以创建单个列表,然后将结果键与换行符连接以匹配flatten模块期望的输入格式。生成的authorized_key文件如下所示:

.ssh/authorized_keys

答案 1 :(得分:0)

这是您要查找的代码吗?

- name: update SSH authorized_keys
  authorized_key:
    user: root
    key: "{{ item.1 }}"
  loop: "{{ ssh_users | subelements('keys', skip_missing=True) }}"
  when: item.0.root

您不需要参数 exclusive state 。我认为默认值 exclusive:否 state:存在还可以。

可以删除 root:False 的键

- name: remove SSH authorized_keys
  authorized_key:
    state: absent
    user: root
    key: "{{ item.1 }}"
  loop: "{{ ssh_users | subelements('keys', skip_missing=True) }}"
  when: not item.0.root

要在一个任务中添加和删除键,ternary过滤器可能会使用

- name: Preen SSH authorized_keys
  authorized_key:
    state: "{{ item.0.root | ternary('present','absent') }}"
    user: root
    key: "{{ item.1 }}"
  loop: "{{ ssh_users | subelements('keys', skip_missing=True) }}"