Код: Выделить всё
# sysadmin keys
ssh-rsa AAAAB1...key_here...
ssh-rsa AAAAB2...key_here...
#
# service keys
ssh-rsa AAAAB9...key_here...
Ключ SSH вставляется после комментария # сервисных ключей, а не раньше.
Я получил ошибки, связанные с использованием шаблонов Jinja2 в условии if.
Вот код, который я пробовал до сих пор:
Код: Выделить всё
---
- name: Add SSH public key to user's authorized_keys before the specified comment
hosts: all
become: yes
vars:
ssh_public_key: "ssh-rsa AAAAB3...key_here... comment"
ssh_directory: "{{ ansible_env.HOME }}/.ssh"
authorized_keys_path: "{{ ssh_directory }}/authorized_keys"
insert_before_comment: "# service keys"
tasks:
- name: Ensure the .ssh directory exists for the user
file:
path: "{{ ssh_directory }}"
state: directory
mode: '0700'
- name: Add SSH public key if not already present
authorized_key:
user: "{{ ansible_env.USER }}"
state: present
key: "{{ ssh_public_key }}"
path: "{{ authorized_keys_path }}"
manage_dir: yes
- name: Read the authorized_keys file
slurp:
src: "{{ authorized_keys_path }}"
register: authorized_keys_content
- name: Set fact to check if the comment exists
set_fact:
insert_before_comment_exists: "{{ insert_before_comment in (authorized_keys_content.content | b64decode()) }}"
- name: Modify authorized_keys file by inserting SSH key before the comment
blockinfile:
path: "{{ authorized_keys_path }}"
marker: "# {{ insert_before_comment }}"
content: |
{{ ssh_public_key }}
when: insert_before_comment_exists
- Ключ вставляется после комментария # служебных ключей. вместо перед ним.
- Условие if с шаблоном Jinja2 ({{insert_before_comment }}) выдает предупреждение: условные операторы не должны включать разделители шаблонов jinja2.
Что я пробовал: - Я использовал lineinfile иblockinfile, но ни один из них не дал результата. желаемый результат.
- Я попытался проверить, существует ли комментарий, и условно вставил ключ.
Подробнее здесь: https://stackoverflow.com/questions/793 ... sing-ansib
Мобильная версия