mantl / terraform.py

Ansible dynamic inventory script for parsing Terraform state files
Apache License 2.0
451 stars 122 forks source link

Different terraform roots based on different inventories #47

Open sean-abbott opened 8 years ago

sean-abbott commented 8 years ago

As per the ansible best practices, I keep different inventories for different environments (or, at my current place of work, stages)

In keeping with that premise and with things I've been reading about terraform on the web (primarily this post), I have also separated by terraform out into different tfstate files on a per-stage basis.

So, my directory structure looks like: site/ ├── group_vars ├── inventory │   ├── base │   ├── dev │   └── prod ├── playbooks │   └── includes ├── terraform │   ├── base │   ├── dev │   ├── modules │   │   ├── app_instance │   │   └── db_instance │   ├── prod └── vault

So, I need my dynamic inventory to match my terraform state file. If I use -i inventory/dev, then my inventory should parse only terraform/dev.

I've hacked this into the current version:

def get_stage_root(tf_dirname=None, root=None):
    """ look for a matching terraform root directory """
    root = root or os.getcwd()
    tf_dirname = tf_dirname or 'terraform'
    inv_dir = os.path.dirname(__file__).split(os.path.sep)[-1]
    terraform_base = os.path.join(root, tf_dirname)
    if inv_dir in os.listdir(terraform_base):
        return os.path.join(terraform_base, inv_dir)
    else:
        return root

and in main()

    staged_root = get_stage_root(root=args.root)
    if staged_root != args.root:
        args.root = staged_root

As I have this written, it's probably only useful to me. However, I thought it might be useful to other folks if it were made more generic.

I use this primarily for amazon. It seems like there's enough config variation that you might want to either consider adding a config stanza to the ansible config, or to add a custom terraform_inventory.cfg at either the root directory level or the file level.

sean-abbott commented 7 years ago

AFAIK, this actually still exists in the code, because when we merged this, I was using it locally.