Use Ansible to deploy TrueNAS SSL


The goal is to deploy Lets Encrypt Certificate for TrueNAS useing the API and ansible.

All you need is an API-Key and the content of the SSL Key and fullpem, you can also use username & password for the API calls, but this is not covered here.

The process is relatively straightforward first you need the POST the new key and certifcate, then fetch all available certs from the API and set the ID of the certificate which you want to use. The ID is simply always the last, because every time you add a new certificate the ID increase.

- name: Get values from Passwordstore
  ansible.builtin.set_fact:
    cert4nas: "{{lookup('community.general.passwordstore', 'automation/lets-encrypt/fullchain' , returnall=true)}}"
    key4nas:  "{{lookup('community.general.passwordstore', 'automation/lets-encrypt/certkey' , returnall=true)}}"
    nas_api_key: "{{lookup('community.general.passwordstore', 'clients/truenas/api-key')}}"
  delegate_to: localhost
  run_once: true

- name: Push SSL cert to TrueNAS
  ansible.builtin.uri:
    url: https://nas.home.example.com/api/v2.0/certificate
    method: POST
    body_format: json
    follow_redirects: all
    headers:
      Authorization: "Bearer {{ nas_api_key }}"
    body:
      create_type: CERTIFICATE_CREATE_IMPORTED
      name: "letsencypt-{{ now(fmt='%Y-%m-%d') }}"
      certificate: "{{ cert4nas }}"
      privatekey: "{{ key4nas }}"
      key_type: EC
    validate_certs: false
  delegate_to: localhost
  run_once: true

- name: Get available certs from TrueNAS API
  ansible.builtin.uri:
    url: https://nas.home.example.com/api/v2.0/certificate
    method: GET
    follow_redirects: all
    headers:
      Authorization: "Bearer {{ nas_api_key }}"
    return_content: true
    validate_certs: false
  register: get_output
  delegate_to: localhost
  run_once: true

- name: Set SSL cert with highest id as current used
  ansible.builtin.uri:
    url: https://nas.home.example.com/api/v2.0/system/general
    method: PUT
    follow_redirects: all
    body_format: json
    headers:
      Authorization: "Bearer {{ nas_api_key }}"
    body:
      ui_certificate: "{{ get_output.json[-1]['id'] }}"
    validate_certs: false
  delegate_to: localhost
  run_once: true

The SSL certificate menu in TrueNAS in well hidden:

System Settings > General > GUI [Settings] > GUI SSL Certificate [Manage Certificates]