A Playbook which Stores Vars

Hi,

I’ve been struggling with how to implement a task which creates a new var which will be used in subsequent playbooks.

For example, I have a accounts.yml vars file with entries like this:

  • accounts:

  • title: Some human readable name
    owner_email: somebody@somewhere.com
    name: sombody_at_somewhere_com

api_key: ApiKeyString

s3_bucket: s3.bucket.name

  • title: Another human readable name

etc.

In my main playbook, I include a tasks files to generate a series of server configs based on these vars using

  • include: tasks_for_each_account.yml

with_items: ${accounts}

My main playbook based on this works fine.

I also created a simple playbook (create_account) which prompts for email and “human readable” name and uses the uri and s3 actions to create a new API key and S3 bucket for an account. The problem is that I then need to manually open up the accounts.yml file and add a new entry for this newly created account.

My goal is that the create_account playbook prompts for the two required fields, creates the API key and S3 bucket and then stores the information in such a way that it’s available to other playbooks (for example my main playbook).

I’m not at all sure that storing all of the account information in a single yml file is the best idea, but it’s what I went with as I started this.

My initial impulse is to use a local action with a template to create a series of files in the vars directory like somebody_at_somewhere_com.yml, person_at_url_net.yml, etc. Unfortunately, I’m not sure how I would iterate over these created vars files in other playbooks. Since these created vars files would define a series of separate top level variables, instead of a single top level list, simply saying “with_items” wouldn’t work. I’ve looked at files_glob, but I don’t think it would work in this case (feel free to correct me if I’m wrong).

In any case, before I go too far down the rabbit hole in this direction, I’d like some feedback. I’m also open to other suggestions (like “creating new accounts isn’t really supported in ansible, just write a helper script to do that and update the accounts.yml file”), but I’d prefer to keep it in ansible if possible.

All the best,

~ Christopher

Public service announcement. This post uses old style variables. Please don’t use those as you can just say:

with_items: accounts

If you’re trying to create a variable in a playbook, any variables you use with the “register” task are accessible in “hostvars” later, even from other server operations.

You should never do include + with_items as it’s super confusing, and this will be an error in future versions of Ansible.

Instead put your loop within the task file and use “with_items” inside there.