Reputation: 1
I am using Ansible's blockinfile
feature to insert user's public keys into authorized_keys
file. Keys are stored as variable in group_vars
.
Inserting works fine, but is there a way to ask blockinfile
to print blocks from the beginning every time? What I mean is, if I remove one key from variable, and run playbook it still exists in authorized file, because blockinfile
is only printing once.
Can I make it print whole variable again everytime?
Playbook:
- 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 }}"
This is how variable looks like:
root_keys:
- { label: somelabel, key: somekey }
- { label: somelabel2, key: somekey2 }
So what I am trying to achieve is that when I remove somekey2
from root_keys
variable, it will disappear from authorized_keys
file.
Can this be done?
Upvotes: 0
Views: 447
Reputation: 68469
You should use a native Ansible authorized_key
for these operations.
As for the question itself if you plan to reorganise root_keys
in the following way:
root_keys:
- { label: somelabel, key: somekey }
- { label: somelabel2 }
You can redefine the task to:
- 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 }}"
If you want to remove the whole element { label: somelabel2, key: somekey2 }
, then you should store all possible label-values in a separate list and iterate over that list checking if an element is present in a union
or difference
of that all-attributes-list and root_keys|map(attribute='label')
to determine if a value should be included or not;
A bad practice-variation would be to parse the file to create this list by parsing the destination file in search for ANSIBLE MANAGED BLOCK
. But that, on the other hand would be the only reason you might want to use blockinfile
instead of authorized_key
module.
Upvotes: 1