Dynamically include vaulted vars within playbook only for certain hosts

309 views
Skip to first unread message

Pete Albrecht

unread,
Feb 22, 2017, 1:08:33 PM2/22/17
to Ansible Project
Greetings!

I'm trying to figure out the best way to dynamically include vaulted vars files in a playbook only for certain hosts. The situation is I'm building out production and pre-prod environments from a common playbook, including development (via vagrant) where the vault password will not be available. The vault password wont be distributed anywhere except for the build box. I tried using group_vars, but the problem I run into is ansible tries to decrypt vars files for other hosts when running the playbook in dev where the vault password is not available. The only work-around I could find is to make a task or role that sets those variables using set_fact, and only including that task in the hosts that need it. I'm wondering if there is a better way or if I'm doing it wrong.

---
- hosts: ci_dev

  roles:
    # Configure ssh key jenkins will use to talk to bitbucket and web, db, etc
    - role: ssh_keys
      ssh_key_dir: "/home/jenkins/.ssh"

      # these should come from Vagrantfile via Vagrantfile.local
      ssh_public_key: "{{ ci_public_key }}"
      ssh_private_key: "{{ ci_private_key }}"

- hosts: ci_prod

  # have to dynamically include vault vars so it doesn't try to decrypt in dev
  pre_tasks:
    - include: vault_vars/ci_prod/vault.yml
      static: false

  roles:
    # Non-dev environments
    - dns

    # Configure ssh key jenkins will use to talk to bitbucket and web, db, etc
    - role: ssh_keys
      ssh_key_dir: "/home/jenkins/.ssh"

      # these should come from the ansible vault ci/provision/group_vars/vault
      ssh_public_key: "{{ vault_ci_public_key }}"
      ssh_private_key: "{{ vault_ci_private_key }}"

and the task:
---
- name: vaulted variables included
  set_fact:
    vault_ci_public_key: "dsafa"
    vault_ci_private_key: "adfa"



Brian Coca

unread,
Feb 28, 2017, 11:25:51 AM2/28/17
to Ansible Project
To include variables, use include_vars, not include (this only works
for plays or tasks).

Include_vars is always dynamic, so you just need a when:

- include_vars: vault_vars/ci_prod/vault.yml
when: myenv != 'dev'

# example when condition

----------
Brian Coca
Reply all
Reply to author
Forward
0 new messages