Skip to content

Commit

Permalink
[IT-3047] Add script for updating owner email tags (Sage-Bionetworks#53)
Browse files Browse the repository at this point in the history
Add a script to be run by an AWS admin for updating the value of the
OwnerEmail and synapse:email tags. The script finds all resources tagged
with the former value and updates those tags to the new value.
  • Loading branch information
jesusaurus authored Feb 1, 2024
1 parent 9f923bf commit 704eccb
Show file tree
Hide file tree
Showing 2 changed files with 133 additions and 0 deletions.
32 changes: 32 additions & 0 deletions aws/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* [tag-instance-volume.ps1](#tag-instance-volumeps1)
* [tag_instance.ps1](#tag_instanceps1)
* [update_other_tag.py](#update_other_tagpy)
* [update_owner_tag.py](#update_owner_tagpy)


## associate-jc-system.ps1
Expand Down Expand Up @@ -102,6 +103,7 @@ Assumes the following are installed through choco:
tag_instance.ps1
```


## update_other_tag.py

Set the value of CostCenterOther for a specified EC2 instance, including related resources in the same cloudformation stack
Expand Down Expand Up @@ -129,6 +131,36 @@ The following python packages are required:
* MIPS_API_URL: (Optional) Overwrite default mips-api URL, https://mips-api.finops.sageit.org/tags?show_inactive_codes&disable_other_code

#### Example

```
AWS_PROFILE=org-sagebase-scipooldev update_other_tag.py -r i-061fee3df7b496cd5 -t "No Program / 000000"
```


## update_owner_tag.py

Perform a search and replace on the owner tags `OwnerEmail` and `synapse:email` across all resources in the current account.
This is useful for transferring ownership of resources. The old tag value cannot be the empty string.

### Dependencies

The following python packages are required:

* boto3

### Usage

#### Options

* -o --old-email: (Required) Existing tag value to match on
* -n --new-email: (Required) New tag value to set

#### Environment Variables

* AWS_PROFILE: (Required) Set AWS account based on `~/.aws/config`

#### Example

```
AWS_PROFILE=org-sagebase-scicomp update_owner_tag.py -o "[email protected]" -n "[email protected]"
```
101 changes: 101 additions & 0 deletions aws/update_owner_tag.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import argparse
import logging

import boto3


logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s')
for lib in ["botocore", "urllib3"]:
log = logging.getLogger(lib)
log.setLevel(logging.WARNING)

tag_client = boto3.client('resourcegroupstaggingapi')


def _find_tagged_arns(tag, value):
"""
Find all resources tagged with the same cloudformation stack
"""

found = []
tag_filter = {
"Key": tag,
"Values": [value, ]
}

pager = tag_client.get_paginator("get_resources")
for page in pager.paginate(TagFilters=[tag_filter, ]):
_list = page['ResourceTagMappingList']
for item in _list:
found.append(item["ResourceARN"])

return found


def replace_owner_tag(old_value, new_value):
"""
Update the owner tag value on all resources with a matching tag.
There are two possible resource tags that may contain a resource owner.
For each owner tag, search for all resources with a tag value matching the
former owner, and then update the tag value to the new owner on all matches.
"""

# loop over each possible owner tag
for owner_tag in ["OwnerEmail", "synapse:email"]:
# find all resources with a matching tag value
arns = _find_tagged_arns(owner_tag, old_value)
logging.info(f"ARNs found for tag {owner_tag}: {arns}")
if not arns:
continue

# replace tag value on found resources
logging.info(f"Setting new tag value '{new_value}' on {arns}")
result = tag_client.tag_resources(ResourceARNList=arns,
Tags={owner_tag: new_value})
failed = result["FailedResourcesMap"]
if failed:
logging.error(f"Failed Resources: {failed}")


def cli():
"""
Command Line Interface
Options
old-email: Existing tag value to match on
new-email: New tag value to set
Environment Variables
AWS_PROFILE: Set AWS account based on ~/.aws/config
Example
AWS_PROFILE=org-sagebase-scicomp update_owner_tag.py -o "[email protected]" -n "[email protected]"
"""

arg_parser = argparse.ArgumentParser()

arg_parser.add_argument("-o", "--old-email",
required=True,
help="Owner tag value to replace")

arg_parser.add_argument("-n", "--new-email",
required=True,
help="New tag value for Owner")

args = arg_parser.parse_args()
logging.debug(f"Args: {args}")

if not args.old_email:
logging.error("Old tag value cannot be empty")

elif not args.new_email:
logging.error("New tag value cannot be empty")

else:
replace_owner_tag(args.old_email, args.new_email)


if __name__ == '__main__':
cli()

0 comments on commit 704eccb

Please sign in to comment.