2 min read

Inject Ansible Vault variable in external file

Inject Ansible Vault variable in external file

You want to inject an Ansible vault variable into an external file (configuration file or other)? Here's how to do it.

This work with any type of variable but in my case the need was to copy an encrypted password in a configuration file.

In this example we will inject the database password in the ghost configuration file config.production.json (the variable {{ mysql_user_password }} is contained in a vault.yml file).

For this we'll use the lineinfile module.


We have an Ansible playbook that'll deploy a Ghost blog. We will focus on variable injection in the configuration file.

We have one folder that contains the playbook and all of the basics files (example ~/ghost-ansible with ansible files, nginx configuration, ghost configuration) and a folder with a copy of the configuration file (example : ~/ghost).

Why we create a copy of the configuration file : the Ansible directory will be clean of any password and you can continue to push this playbook into your versionning tool without any problem.

Create your vault

Create the vault and set the password :

$ ansible-vault create vault.yml
Vault password:

Add your variables :

mysql_root_password: "secret_root"
mysql_user_password: "secret_user"


The file config.production.json :

  "database": {
    "client": "mysql",
    "connection": {
        "host": "db",
        "user": "ghost-user",
        "password": ""
        "database": "ghost",
        "charset": "utf8"

Creation of the folder and copy the file with Ansible :

  - name: Creates stack directory
      path: ~/ghost
      state: directory

  - name: Copying configuration files
      src: ./configuration
      dest: ~/ghost/

Inject the password into the configuration file :

  - name: Set Ghost secret in config.production.json
      path: ~/ghost/configuration/config.production.json
      regexp: '^(.*)password(.*)$'
      line: '        "password": "{{ mysql_user_password }}"'

And the result :

$ cat  ~/ghost/configuration/config.production.json
$ grep password ~/ghost/configuration/config.production.json
        "password": "secret_user"


$ ansible-playbook pre-config.yml --ask-vault-pass
Vault password:



Feel free to correct me if you see any typo or if something seems wrong to you.
You can send me an email or comment below.

Picture : Silas Köhler