How can I copy existing Lightsail firewall rules to different Lightsail instances?

Last updated: 2021-09-28

How do I copy firewall rules to multiple Amazon Lightsail instances?

Short description

Firewall rules are unique to each Lightsail instance. If you want multiple instances to have the same rules, you must edit the rules for each of the instances. You can use the AWS Command Line Interface (AWS CLI) and API calls to retrieve the current firewall rules, and then output them into a .json file. You can use the .json file to copy all the rules into another Lightsail instance.

Note: You must install and configure the AWS CLI to perform the following resolution steps. If you receive errors when running AWS CLI commands, make sure that you’re using the most recent version of the AWS CLI. You can also use AWS CloudShell to perform these steps.

Resolution

1.    Run the following command to retrieve the current configurations you want to copy from the existing instance, and then output it to a .json file. This generates a .json file containing the firewall configuration. In the following example, replace SourceInstanceName and RegionName with the correct information for your instance.

$ aws lightsail get-instance-port-states --instance-name SourceInstanceName --region RegionName | grep -v "state" > firewall.json

2.    Open the .json file, firewall.json in this example, and then replace "portStates" with "portInfos". This parameter is at the beginning of the file, as shown in the following example:

{
    "portStates": [
        {
            "fromPort": 80,
            "toPort": 80,
            "protocol": "tcp",
            "cidrs": [
                "0.0.0.0/0"
            ],
            "cidrListAliases": []
        },
        {
            "fromPort": 22,
            "toPort": 22,
            "protocol": "tcp",
            "cidrs": [
                "0.0.0.0/0"
            ],
            "cidrListAliases": []
        },
        {
            "fromPort": 8080,
            "toPort": 8080,
            "protocol": "tcp",
            "cidrs": [
                "11.11.11.0/20",
                "22.22.22.0/20"
            ],
            "cidrListAliases": []
        }
    ]
}

3.    After changing the parameter to "portInfos", you can use the .json file to add the same configurations to other instances. In the following example, replace DestinationInstanceName, firewall.json, and RegionName with the correct information for your instance.

$ aws lightsail put-instance-public-ports --instance-name DestinationInstanceName  --cli-input-json file://firewall.json --region 
RegionName