Tuve un problema similar pero copiando SG en diferentes cuentas.
Simplemente especifique algunas CONSTANTES al principio y la función copy_sg las copiará.
No se ha realizado ninguna verificación de error, por lo tanto, si el SG objetivo ya existe, fallará.
Siga una solución general que se puede usar también dentro de la cuenta:
#!/usr/bin/env python3
# coding: utf-8
import boto3
from typing import Any, List
# This profile needs to be able to assume the specified role in SRC/TGT account
appops_session = boto3.Session(profile_name='YOUR_PRECONFIGURE_PROFILE')
ROLE = "THE ROLE TO BE ASSUMED" # I presume it is the same in SRC/TGT Account
SRC_ACCOUNT = "YOUR SRC ACCOUNT NUMBER"
TGT_REGION = "eu-central-1"
DST_ACCOUNT = "YOUR TARGET ACCOUNT NUMBER"
TGT_VPC = "vpc-XXXXXXXXXXXXXXX"
region = "ap-southeast-2"
dst_vpc_id = "vpc-XXXXXXXXXXXXXXX"
sg_list = ["sg-XXXXXXXX", "sg-YYYYYYYYY"]
def aws_sts_cred(account, role):
"""Get the STS credential.
return credential_object
"""
sts_creds = {}
sts_conn = appops_session.client('sts')
role_arn = "arn:aws:iam::" + account + ":role/" + role
assumed_role = sts_conn.assume_role(RoleArn=role_arn,
RoleSessionName="TMPROLE")
sts_creds["aws_access_key_id"] = assumed_role['Credentials']['AccessKeyId']
sts_creds["aws_secret_access_key"] = assumed_role['Credentials']['SecretAccessKey']
sts_creds["aws_session_token"] = assumed_role['Credentials']['SessionToken']
return sts_creds
def aws_conn(service: str, region: str, **kwargs) -> Any:
"""Create a client object."""
return boto3.client(service, region_name=region, **kwargs)
def dump_sg(client, vpcid: str = "", sgids: List = []) -> List:
"""Dump the specified SG."""
print(sgids)
sg_info = client.describe_security_groups(
Filters = [{'Name': 'group-id', 'Values': sgids}])['SecurityGroups']
return sg_info
def copy_sg(tgt_client, sgs, vpcid=""):
for sg in sgs:
# With no Vpc ID the SG is created in the default VPC.
resp = tgt_client.create_security_group(
GroupName=sg['GroupName'], Description=sg['Description'], VpcId=vpcid)
new_grp_id = resp['GroupId']
tgt_client.authorize_security_group_ingress(
GroupId=new_grp_id, IpPermissions=sg.get('IpPermissions', list()))
if sg.get('IpPermissionsEgress') != []:
# It doesn't work with an empty list
tgt_client.authorize_security_group_egress(
GroupId=new_grp_id, IpPermissions=sg.get('IpPermissionsEgress'))
print("Create SG {} - \"{}\" - \"{}\" in VPCID: {}".format(new_grp_id, sg['GroupName'], sg['Description'], vpcid))
STS_CRED = aws_sts_cred(SRC_ACCOUNT, ROLE)
STS_CRED_TGT = aws_sts_cred(DST_ACCOUNT, ROLE)
src_client = aws_conn("ec2", region, **STS_CRED)
sg_list = dump_sg(src_client, sgids=sg_list)
tgt_client = aws_conn("ec2", TGT_REGION, **STS_CRED_TGT)
copy_sg(tgt_client, sg_list)