Ansible blockinfile重新打印

时间:2018-02-13 08:19:13

标签: ansible yaml

我正在使用Ansible的blockinfile功能将用户的公钥插入authorized_keys文件。密钥存储为group_vars中的变量。

插入工作正常,但有没有办法让blockinfile每次从头开始打印块?我的意思是,如果我从变量中删除一个键,并运行playbook,它仍然存在于授权文件中,因为blockinfile只打印一次。

我可以每次都让它再次打印整个变量吗?

剧本:

- name: Add root authorized keys
  blockinfile:
    state: present
    path: /root/.ssh/authorized_keys
    block: |
      {{ item.key }} {{ item.label }}
    marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.label }}"
    backup: yes
  with_items: "{{ root_keys }}"

这就是变量的样子:

root_keys:
- { label: somelabel, key: somekey }
- { label: somelabel2, key: somekey2 }

所以我想要实现的是,当我从somekey2变量中删除root_keys时,它将从authorized_keys文件中消失。

可以这样做吗?

1 个答案:

答案 0 :(得分:1)

您应该使用原生的Ansible authorized_key进行这些操作。

至于问题本身,如果您打算以下列方式重新组织root_keys

root_keys:
- { label: somelabel, key: somekey }
- { label: somelabel2 }

您可以将任务重新定义为:

- name: Add root authorized keys
  blockinfile:
    state: "{{ (item.key is defined ) | ternary('present', 'absent') }}"
    path: /root/.ssh/authorized_keys
    block: |
      {{ item.key | default(omit) }} {{ item.label }}
    marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.label }}"
    backup: yes
  with_items: "{{ root_keys }}"

如果要删除整个元素{ label: somelabel2, key: somekey2 },则应将所有可能的标签值存储在单独的列表中,并迭代该列表,检查元素是否存在于union or difference中all-attributes-list和root_keys|map(attribute='label')以确定是否应包含值;

一个不好的做法 - 变体是解析文件以通过解析搜索ANSIBLE MANAGED BLOCK的目标文件来创建此列表。但另一方面,这是您可能希望使用blockinfile而不是authorized_key模块的唯一原因。