--- - name: Create read-only Proxmox token for monitoring hosts: mini-pc gather_facts: false vars: monitoring_pve_user: monitoring@pve monitoring_pve_token_id: prometheus monitoring_pve_env_file: "{{ playbook_dir }}/../.env" monitoring_pve_rotate_existing_token: false tasks: - name: Read existing Proxmox users ansible.builtin.command: pveum user list --output-format json register: monitoring_pve_users_raw changed_when: false - name: Create monitoring Proxmox user ansible.builtin.command: >- pveum user add {{ monitoring_pve_user }} --comment 'Read-only Prometheus monitoring user' when: monitoring_pve_user not in (monitoring_pve_users_raw.stdout | from_json | map(attribute='userid') | list) - name: Grant PVEAuditor role to monitoring user ansible.builtin.command: >- pveum acl modify / -user {{ monitoring_pve_user }} -role PVEAuditor changed_when: false - name: Read monitoring user tokens ansible.builtin.command: >- pveum user token list {{ monitoring_pve_user }} --output-format json register: monitoring_pve_tokens_raw changed_when: false - name: Refuse to overwrite an existing monitoring token ansible.builtin.assert: that: - monitoring_pve_token_id not in (monitoring_pve_tokens_raw.stdout | from_json | map(attribute='tokenid') | list) fail_msg: Existing monitoring token secret cannot be recovered safely. Rotate it explicitly before rerunning this playbook. when: not monitoring_pve_rotate_existing_token | bool - name: Rotate existing monitoring token explicitly ansible.builtin.command: >- pveum user token remove {{ monitoring_pve_user }} {{ monitoring_pve_token_id }} when: - monitoring_pve_rotate_existing_token | bool - monitoring_pve_token_id in (monitoring_pve_tokens_raw.stdout | from_json | map(attribute='tokenid') | list) - name: Create separated monitoring token ansible.builtin.command: >- pveum user token add {{ monitoring_pve_user }} {{ monitoring_pve_token_id }} --privsep 1 --comment 'Prometheus PVE exporter' --output-format json register: monitoring_pve_token_created no_log: true - name: Grant PVEAuditor role to separated monitoring token ansible.builtin.command: >- pveum acl modify / -token {{ monitoring_pve_user }}!{{ monitoring_pve_token_id }} -role PVEAuditor changed_when: false - name: Store monitoring token variables locally ansible.builtin.lineinfile: path: "{{ monitoring_pve_env_file }}" regexp: "^export {{ item.name }}=" line: "export {{ item.name }}='{{ item.value }}'" create: false loop: - name: MONITORING_PVE_API_USER value: "{{ monitoring_pve_user }}" - name: MONITORING_PVE_API_TOKEN_ID value: "{{ monitoring_pve_token_id }}" - name: MONITORING_PVE_API_TOKEN_SECRET value: "{{ (monitoring_pve_token_created.stdout | from_json).value }}" delegate_to: localhost vars: ansible_connection: local ansible_become: false no_log: true