Skip to content

Instantly share code, notes, and snippets.

@ChristophShyper
Last active February 17, 2021 12:28
Show Gist options
  • Save ChristophShyper/b343567feba26e2c095d7d301a9dae5d to your computer and use it in GitHub Desktop.
Save ChristophShyper/b343567feba26e2c095d7d301a9dae5d to your computer and use it in GitHub Desktop.
Filter AWS accounts for Terraform

Reading and fitlering AWS accounts' attributes with Terraform

To fix hashicorp/terraform-provider-aws#17656 I created a simple script using external data source for Terraform.

Using it I'm able, for example, to list all ACTIVE accounts with IDs or emails.

Usage

local {
  accounts_emails = split(",", data.external.accounts.result.Outputs)
}

Data source

data "external" "accounts" {
  program = ["python3", "${path.module}/../utils/get_accounts.py"]
  query = {
    status    = "ACTIVE"
    parameter = "Email"
  }
}

Python script

#!/usr/bin/env python

import boto3
import json
import sys


"""
Script for filtering accounts' parameters
"""


def handler(arg):
    status = arg['status']
    parameter = arg['parameter']
    organizations = boto3.client('organizations')
    organizations_paginator = organizations.get_paginator('list_accounts')
    response_iterator = organizations_paginator.paginate(
        PaginationConfig={
            'MaxItems': 200,
            'PageSize': 20,  # Max allowed
        }
    )
    resp = []
    for page in response_iterator:
        for acc in page['Accounts']:
            if acc['Status'] == status:
                resp.append(acc[parameter])
    ret = {
        'Outputs': ','.join(map(str, resp))
    }
    print("{}".format(json.dumps(ret)))


if __name__ == '__main__':
    data = json.load(sys.stdin)
    handler(data)
    exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment