name: Replace the old API keys with the new ones
ansible.builtin.blockinfile:
path: "{{ jellyfin_tmp_vault }}"
marker: "# Compiled by Ansible"
insertafter: '(?m)vm_data:[\s\S]?test-lxc:[\s\S]?jellyfin:[\S\s]api_keys:\n(?:#.?\n)?' # (?:(?:\s*[ \t]+.|\s)\n)*
block: |
{% for user, key in relevant_keys.items() %}
{{ ' ' * 8 }}{{ user }}: {{ key }}
{% endfor %}
delegate_to: localhost
The strange result occurs because the blockinfile module is inserting the new API keys after the api_keys: line without removing the existing keys. Here's the breakdown:
Root Cause
The insertafter regex matches the api_keys: line but does not target the existing keys for replacement.
blockinfileinserts the block after the matched line, not replaces it. This leads to duplicate entries (existing keys + new keys) in the output.
Matches the api_keys: line but does not capture the existing keys (e.g., jellyadmin: "").
As a result, the new block is inserted after the api_keys: line, but the original keys remain untouched.
Desired Behavior vs. Actual Behavior
Desired: Replace the existing jellyadmin and jellyseer keys under api_keys:.
Actual: Insert the new keys after the api_keys: line, leaving the old keys intact.
Solution
To replace the existing keys, you need to:
Match the entire block (including the existing keys) for replacement.
Use blockinfile with a marker to wrap the new content, ensuring the old content is overwritten.
Corrected Task
yaml
- name: Replace the old API keys with the new ones
ansible.builtin.blockinfile:
path: "{{ jellyfin_tmp_vault }}"
marker: "# Compiled by Ansible"
insertafter: '(?m)^ api_keys:\n'
block: |
{% for user, key in relevant_keys.items() %}
{{ ' ' * 8 }}{{ user }}: {{ key }}
{% endfor %}
delegate_to: localhost
Key Fixes
insertafter: '(?m)^ api_keys:\n':
Matches the api_keys: line exactly (with indentation).
Ensures the block is inserted after the api_keys: line, replacing the existing keys.
Marker Usage:
The # Compiled by Ansible marker ensures the new block is properly wrapped and replaces the old content.
Expected Result
After the fix, the api_keys section will only contain the new keys: