Creating Self Signed certificates in Ansible

In my day job, I sometimes need to use a self-signed certificate when building a box. As I love using Ansible, I wanted to make the self-signed certificate piece something that was part of my Ansible workflow.

Here follows a bit of basic code that you could use to work through how the process of creating a self-signed certificate would work. I would strongly recommend using something more production-ready (e.g. LetsEncrypt) when you’re looking to move from “development” to “production” :)

---
- hosts: localhost
vars:
- dnsname: your.dns.name
- tmppath: "./tmp/"
- crtpath: "{{ tmppath }}{{ dnsname }}.crt"
- pempath: "{{ tmppath }}{{ dnsname }}.pem"
- csrpath: "{{ tmppath }}{{ dnsname }}.csr"
- pfxpath: "{{ tmppath }}{{ dnsname }}.pfx"
- private_key_password: "password"
tasks:
- file:
path: "{{ tmppath }}"
state: absent
- file:
path: "{{ tmppath }}"
state: directory
- name: "Generate the private key file to sign the CSR"
openssl_privatekey:
path: "{{ pempath }}"
passphrase: "{{ private_key_password }}"
cipher: aes256
- name: "Generate the CSR file signed with the private key"
openssl_csr:
path: "{{ csrpath }}"
privatekey_path: "{{ pempath }}"
privatekey_passphrase: "{{ private_key_password }}"
common_name: "{{ dnsname }}"
- name: "Sign the CSR file as a CA to turn it into a certificate"
openssl_certificate:
path: "{{ crtpath }}"
privatekey_path: "{{ pempath }}"
privatekey_passphrase: "{{ private_key_password }}"
csr_path: "{{ csrpath }}"
provider: selfsigned
- name: "Convert the signed certificate into a PKCS12 file with the attached private key"
openssl_pkcs12:
action: export
path: "{{ pfxpath }}"
name: "{{ dnsname }}"
privatekey_path: "{{ pempath }}"
privatekey_passphrase: "{{ private_key_password }}"
passphrase: password
certificate_path: "{{ crtpath }}"
state: present

JonTheNiceGuy

He/Him. Husband and father. Linux advocating geek. Co-Host on the AdminAdmin Podcast, occasional conference speaker.

One thought to “Creating Self Signed certificates in Ansible”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.