How to Copy a Security Group with Rules from one AWS Account to Another account ? 🧐✅👨‍💻👩‍💻
Tags: aws, linux, devops, cloud
Published: 2021-01-21 03:45:23

#### 𝗜𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗡𝗼𝘁𝗲:  📝𝗢𝗽𝗶𝗻𝗶𝗼𝗻𝘀 𝗮𝗿𝗲 𝗺𝘆 𝗼𝘄𝗻 🏁🙂 𝗔𝗻𝗱 𝗶𝘁 𝗶𝘀 𝗺𝘆 𝗽𝗲𝗿𝘀𝗼𝗻𝗮𝗹 𝗯𝗹𝗼𝗴.

#### As you might be already aware that you can copy rules from an existing security group to a new security group <b> within same Account</b>, you can refer to an existing [AWS Knowledge Center Article](https://aws.amazon.com/premiumsupport/knowledge-center/vpc-copy-security-group-rules/)

- <i>But the Challenge comes in when you need to Achieve it <b> "From one AWS Account to another Account."</b></i>

![CMD Line - Copy SG](https://media.giphy.com/media/ihSGiK0waskWDJ8iyl/giphy.gif)


#### **How to Copy a Security Group with Rules from one Account to Another ?**

- Use this Python Script  [**CopySGFromOneAWSAccountToAnotherScript.py**](https://github.com/dineshrathee12/CopySecurityGroupWithRulesFromOneAWSAccountToAnotherAWSAccount/blob/main/CopySGFromOneAWSAccountToAnotherScript.py) , and you will need to provide the following details:

**Source Account:**
	- Access Key
	- Secret Key
	- Region
	- Security Group Id
	
**Destination Account:**
	- Access Key
	- Secret Key
	- Region

**Script Content**
<p class="MsoNormal"><span style="font-family: &quot;Amazon Ember&quot;; color: rgb(22, 25, 31); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial;"><br></span></p><pre><font color="#16191f" face="Amazon Ember"># -*- coding: utf-8 -*-
"""
Created on Wed May 20 13:30:41 2021
@author: nikheel script, blog dinesh
"""

import boto3

sourceAccount={
        'AccessKey':'access key',
        'SecretKey':'secret key',
        'Region':'source region',
        'SecurityGroupId': 'security group id'
        }
destinationAccount = {
        'AccessKey':'access key',
        'SecretKey':'secret key',
        'Region':'destination region'
        }

# ------ Source Account ------ #

#set up boto3 client for source account

client = boto3.client(
        "ec2",
        region_name = sourceAccount['Region'],
        aws_access_key_id=sourceAccount['AccessKey'],
        aws_secret_access_key=sourceAccount['SecretKey']
        )

# describe security group that will be copied

response = client.describe_security_groups(
        GroupIds=[
                sourceAccount['SecurityGroupId']
                ]
        )["SecurityGroups"][0]

# extract ingress and egress rules for the security group

ingress = response["IpPermissions"]
egress = response["IpPermissionsEgress"]

# ------ Destination Account ------ #

#set up boto3 client for destination account

client = boto3.client(
        "ec2",
        region_name = destinationAccount['Region'],
        aws_access_key_id=destinationAccount['AccessKey'],
        aws_secret_access_key=destinationAccount['SecretKey']
        )

# create a new security group in the destination account

groupId = client.create_security_group(
        Description='security-group-from-{}'.format(sourceAccount['Region']),
        GroupName='security-group-from-{}'.format(sourceAccount['Region'])
        )["GroupId"]

# removed all egress rules from newly created security group

clearEgress = client.describe_security_groups(
        GroupIds=[groupId]
        )["SecurityGroups"][0]["IpPermissionsEgress"]

client.revoke_security_group_egress(
        GroupId=groupId,
        IpPermissions=clearEgress
        ) 

# create ingress and egress rules for the newly created security group   

client.authorize_security_group_ingress(
        GroupId=groupId,
        IpPermissions=ingress
        )
client.authorize_security_group_egress(
        GroupId=groupId,
        IpPermissions=egress
        )</font><br></pre>
<p class="MsoNormal"><span style="font-family: &quot;Amazon Ember&quot;; color: rgb(22, 25, 31); background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial;"><br></span></p>

*I have structured the above in an easy to view and edit dictionary format. These are the only updates that will be needed to be performed on this script.*
>> For the record, it is not advised to hard code access keys into our scripts as this can be a security risk if the script is accidentally exposed however, in this case, I just wanted to show the main principle of what needed to be done.<br>

Created an example of your particular needs using the [**Python Boto3 SDK for AWS**](https://aws.amazon.com/sdk-for-python/) which you can find with attached script named [**"CopySGFromOneAWSAccountToAnotherScript.py"**](https://github.com/dineshrathee12/CopySecurityGroupWithRulesFromOneAWSAccountToAnotherAWSAccount/blob/main/CopySGFromOneAWSAccountToAnotherScript.py)<br>

Once you have executed this script, it will perform the following functions in this order:<br>
------------------------------------------------------------------

<ol type="a">
<li> describe the security group rule you would like to copy in the source account using the <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_security_groups"><b>describe_security_groups API call<b></a></li>
<li> from the response obtained, we store the ingress and egress rules into variables for future reference</li>
<li> we create a new security group in the destination account using the <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.create_security_group"><b>create_security_group API call</b></a></li>
<li> remove all egress rules from the newly created security group using the <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.revoke_security_group_egress"><b>revoke_security_group_egress API call</b></a></li>
<li> add the egress and ingress rules to the new security group using the API calls <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.authorize_security_group_ingress"><b>authorize_security_group_ingress</b></a> and <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.authorize_security_group_egress"><b>authorize_security_group_egress</b></a></li>
</ol>


![Security Group with Rules Copied to another Account](https://media.giphy.com/media/11kcEW8uNh8RwY/giphy.gif)

**References**
- [**Script - CopySGFromOneAWSAccountToAnotherScript.py**](https://github.com/dineshrathee12/CopySecurityGroupWithRulesFromOneAWSAccountToAnotherAWSAccount/blob/main/CopySGFromOneAWSAccountToAnotherScript.py)<br>

<b>Thanks for reading.<b>
Any feedback, please write it to me here in comments..
<b>Also, 🤝🤗You can connect with us 🤝🤗</b>
<ul>
<li><b><a href="https://www.linkedin.com/in/dineshrathee12/" target="_blank">LinkedIn</a></li>
<li><b><a href="https://dev.to/dineshrathee12" target="_blank">DevTo</a></li>
<li><b><a href="https://github.com/dineshrathee12" target="_blank">GitHub</a></li>
<li><b><a href="https://twitter.com/dinesh_rathee12" target="_blank">Twitter</a></li>
</ul>

**Script Credits - Nikheel Soni**
<ul>
<li><b><a href="https://www.linkedin.com/in/nikheelsoni/" target="_blank">Nikheel's LinkedIn</a></li>
<li><b><a href="https://www.facebook.com/IonicSONIK" target="_blank">Nikheel's Facebook</a></li>
<li><b><a href="https://twitter.com/ionicsonik" target="_blank">Nikheel's Twitter</a></li>
</ul>

𝗜𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗡𝗼𝘁𝗲:  📝𝗢𝗽𝗶𝗻𝗶𝗼𝗻𝘀 𝗮𝗿𝗲 𝗺𝘆 𝗼𝘄𝗻 🏁🙂 𝗔𝗻𝗱 𝗶𝘁 𝗶𝘀 𝗺𝘆 𝗽𝗲𝗿𝘀𝗼𝗻𝗮𝗹 𝗯𝗹𝗼𝗴.