Is there a way to update the primary_aws_region field for multiple AWS accounts?
search cancel

Is there a way to update the primary_aws_region field for multiple AWS accounts?

book

Article ID: 284309

calendar_today

Updated On:

Products

CloudHealth

Issue/Introduction

The below script can be used update primary_aws_region field for multiple AWS account all at once: 

 

import json
import http.client
import ssl
from pprint import pprint

#Print Description
print("This script calls the aws accounts api to list all accounts. For each account it will attempt to configure eu-west-2 region to be used to validate the read-only IAM policy. It will fail if no role acess permissions are applied.")

#Prompt for inputs
api_key = input('To continue type your API Key here, to cancel press control+c. ')

class Account:
def __init__(self, id, amazon_name, owner_id):
self.id = id
self.amazon_name = amazon_name
self.owner_id = owner_id

accounts = []

def main():
#Functions
class Account:
def __init__(self, uniqueAccountID, assetID):
self.uniqueAccountID = uniqueAccountID
self.assetID = assetID

class AccountList:
def __init__(self, partnerapikey):
self.accounts = []
self._fetch_accounts(partnerapikey)

def _fetch_accounts(self, partnerapikey):
page = 1
while page:
conn = http.client.HTTPSConnection('chapi.cloudhealthtech.com', context=ssl._create_unverified_context())
url = f'/v1/aws_accounts?api_key={partnerapikey}&page={page}&per_page=100'
conn.request('GET', url)
response = conn.getresponse()
temp_aws_accounts_details = json.loads(response.read())
page += 1
try:
if temp_aws_accounts_details['aws_accounts'] == []:
break
except KeyError:
break
for account in temp_aws_accounts_details['aws_accounts']:
try:
uniqueAccountID = account['owner_id']
except KeyError:
print(f"Error processing account {account['id']}: missing owner ID")
continue
a = Account(uniqueAccountID, account['id'])
self.accounts.append(a)
conn.close()

def __len__(self):
return len(self.accounts)

def __iter__(self):
return iter(self.accounts)

def add_region_account(api_key, account_asset_id):
base_url = 'chapi.cloudhealthtech.com'
query = f'/v1/aws_accounts/{account_asset_id}'
headers = {'Content-type': 'application/json', 'Authorization': 'Bearer %s' % api_key}
data = {
"primary_aws_region": "eu-west-2"
}
body = json.dumps(data)
connection = http.client.HTTPSConnection(base_url, context=ssl._create_unverified_context())
connection.request('PUT', url=query, body=body, headers=headers)
response = connection.getresponse()
status = response.status
payload = json.loads(response.read().decode())
connection.close()
return status, payload

#Werk
accounts_list = AccountList(api_key)
print(len(accounts_list))
for account in accounts_list:
pprint([account.uniqueAccountID, account.assetID])
pprint(add_region_account(api_key, account.assetID))
main()