Add SSL CA Certificate to Ubuntu and Use It with Python Requests

Python
2018-06-21 02:34 (7 years ago)
Trust Chain Alchemy
Play a song themed on this article

1. If the certificate is in DER format, convert it to PEM

openssl x509 -in torico.der -inform DER -out torico-ca.crt -outform PEM

2. Copy the certificate to /usr/local/share/ca-certificates/

3. Execute sudo update-ca-certificates

At this point, certificates will be used when using tools like curl, and certificate errors will no longer occur.

However, certificate errors will still occur with Python Requests.

4. An environment variable is required when using Python Requests

REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt

It is recommended to add the environment variable to /etc/environment

Incidentally, you can also specify the CA path in the verify= argument of requests

import requests
requests.get('https://xxx', verify='/usr/local/share/ca-certificates/torico-ca.crt')

Ansible

Here's how it looks when written in Ansible

- hosts: servers
gather_facts: no
become: yes
tasks:
- copy:
src: torico-ca.crt
dest: "/usr/local/share/ca-certificates/torico-ca.crt"
mode: 0664

- shell: update-ca-certificates

- lineinfile:
dest: "/etc/environment"
insertafter: EOF
line: "REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt"

Reference
ssl - Python Requests - How to use system ca-certificates (debian/ubuntu)? - Stack Overflow

Please rate this article
Currently unrated
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.

Categories

Archive