Skip to content
This repository was archived by the owner on Jul 27, 2023. It is now read-only.
This repository was archived by the owner on Jul 27, 2023. It is now read-only.

Different terraform roots based on different inventories #47

Open
@sean-abbott

Description

@sean-abbott

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.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions