Introduction
Ansible Vault is simply a characteristic that allows you to encrypt values and information structures wrong Ansible projects. This provides the expertise to unafraid immoderate delicate information that is basal to successfully tally Ansible plays but should not beryllium publically visible, specified arsenic passwords, API keys, aliases backstage keys. Ansible automatically decrypts vault-encrypted contented astatine runtime erstwhile the correct password is provided.
In this guide, you will study really Ansible Vault useful nether the hood, really to encrypt full files and individual variables, really to proviso the vault password to Ansible interactively aliases done a password file, and really to negociate aggregate vault passwords pinch vault IDs. You will besides spot really Ansible Vault compares pinch different approaches to secrets management. You will usage a azygous Ansible power instrumentality and nary distant hosts are required. This guideline was tested connected an Ubuntu server, but the workflow is identical connected immoderate Linux distribution wherever Ansible is installed.
Key takeaways
- Ansible Vault encrypts secrets astatine remainder truthful you tin support delicate and nonsensitive configuration information together successful 1 task without exposing the secrets.
- You tin encrypt an full record pinch ansible-vault encrypt, aliases encrypt a azygous worth inline pinch ansible-vault encrypt_string, which is friendlier for shared repositories.
- The ansible and ansible-playbook commands decrypt vault contented automatically erstwhile fixed the password done --ask-vault-pass, a --vault-password-file, aliases the ANSIBLE_VAULT_PASSWORD_FILE situation variable.
- A vault password record must beryllium kept retired of type power (add it to .gitignore) and locked down pinch chmod 600.
- Vault IDs (the --vault-id label@source syntax) fto you negociate aggregate passwords, specified arsenic abstracted secrets for development, staging, and production.
- In CI/CD pipelines, shop the vault password arsenic a protected pipeline secret, constitute it to a impermanent record astatine runtime, and region that record aft the run.
- Ansible Vault protects information connected disk only; erstwhile decrypted astatine runtime, secrets unrecorded successful representation and tin look successful verbose output aliases logs, truthful grip them carefully.
- If you suffer a vault password, the encrypted information cannot beryllium recovered, which is why storing vault passwords successful a dedicated password aliases secrets head matters.
- For ample teams scaling their automation, an outer secrets head specified arsenic HashiCorp Vault tin complement aliases switch Ansible Vault.
Prerequisites
To travel along, you will request an Ubuntu server pinch a non-root personification pinch sudo privileges. You tin travel our Initial Server Setup pinch Ubuntu guideline to create a personification pinch the due permissions.
On the server, you will request to instal and configure Ansible. You tin travel our tutorial connected installing Ansible connected Ubuntu to instal the due packages. Continue pinch this guideline erstwhile your server is configured pinch the supra requirements.
What is Ansible Vault?
Ansible Vault is simply a system that allows encrypted contented to beryllium incorporated transparently into Ansible workflows. A inferior called ansible-vault secures confidential data, called secrets, by encrypting it connected disk. To merge these secrets pinch regular Ansible data, some the ansible and ansible-playbook commands, utilized for executing advertisement hoc tasks and system playbooks respectively, support decrypting vault-encrypted contented astatine runtime.
Vault is implemented pinch file-level granularity, meaning that individual files are either encrypted aliases unencrypted arsenic a whole. It tin besides encrypt azygous values inline, which you will spot later. Ansible identifies and decrypts immoderate vault-encrypted contented it finds while executing a playbook aliases task, arsenic agelong arsenic it has the correct password.
Encryption algorithm and information model
Ansible Vault encrypts contented pinch AES-256 successful CTR mode and derives the encryption cardinal from your password utilizing PBKDF2 pinch HMAC-SHA256, tally complete 10,000 iterations pinch a 32-byte random salt, past authenticates the ciphertext pinch an HMAC-SHA256 digest. These are strong, industry-standard primitives, truthful successful believe the information of a vault comes down to the spot of the password you take and really cautiously you shop it. A short aliases reused password undermines different coagulated cryptography.
It is arsenic important to understand what Ansible Vault does not protect against. Vault secures information only while it sits connected disk. Once Ansible decrypts a concealed to usage it during a run, that worth exists successful representation arsenic an mean adaptable and tin look successful verbose output (for example, erstwhile you tally pinch -vvv), successful task results, aliases successful logs if you are not careful. Vault besides has nary per-user entree power beyond the shared password: anyone pinch the password tin publication everything that password protects. Treat it arsenic encryption astatine rest, not arsenic a complete secrets-management platform.
Now that you understand what Vault is and really it secures data, you tin commencement utilizing the devices Ansible provides.
Setting the Ansible Vault editor
Before utilizing the ansible-vault command, it is simply a bully thought to specify your preferred matter editor. Several of Vault’s commands unfastened an editor to manipulate the contents of an encrypted file. Ansible sounds the EDITOR situation adaptable to find your preferred editor, and if it is unset, it defaults to vi.
If you do not want to edit pinch the vi editor, group the EDITOR adaptable successful your environment.
Note: If you find yourself wrong a vi convention accidentally, you tin exit by pressing the Esc key, typing :q!, and past pressing Enter. If you are not acquainted pinch vi, immoderate changes you make are apt to beryllium unintentional, truthful this bid exits without saving.
To group the editor for a azygous command, prepend the bid pinch the situation adaptable assignment, for illustration this:
- EDITOR=nano ansible-vault . . .
To make this persistent, unfastened your ~/.bashrc file:
- nano ~/.bashrc
Specify your preferred editor by adding an EDITOR duty to the extremity of the file:
~/.bashrc
export EDITOR=nanoSave and adjacent the record erstwhile you are finished, past root the record again to publication the alteration into the existent session:
- . ~/.bashrc
Display the EDITOR adaptable to cheque that your mounting was applied:
- echo $EDITOR
The bid prints the editor you set:
Output
nanoNow that you person established your preferred editor, you tin research the operations disposable pinch the ansible-vault command.
Managing delicate files pinch ansible-vault
The ansible-vault bid is the main interface for managing encrypted contented wrong Ansible. You usage it to initially encrypt files and past to view, edit, rekey, aliases decrypt the data. The pursuing subsections locomotion done each operation.
Creating caller encrypted files
To create a caller record encrypted pinch Vault, usage the ansible-vault create bid and walk successful the sanction of the record you wish to create. For example, to create an encrypted YAML record called vault.yml to shop delicate variables, type the following:
- ansible-vault create vault.yml
You are prompted to participate and corroborate a password:
Output
New Vault password: Confirm New Vault password:When you person confirmed your password, Ansible instantly opens an editing model wherever you tin participate your desired contents. To trial the encryption, participate immoderate sample text:
vault.yml
Secret informationAnsible encrypts the contents erstwhile you adjacent the file. If you cheque the file, alternatively of the words you typed, you spot an encrypted block:
- cat vault.yml
The record now contains a Vault header followed by the encrypted payload:
Output
$ANSIBLE_VAULT;1.1;AES256 65316332393532313030636134643235316439336133363531303838376235376635373430336333 3963353630373161356638376361646338353763363434360a363138376163666265336433633664 30336233323664306434626363643731626536643833336638356661396364313666366231616261 3764656365313263620a383666383233626665376364323062393462373266663066366536306163 31643731343666353761633563633634326139396230313734333034653238303166The header tells Ansible really to grip the file, and it is followed by the encrypted contents, which show arsenic hexadecimal digits.
Encrypting existing files
If you already person a record that you wish to encrypt pinch Vault, usage the ansible-vault encrypt bid instead. For testing, create an illustration file:
- echo 'unencrypted stuff' > encrypt_me.txt
Now encrypt the existing file:
- ansible-vault encrypt encrypt_me.txt
Again, you are prompted to supply and corroborate a password, aft which a connection confirms the encryption:
Output
New Vault password: Confirm New Vault password: Encryption successfulInstead of opening an editing window, ansible-vault encrypts the contents of the record and writes it backmost to disk, replacing the unencrypted version. If you cheque the file, you spot a akin encrypted pattern:
- cat encrypt_me.txt
The output shows the aforesaid Vault header and encrypted assemblage arsenic a recently created file:
Output
$ANSIBLE_VAULT;1.1;AES256 66633936653834616130346436353865303665396430383430353366616263323161393639393136 3737316539353434666438373035653132383434303338640a396635313062386464306132313834 34313336313338623537333332356231386438666565616537616538653465333431306638643961 3636663633363562320a613661313966376361396336383864656632376134353039663662666437 39393639343966363565636161316339643033393132626639303332373339376664As you tin see, Ansible encrypts existing contented successful overmuch the aforesaid measurement arsenic it encrypts caller files.
Viewing encrypted files
Sometimes you request to reference the contents of a vault-encrypted record without editing it aliases penning it to the filesystem unencrypted. The ansible-vault position bid feeds the contents of a record to modular output, which by default displays them successful the terminal. Pass the vault-encrypted record to the command:
- ansible-vault position vault.yml
You are asked for the file’s password, and aft entering it successfully the contents are displayed:
Output
Vault password: Secret informationThe password punctual is mixed into the output of the record contents, truthful support this successful mind erstwhile utilizing ansible-vault position successful automated processes.
Editing encrypted files
When you request to edit an encrypted file, usage the ansible-vault edit command:
- ansible-vault edit vault.yml
You are prompted for the file’s password, and aft entering it, Ansible opens the record successful an editing model wherever you tin make immoderate basal changes. Upon saving, the caller contents are encrypted again pinch the file’s password and written to disk.
Manually decrypting encrypted files
To decrypt a vault-encrypted file, usage the ansible-vault decrypt command.
Note: Because of the accrued likelihood of accidentally committing delicate information to your task repository, the ansible-vault decrypt bid is champion reserved for erstwhile you want to region encryption from a record permanently. If you only request to position aliases edit a vault-encrypted file, usage ansible-vault position aliases ansible-vault edit instead.
Pass successful the sanction of the encrypted file:
- ansible-vault decrypt vault.yml
You are prompted for the encryption password, and erstwhile you participate the correct one, the record is decrypted:
Output
Vault password: Decryption successfulIf you position the record again, you spot the existent contents alternatively of the encrypted block:
- cat vault.yml
The record is now plain matter connected disk:
Output
Secret informationYour record is now unencrypted connected disk, truthful beryllium judge to region immoderate delicate accusation aliases re-encrypt the record erstwhile you are finished.
Changing the password of encrypted files
If you request to alteration the password of an encrypted file, usage the ansible-vault rekey command:
- ansible-vault rekey encrypt_me.txt
When you participate the command, you are first prompted for the file’s existent password:
Output
Vault password:After entering it, you are asked to prime and corroborate a caller vault password:
Output
Vault password: New Vault password: Confirm New Vault password:When you person successfully confirmed a caller password, you person a connection indicating the re-encryption succeeded:
Output
Rekey successfulThe record is now accessible utilizing the caller password, and the aged password nary longer works.
Encrypting individual variables pinch ansible-vault encrypt_string
Encrypting an full record is useful, but it has a drawback for shared projects: a reviewer cannot spot which variables a record defines without decrypting it. The ansible-vault encrypt_string bid solves this by encrypting a azygous worth inline, truthful you tin support 1 readable variables record wherever astir values are plain matter and only the delicate ones are encrypted.
To encrypt a worth and delegate it a adaptable name, tally the bid and walk the worth on pinch the --name flag:
- ansible-vault encrypt_string 'supersecretpassword' --name 'mysql_password'
You are prompted for a vault password, and past Ansible prints a ready-to-paste YAML snippet:
Output
New Vault password: Confirm New Vault password: mysql_password: !vault | $ANSIBLE_VAULT;1.1;AES256 39613463343766353861393236363232383831356636373033386230623261306566653034643865 6566383437333436353331353764633033366563343631380a316234383... Encryption successfulYou tin paste that artifact straight into a regular variables file, mixing encrypted and unencrypted values successful 1 place:
vars.yml
--- # nonsensitive data mysql_port: 3306 mysql_host: 10.0.0.3 mysql_user: fred # delicate data, encrypted inline mysql_password: !vault | $ANSIBLE_VAULT;1.1;AES256 39613463343766353861393236363232383831356636373033386230623261306566653034643865 6566383437333436353331353764633033366563343631380a316234383...The !vault tag tells Ansible that the worth is encrypted and should beryllium decrypted astatine runtime. This attack keeps adaptable names visible successful codification reappraisal while protecting only the concealed values, which is why it is often preferred complete encrypting full files successful collaborative repositories.
Running Ansible pinch vault-encrypted files
After you encrypt your delicate accusation pinch Vault, you tin usage the files pinch Ansible’s accepted tooling. The ansible and ansible-playbook commands some cognize really to decrypt vault-protected contented fixed the correct password, and location are a fewer different ways to supply that password depending connected your needs.
To travel along, you request a vault-encrypted file. Create 1 pinch the following:
- ansible-vault create secret_key
Select and corroborate a password, past capable successful immoderate dummy contents you want:
secret_key
confidential dataSave and adjacent the file. Next, create a impermanent hosts record to enactment arsenic an inventory:
- nano hosts
Add conscionable the Ansible localhost to it. To hole for a later step, spot it successful the [database] group:
hosts
[database] localhost ansible_connection=localSave and adjacent the file. Now create an ansible.cfg record successful the existent directory if 1 does not already exist:
- nano ansible.cfg
For now, adhd a [defaults] conception and constituent Ansible to the inventory you conscionable created:
ansible.cfg
[defaults] inventory = ./hostsWhen you are ready, proceed connected to the different ways of supplying a password.
Using an interactive prompt
The astir straightforward measurement to decrypt contented astatine runtime is to person Ansible punctual you for the password. Add the --ask-vault-pass emblem to immoderate ansible aliases ansible-playbook command, and Ansible will punctual you for a password to usage erstwhile it encounters vault-protected content.
For example, to transcript the contents of a vault-encrypted record to a host, you could usage the transcript module pinch the --ask-vault-pass flag. If the record contains existent delicate data, you astir apt want to fastener down entree connected the distant big pinch support and ownership restrictions.
Note: This illustration uses localhost arsenic the target big to minimize the number of servers required, but the results are the aforesaid arsenic if the big were genuinely remote.
- ansible --ask-vault-pass -bK -m transcript -a 'src=secret_key dest=/tmp/secret_key mode=0600 owner=root group=root' localhost
The task specifies that the file’s ownership should alteration to root, truthful administrative privileges are required. The -bK emblem tells Ansible to punctual for the sudo (become) password connected the target host, truthful you are asked for that first, past for the Vault password:
Output
BECOME password: Vault password:When the passwords are provided, Ansible executes the task, utilizing the Vault password for immoderate encrypted files it finds. Keep successful mind that each files referenced during a azygous execution must usage the aforesaid password:
Output
localhost | SUCCESS => { "changed": true, "checksum": "7a2eb5528c44877da9b0250710cba321bc6dac2d", "dest": "/tmp/secret_key", "gid": 0, "group": "root", "md5sum": "270ac7da333dd1db7d5f7d8307bd6b41", "mode": "0600", "owner": "root", "size": 18, "src": "/home/sammy/.ansible/tmp/ansible-tmp-1480978964.81-196645606972905/source", "state": "file", "uid": 0 }Prompting for a password is secure, but it tin beryllium tedious connected repeated runs and it hinders automation, truthful the adjacent sections screen alternatives.
Using a vault password file
If you do not want to type the Vault password each time, you tin shop it successful a record and reference that record during execution. For example, put your password successful a .vault_pass file:
- echo 'my_vault_password' > .vault_pass
Note: A vault password record is arsenic delicate arsenic the password itself. Restrict its permissions truthful only your personification tin publication it, and ne'er perpetrate it to type control.
Lock down the record truthful that only your personification tin publication it, then, if you usage type control, adhd it to your disregard record truthful you do not perpetrate it by accident:
- chmod 600 .vault_pass
- echo '.vault_pass' >> .gitignore
Now reference the record pinch the --vault-password-file flag. You tin complete the aforesaid task from the past conception without an interactive Vault prompt:
- ansible --vault-password-file=.vault_pass -bK -m transcript -a 'src=secret_key dest=/tmp/secret_key mode=0600 owner=root group=root' localhost
You are not prompted for the Vault password this time:
Output
localhost | SUCCESS => { "changed": false, "checksum": "52d7a243aea83e6b0e478db55a2554a8530358b0", "dest": "/tmp/secret_key", "gid": 0, "group": "root", "mode": "0600", "owner": "root", "path": "/tmp/secret_key", "size": 8, "state": "file", "uid": 0 }Reading the password record automatically
To debar providing a emblem astatine all, group the ANSIBLE_VAULT_PASSWORD_FILE situation adaptable pinch the way to the password file:
- export ANSIBLE_VAULT_PASSWORD_FILE=./.vault_pass
You tin now tally the bid without the --vault-password-file emblem for the existent session:
- ansible -bK -m transcript -a 'src=secret_key dest=/tmp/secret_key mode=0600 owner=root group=root' localhost
To make Ansible alert of the password record location crossed sessions, edit your ansible.cfg file. Open the section ansible.cfg you created earlier:
- nano ansible.cfg
In the [defaults] section, group the vault_password_file action to the location of your password file. This tin beryllium a comparative aliases absolute path, whichever is astir useful for you:
ansible.cfg
[defaults] . . . vault_password_file = ./.vault_passNow, erstwhile you tally commands that require decryption, you are nary longer prompted for the vault password. As a bonus, ansible-vault besides uses the password successful the record automatically erstwhile creating caller files pinch ansible-vault create aliases encrypting existing ones pinch ansible-vault encrypt.
Reading the password from an situation variable
You whitethorn interest astir accidentally committing your password record to your repository. While Ansible has an situation adaptable that points to the location of a password file, it does not person 1 for mounting the password worth itself. However, if your password record is executable, Ansible runs it arsenic a book and uses the resulting output arsenic the password. The pursuing short book sounds the password from an situation adaptable alternatively of storing it connected disk.
Open your .vault_pass record successful your editor:
- nano .vault_pass
Replace the contents pinch the pursuing script. Note the parentheses connected print(), which are required successful Python 3:
.vault_pass
#!/usr/bin/env python3 import os print(os.environ['VAULT_PASSWORD'])Make the record executable:
- chmod +x .vault_pass
You tin past group and export the VAULT_PASSWORD situation variable, which is disposable for your existent session:
- export VAULT_PASSWORD=my_vault_password
You person to do this astatine the opening of each Ansible session, which whitethorn sound inconvenient. However, it efficaciously guards against accidentally committing your Vault password, since the password itself is ne'er written to disk. This shape is besides the instauration of the CI/CD attack described later.
Working pinch aggregate vault passwords
As projects grow, a azygous password seldom fits each secret. You often want abstracted passwords for development, staging, and production, truthful that a developer pinch the dev password cannot decrypt accumulation secrets. Ansible handles this pinch vault IDs, which connect a explanation to each password.
A vault ID uses the syntax label@source, wherever root is either a password record aliases the keyword prompt. For example, to encrypt a drawstring pinch a accumulation vault ID and beryllium prompted for the password, tally the following:
- ansible-vault encrypt_string --vault-id prod@prompt 'RealProductionPassword' --name 'vault_db_password'
When you usage a branded vault ID, the explanation is recorded successful the encrypted block’s header, which changes from type 1.1 to 1.2 and includes the label:
Output
$ANSIBLE_VAULT;1.2;AES256;prodWhen you tally a playbook, you tin proviso respective vault IDs astatine once, and Ansible tries each 1 arsenic needed. The pursuing passes a improvement password from a record and prompts for the accumulation password:
- ansible-playbook site.yml --vault-id dev@dev_pass --vault-id prod@prompt
When decrypting, Ansible tries the password whose explanation matches the encrypted contented first, past falls backmost to trying the others successful the bid you provided them. Vault IDs are astir useful erstwhile you abstracted secrets by environment, erstwhile different squad members clasp different passwords, aliases erstwhile you rotate 1 environment’s password without rubbing the others.
Using vault-encrypted variables pinch regular variables
While Ansible Vault tin encrypt arbitrary files, it is astir often utilized to protect delicate variables. This conception useful done an illustration that transforms a regular variables record into a configuration that balances information and usability. It complements the inline encrypt_string attack shown earlier by splitting secrets into a abstracted encrypted file.
Setting up the example
For this example, dress you are configuring a database server, without really installing a database. When you created the hosts record earlier, you placed the localhost introduction successful a group called database to hole for this step. Databases usually require a substance of delicate and nonsensitive variables, which you tin delegate successful a group_vars directory successful a record named aft the group:
- mkdir -p group_vars
- nano group_vars/database.yml
Inside the group_vars/database.yml file, adhd immoderate emblematic variables. Some, for illustration the MySQL larboard number, are not concealed and tin beryllium freely shared, while others, for illustration the database password, are confidential:
group_vars/database.yml
--- # nonsensitive data mysql_port: 3306 mysql_host: 10.0.0.3 mysql_user: fred # delicate data mysql_password: supersecretpasswordYou tin trial that each of the variables are disposable to your big pinch Ansible’s debug module and the hostvars variable:
- ansible -m debug -a 'var=hostvars[inventory_hostname]' database
The output confirms that each adaptable you defined is applied to the host:
Output
localhost | SUCCESS => { "hostvars[inventory_hostname]": { "ansible_check_mode": false, "ansible_version": { "full": "2.18.1", "major": 2, "minor": 18, "revision": 1, "string": "2.18.1" }, "group_names": [ "database" ], "groups": { "all": [ "localhost" ], "database": [ "localhost" ], "ungrouped": [] }, "inventory_dir": "/home/sammy", "inventory_file": "hosts", "inventory_hostname": "localhost", "inventory_hostname_short": "localhost", "mysql_host": "10.0.0.3", "mysql_password": "supersecretpassword", "mysql_port": 3306, "mysql_user": "fred", "omit": "__omit_place_holder__1c934a5a224ca1d235ff05eb9bda22044a6fb400", "playbook_dir": "." } }The output confirms that each of the variables are applied to the host. However, the group_vars/database.yml record presently holds each of the variables together. This intends you tin either time off it unencrypted, which is simply a information interest because of the database password, aliases encrypt each of the variables, which creates usability and collaboration problems.
Moving delicate variables into Ansible Vault
To lick this, make a favoritism betwixt delicate and nonsensitive variables truthful you tin encrypt confidential values while still easy sharing the rest. To do so, divided the variables betwixt 2 files.
You tin usage a adaptable directory successful spot of a adaptable file to use variables from much than 1 file. First, rename the existing record from database.yml to vars.yml, which will beryllium your unencrypted adaptable file:
- mv group_vars/database.yml group_vars/vars.yml
Next, create a directory pinch the aforesaid sanction arsenic the aged adaptable file, and move the vars.yml record wrong it:
- mkdir group_vars/database
- mv group_vars/vars.yml group_vars/database/
You now person a adaptable directory for the database group alternatively of a azygous file, positive 1 unencrypted adaptable file. Since you will beryllium encrypting your delicate variables, region them from the unencrypted file. Edit group_vars/database/vars.yml to region the confidential data:
- nano group_vars/database/vars.yml
In this case, region the mysql_password adaptable truthful the record looks for illustration this:
group_vars/database/vars.yml
--- # nonsensitive data mysql_port: 3306 mysql_host: 10.0.0.3 mysql_user: fredNext, create a vault-encrypted record successful the directory that will unrecorded alongside the unencrypted vars.yml file:
- ansible-vault create group_vars/database/vault.yml
In this file, specify the delicate variables that utilized to beryllium successful the vars.yml file. Use the aforesaid adaptable names, but prepend the drawstring vault_ to bespeak that these variables are defined successful the vault-protected file:
group_vars/database/vault.yml
--- vault_mysql_password: supersecretpasswordSave and adjacent the file. The resulting directory building looks for illustration this:
. ├── . . . ├── group_vars/ │ └── database/ │ ├── vars.yml │ └── vault.yml └── . . .At this point, the variables are abstracted and only the confidential information is encrypted. This is secure, but it has reduced usability: while the extremity was to protect delicate values, you person besides unintentionally hidden the adaptable names. It is not clear which variables are assigned without referencing much than 1 file, and you astir apt still want to stock the adaptable names moreover while restricting entree to the values. To reside this, the Ansible task recommends a somewhat different approach.
Referencing vault variables from unencrypted variables
When you moved the delicate information to the vault-protected file, you prefaced the adaptable names pinch vault_, truthful mysql_password became vault_mysql_password. You tin adhd the original adaptable names backmost to the unencrypted record and, alternatively of mounting them to delicate values directly, usage Jinja2 templating to reference the encrypted variables. This way, you tin spot each of the defined variables successful a azygous file, while the confidential values stay successful the encrypted file.
Open the unencrypted variables record again:
- nano group_vars/database/vars.yml
Add the mysql_password adaptable again, this clip utilizing Jinja2 templating to reference the adaptable defined successful the vault-protected file:
group_vars/database/vars.yml
--- # nonsensitive data mysql_port: 3306 mysql_host: 10.0.0.3 mysql_user: fred # delicate data mysql_password: "{{ vault_mysql_password }}"The mysql_password adaptable is group to the worth of vault_mysql_password, which is defined successful the vault file. With this method, you tin understand each of the variables that use to hosts successful the database group by viewing the group_vars/database/vars.yml file, while the delicate parts enactment obscured down the Jinja2 reference. You only request to unfastened group_vars/database/vault.yml erstwhile the values themselves request to beryllium viewed aliases changed.
You tin cheque that each of the mysql_* variables are still correctly applied utilizing the aforesaid method arsenic before.
Note: If your Vault password is not being applied automatically done a password file, adhd the --ask-vault-pass emblem to the bid below.
- ansible -m debug -a 'var=hostvars[inventory_hostname]' database
The output shows some variables resolving to the aforesaid concealed value:
Output
localhost | SUCCESS => { "hostvars[inventory_hostname]": { "ansible_check_mode": false, "ansible_version": { "full": "2.18.1", "major": 2, "minor": 18, "revision": 1, "string": "2.18.1" }, "group_names": [ "database" ], "groups": { "all": [ "localhost" ], "database": [ "localhost" ], "ungrouped": [] }, "inventory_dir": "/home/sammy/vault", "inventory_file": "./hosts", "inventory_hostname": "localhost", "inventory_hostname_short": "localhost", "mysql_host": "10.0.0.3", "mysql_password": "supersecretpassword", "mysql_port": 3306, "mysql_user": "fred", "omit": "__omit_place_holder__6dd15dda7eddafe98b6226226c7298934f666fc8", "playbook_dir": ".", "vault_mysql_password": "supersecretpassword" } }Both vault_mysql_password and mysql_password are accessible, and this plagiarism is harmless and will not impact your usage of the system.
Ansible Vault compared pinch situation variables and outer secrets managers
Ansible Vault is not the only measurement to grip secrets successful automation, and choosing the correct instrumentality depends connected your squad size, your workflow, and really your secrets are consumed. The pursuing array compares the 3 astir communal approaches.
| Ansible Vault | Yes (AES-256) | Yes (encrypted files only) | Yes, pinch a password injected astatine runtime | Low |
| Plain situation variables | No | No (never perpetrate secrets) | Yes, via pipeline secrets | Very low |
| External secrets manager | Yes, pinch rotation and auditing | Yes (no concealed stored successful repo) | Yes, via API aliases plugin | High |
Ansible Vault is the champion fresh erstwhile you want secrets encrypted astatine remainder and stored alongside your playbooks successful the aforesaid repository, which suits mini to mid-sized teams and infrastructure-as-code workflows. Plain situation variables are simplest for a azygous concealed consumed astatine runtime, but they connection nary encryption astatine remainder and must ne'er beryllium committed. An outer secrets head is the strongest action for ample organizations that request centralized rotation, fine-grained entree control, and audit logging, astatine the costs of further infrastructure to tally and integrate. Many teams harvester approaches, for illustration utilizing Ansible Vault for project-level secrets and an outer head for organization-wide credentials.
Best practices for managing secrets pinch Ansible Vault
A fewer habits support a vault-based workflow some unafraid and maintainable:
-
Keep the vault password record extracurricular type power and restrict it pinch chmod 600, and adhd unencrypted concealed files to .gitignore truthful they are ne'er committed.
-
Prefer ansible-vault encrypt_string for individual values successful shared repositories truthful reviewers tin still spot adaptable names, and reserve whole-file encryption for files that are wholly sensitive.
-
Use a clear naming convention, specified arsenic the vault_ prefix, truthful it is evident which variables travel from an encrypted source.
-
Separate vault IDs by situation (for illustration dev, staging, and prod) truthful that entree to 1 environment’s secrets does not assistance entree to another’s.
-
Rotate vault passwords connected a defined schedule utilizing ansible-vault rekey, and rotate instantly if a password whitethorn person been exposed.
-
Store the vault passwords themselves successful a dedicated password head aliases secrets manager, because losing a vault password intends the encrypted information cannot beryllium recovered.
-
Use no_log: existent connected immoderate task that handles a decrypted concealed to forestall the worth from appearing successful task output, logs, aliases Ansible Tower / AWX occupation results. For example:
- name: Create database user community.mysql.mysql_user: name: "{{ mysql_user }}" password: "{{ mysql_password }}" state: present no_log: trueVault protects information connected disk; no_log protects it astatine runtime. Both controls together springiness you defense successful depth.
-
Although ansible-vault encrypt useful connected immoderate record including full playbooks, whole-playbook encryption is seldom applicable successful squad settings because it prevents anyone from reference the task database without decrypting it first. Prefer encrypting only the variables files that incorporate secrets, and support your playbooks successful plain text.
FAQs
1. Can you usage Ansible Vault to shop delicate information?
Yes, Ansible Vault is designed specifically to shop delicate accusation specified arsenic passwords, API keys, backstage keys, and TLS certificates by encrypting them astatine rest. It is due for immoderate concealed you request disposable during a playbook tally but do not want visible successful plain matter successful your repository. Keep successful mind what it does not protect: erstwhile Ansible decrypts a worth astatine runtime, that worth exists successful representation arsenic a normal adaptable and tin look successful verbose output aliases logs, truthful it secures information connected disk alternatively than during execution.
2. How do you encrypt a record pinch Ansible Vault?
Run ansible-vault encrypt filename.yml to encrypt an existing file, aliases ansible-vault create filename.yml to create and encrypt a caller one. In some cases Ansible prompts you to participate and corroborate a vault password, past writes the encrypted contented backmost to disk successful spot of the original. You tin corroborate the consequence pinch feline filename.yml, which shows the $ANSIBLE_VAULT header followed by the encrypted payload alternatively of your plain text.
3. How unafraid is Ansible Vault?
Ansible Vault uses AES-256 encryption successful CTR mode and derives its cardinal from your password pinch PBKDF2 utilizing HMAC-SHA256 complete 10,000 iterations, which are strong, industry-standard algorithms. Because the cardinal is derived straight from your password, the real-world information depends connected choosing a long, unsocial password and storing it safely alternatively than connected the algorithm. Vault protects information astatine remainder only, truthful it does not forestall a decrypted concealed from being exposed successful memory, logs, aliases verbose output during a run.
4. Which characteristic should you usage to securely negociate delicate information specified arsenic passwords successful your Ansible playbook?
Ansible Vault is the built-in characteristic for securely managing delicate information specified arsenic passwords successful your playbooks. It encrypts secrets astatine remainder and integrates straight pinch the ansible and ansible-playbook commands, which decrypt the contented automatically astatine runtime erstwhile you proviso the password. For organization-wide credential guidance pinch rotation and auditing, you tin complement Vault pinch an outer secrets head specified arsenic HashiCorp Vault.
5. What is the quality betwixt ansible-vault encrypt and ansible-vault encrypt_string?
ansible-vault encrypt encrypts an full file, truthful the full record becomes an opaque encrypted block, while ansible-vault encrypt_string encrypts a azygous worth and returns an inline YAML snippet you tin paste into an different plain-text variables file. Use whole-file encryption erstwhile a record contains only secrets, and usage encrypt_string erstwhile you want astir variables to enactment readable and only circumstantial values encrypted. The inline attack is mostly friendlier for codification reappraisal successful shared repositories.
6. How do you usage a vault password record alternatively of typing a password interactively?
Save the password successful a record and reference it pinch the --vault-password-file flag, for illustration ansible-playbook site.yml --vault-password-file .vault_pass, aliases group the ANSIBLE_VAULT_PASSWORD_FILE situation adaptable to the file’s way truthful you do not request the flag. You tin besides group vault_password_file successful the [defaults] conception of ansible.cfg to make it the default. In each case, restrict the record pinch chmod 600 and adhd it to .gitignore truthful it is ne'er readable by others aliases committed to type control.
7. Can Ansible Vault beryllium utilized successful CI/CD pipelines?
Yes, Ansible Vault useful good successful CI/CD pipelines. Store the vault password arsenic a protected pipeline concealed (for example, a masked CI/CD variable), past person the pipeline constitute it to a impermanent record astatine the commencement of the run, walk that record pinch --vault-password-file, and delete the record erstwhile the tally finishes. This keeps the password retired of the repository and retired of the build logs while still allowing afloat automated, unattended playbook runs.
Here is an illustration GitHub Actions step:
- name: Run playbook env: VAULT_PASSWORD: ${{ secrets.VAULT_PASSWORD }} run: | echo "$VAULT_PASSWORD" > .vault_pass chmod 600 .vault_pass ansible-playbook site.yml --vault-password-file .vault_pass rm -f .vault_passFor GitLab CI, the shape is equivalent: group VAULT_PASSWORD arsenic a masked CI/CD adaptable successful your task settings and reference it the aforesaid way. Always delete the impermanent record successful the aforesaid measurement truthful it is removed moreover if the playbook fails.
8. What happens if you suffer your Ansible Vault password?
If you suffer a vault password, the information encrypted pinch it cannot beryllium recovered, because the password is required to deduce the decryption cardinal and location is nary backdoor aliases betterment mechanism. Your only options are to reconstruct the original unencrypted information from different root aliases recreate the secrets. To debar this situation, shop vault passwords successful a dedicated password head aliases secrets manager, and see rekeying important vaults connected a schedule truthful the existent password is ever known and backed up.
Conclusion
In this guide, you learned really Ansible Vault encrypts information pinch AES-256. You besides learned really to encrypt some full files and individual variables, really to proviso vault passwords interactively aliases done password files and situation variables, really to negociate aggregate passwords pinch vault IDs, and really Vault compares pinch different secrets-management approaches. With these tools, you tin support each of your configuration information successful 1 spot without compromising security.
To support building your Ansible skills, research these related DigitalOcean tutorials:
- How to Install and Configure Ansible connected Ubuntu
- Configuration Management 101: Writing Ansible Playbooks
- How to Use Ansible: A Reference Guide
- How To Write Ansible Playbooks
- An Introduction to Configuration Management pinch Ansible
This activity is licensed nether a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
English (US) ·
Indonesian (ID) ·